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
67579e585b0ed0abda5a0dc85c1db73684b5cdea
795
swift
Swift
Sources/StinkyKeyboard/KeyboardObserver.swift
lucamegh/StinkyKeyboard
f35ee2ba0fe539112a727c39a62c3e53a1707b88
[ "MIT" ]
null
null
null
Sources/StinkyKeyboard/KeyboardObserver.swift
lucamegh/StinkyKeyboard
f35ee2ba0fe539112a727c39a62c3e53a1707b88
[ "MIT" ]
null
null
null
Sources/StinkyKeyboard/KeyboardObserver.swift
lucamegh/StinkyKeyboard
f35ee2ba0fe539112a727c39a62c3e53a1707b88
[ "MIT" ]
null
null
null
/** * StinkyKeyboard * Copyright (c) Luca Meghnagi 2021 * MIT license, see LICENSE file for details */ import Combine import UIKit class KeyboardObserver { private var cancellables = Set<AnyCancellable>() func observe(_ handler: @escaping (Keyboard) -> Void) { NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification) .map(Keyboard.init) .sink(receiveValue: handler) .store(in: &cancellables) NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification) .map { notification in Keyboard(height: 0, animation: notification.keyboardAnimation) } .sink(receiveValue: handler) .store(in: &cancellables) } }
29.444444
91
0.651572
5253dd36e271354d2367e644fea22d9b4b975fac
934
rb
Ruby
lib/back_test/strategy/cbpb_days.rb
Traver1/sok
96d91d278b7e36d59e397456672ebf235318adf2
[ "MIT" ]
null
null
null
lib/back_test/strategy/cbpb_days.rb
Traver1/sok
96d91d278b7e36d59e397456672ebf235318adf2
[ "MIT" ]
null
null
null
lib/back_test/strategy/cbpb_days.rb
Traver1/sok
96d91d278b7e36d59e397456672ebf235318adf2
[ "MIT" ]
1
2020-03-31T13:16:31.000Z
2020-03-31T13:16:31.000Z
module Kabu class CbPbDays attr_accessor :n, :length def initialize @length = 27 end def set_env(soks, env) env[:soks] = soks end def decide(env) code = env[:code] date = env[:date] soks = env[:soks] position = env[:position] highs = soks[-27..-2].high(20) is_high = false highs.zip(soks[-8..-2]).each do |high,sok| next if high != sok.high is_high = true break end lows = soks[-6..-2].low(5) is_low = lows[-1] == soks[-2].low if not position.nil? if position.term >= @n return Action::Sell.new(code, date, soks[-1].open,1) else return Action::None.new(code, soks[-1].open) end end if is_high and is_low Action::Buy.new(code, date, soks[-1].open,1) else Action::None.new(code, soks[-1].open) end end end end
19.87234
62
0.522484
2bc5d8f76111bc738375eb096ff28b582e1b894d
434
cs
C#
src/Zenseless.ExampleFramework/SolutionAttribute.cs
danielscherzer/Zenseless
c17555d9017bbc364b7bdafeb5a4c8ee23a014db
[ "Apache-2.0" ]
9
2018-01-07T19:57:48.000Z
2022-01-30T12:09:52.000Z
src/Zenseless.ExampleFramework/SolutionAttribute.cs
danielscherzer/Zenseless
c17555d9017bbc364b7bdafeb5a4c8ee23a014db
[ "Apache-2.0" ]
null
null
null
src/Zenseless.ExampleFramework/SolutionAttribute.cs
danielscherzer/Zenseless
c17555d9017bbc364b7bdafeb5a4c8ee23a014db
[ "Apache-2.0" ]
5
2018-11-03T01:03:39.000Z
2019-11-12T18:23:52.000Z
using System; using System.Runtime.InteropServices; namespace Zenseless.ExampleFramework { /// <summary> /// Defines an attribute that is used by Zenseless to detect if SOLUTION is defined. /// Solution code is removed upon template generation /// </summary> /// <seealso cref="Attribute" /> [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] [ComVisible(true)] public class SolutionAttribute : Attribute { } }
27.125
85
0.746544
581e3643fedd1260e0f1ad855ee6aee4329a190d
4,796
css
CSS
frontend/web/stylesheets/calendar.css
sbeka/abna-alux
d5ab531fc0f1aa52b57767beb6d8fb41990f7c40
[ "BSD-3-Clause" ]
null
null
null
frontend/web/stylesheets/calendar.css
sbeka/abna-alux
d5ab531fc0f1aa52b57767beb6d8fb41990f7c40
[ "BSD-3-Clause" ]
null
null
null
frontend/web/stylesheets/calendar.css
sbeka/abna-alux
d5ab531fc0f1aa52b57767beb6d8fb41990f7c40
[ "BSD-3-Clause" ]
null
null
null
#calendar2 + .filter { padding: 0 13px; } #calendar3, #calendar2 { width: 100%; font: monospace; line-height: 1.2em; font-size: 15px; text-align: center; height: 350px; } #calendar3 { } #calendar2 thead tr:last-child { font-size: small; color: rgb(85, 85, 85); } #calendar3 thead tr:nth-child(1) td { color: #fff; font-family: "MontserratExtrabold"; font-size: 17px; line-height: 30px; text-align: center; } #calendar2 thead tr:nth-child(1) td:nth-child(1) { padding-right: 5px; text-align: right; font-size: 35px; line-height: 30px; color: #8b8b8a; } #calendar2 thead tr:nth-child(1) td:nth-child(3) { padding-left: 5px; text-align: left; font-size: 35px; line-height: 30px; color: #8b8b8a; } #calendar2 thead tr:nth-child(1) td:nth-child(2) { color: #fff; font-family: "MontserratExtrabold"; font-size: 22px; line-height: 30px; padding-bottom: 20px; padding-top: 10px; } #calendar2 thead tr:nth-child(1) td:nth-child(1):hover, #calendar2 thead tr:nth-child(1) td:nth-child(3):hover { cursor: pointer; } #calendar2 tbody td { color: rgb(44, 86, 122); height: 10px; padding: 10px; position: relative; } #calendar2 tbody td:nth-child(n+6), #calendar2 .holiday { color: rgb(231, 140, 92); } #calendar2 tbody td.today { color: #fff; } #calendar2 tbody td.today span { background: #f48f00; border-radius: 100%; height: 18px; width: 18px; position: absolute; display: block; padding: 6px; left: 3px; top: 3px; font-size: 16px; } #calendar3 tbody td.event { background-color: rgba(244, 143, 0, 0.3); } #calendar3 tbody td { border: none; position: relative; width: 14%; height: 64px; display: table-cell; vertical-align: middle; color: #ffffff; } #calendar3 tbody td:hover { background: #F5BD5C; color: #000; cursor: pointer; } #calendar3 tbody td > span { font-family: "MontserratBold"; font-size: 20px; } #calendar3 tbody td.event { } #calendar3 tbody td.event label { float: left; padding-left: 10px; border-left: 2px solid red; font-size: 14px; text-align: left; } @media only screen and (max-width : 767px) { #calendar3 tbody td.event .more { min-width: 150px; } #calendar3 tbody td > span { font-size: 14px; } #calendar3 tbody td.event label { overflow: hidden; text-overflow: ellipsis; border-left: 1px solid red; padding-left: 5px; max-width: 45px; } } #calendar3 tbody td.event .more { display: none; position: absolute; z-index: 999; top: 100%; left: 0; padding: 10px; box-shadow: 4px 4px 10px #999; box-sizing: border-box; width: 150%; background-color: #ebebeb; } #calendar3 tbody td.event .more > * { clear: both; display: block; text-align: left; font-size: 14px; padding: 0 5px; margin-bottom: 5px; } #calendar3 tbody td.event .more > span { color: #f48f00; } #calendar3 tbody td.event .more:hover, #calendar3 tbody td.event:hover .more { display: block; } #calendar3 tbody tr:first-child td { } #calendar3 tbody tr td:last-child { } #calendar-events-box { padding: 0px 20px; font-family: "MontserratBold"; box-shadow: 0 0 10px rgba(197, 197, 197, 0.5); height: 284px; overflow: scroll; } .event-item { padding: 25px 0; border-bottom: 1px solid #ccc; } .event-item:last-child { border-bottom: none; } .event-date { float: left; padding-top: 15px; width: 50px; height: 50px; border-radius: 10px; background: #64769F; display: inline-block; color: #fff; text-align: center; } .event-date h1 { margin: 0; font-weight: bold; font-size: 20px; line-height: 5px; } .event-date span { font-size: 10px; } .event-title { margin-left: 60px; margin-right: 80px; } .event-title a { font-family: "MontserratBold"; color: #11244E; font-size: 16px; text-transform: uppercase; font-weight: bold; line-height: 20px; } .event-title a:hover { color: #F5BD5C; text-decoration: underline; } .event-time table td, .event-time table { padding: 0; margin: 0; //border: 1px solid black; } .event-time { float: right; display: inline-block; } .event-time .hour, .event-time .minute, .event-time .type { font-family: "MontserratRegular"; display: block; } .event-time .hour { font-size: 40px; color: #F5BD5C; margin-right: 10px; line-height: 30px; } .event-time .minute { font-size: 20px; color: #F5BD5C; line-height: 20px; } .event-time .type { line-height: 20px; font-size: 16px; color: #A6AAB4; text-transform: uppercase; } .clear { clear: both; }
23.057692
144
0.623019
a3703f311b29fa9032040508a63efe4c35a16cca
868
java
Java
app/src/main/java/com/androworld/videoeditorpro/Helper.java
vimalcvs/Video-Editor-pro
c504b024e7a445e6113edc1990aa6b09ca9f2a69
[ "Apache-2.0" ]
2
2020-08-11T18:37:54.000Z
2020-11-21T09:20:49.000Z
app/src/main/java/com/androworld/videoeditorpro/Helper.java
vimalcvs/Video-Editor-pro
c504b024e7a445e6113edc1990aa6b09ca9f2a69
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/androworld/videoeditorpro/Helper.java
vimalcvs/Video-Editor-pro
c504b024e7a445e6113edc1990aa6b09ca9f2a69
[ "Apache-2.0" ]
3
2020-08-11T18:37:56.000Z
2021-05-16T14:25:18.000Z
package com.androworld.videoeditorpro; import android.graphics.Typeface; public class Helper { public static String FontStyle = "AVENIRLTSTD-MEDIUM.OTF"; public static int ModuleId = 0; public static String account_string = "https://play.google.com/store/apps/developer?id=androworld"; public static String app_name = "Video Editor With Music"; public static String audioname = null; public static String audiopath = null; public static String audiopath1 = null; public static String package_name = "https://play.google.com/store/apps/details?id=com.androworld.videoeditorpro"; public static String share_string = "Hey!Check Out Video Editor With Music app is Professional Video Editing tool for your daily needs with most useful and handy Features to edit your video within minutes.!!!"; public static Typeface txtface; }
43.4
214
0.760369
832b90c13336a465b41ca48fa8aec0eb1b26f1d5
4,953
tsx
TypeScript
app/packages/app/src/components/Actions/Options.tsx
williamcorsel/fiftyone
22e34e91deb1d2e2fe6316ec81714e0c55015523
[ "Apache-2.0" ]
null
null
null
app/packages/app/src/components/Actions/Options.tsx
williamcorsel/fiftyone
22e34e91deb1d2e2fe6316ec81714e0c55015523
[ "Apache-2.0" ]
null
null
null
app/packages/app/src/components/Actions/Options.tsx
williamcorsel/fiftyone
22e34e91deb1d2e2fe6316ec81714e0c55015523
[ "Apache-2.0" ]
null
null
null
import { Autorenew, OpacityRounded } from "@material-ui/icons"; import React from "react"; import { constSelector, useRecoilState, useRecoilValue } from "recoil"; import * as atoms from "../../recoil/atoms"; import * as selectors from "../../recoil/selectors"; import Checkbox from "../Common/Checkbox"; import { PopoutSectionTitle, TabOption } from "../utils"; import { Button } from "../FieldsSidebar"; import Popout from "./Popout"; import { Slider } from "../Filters/RangeSlider"; import { useTheme } from "../../utils/hooks"; export const RefreshButton = ({ modal }) => { const [colorSeed, setColorSeed] = useRecoilState( atoms.colorSeed(Boolean(modal)) ); return ( <> <Button text={ <span style={{ display: "flex", justifyContent: "center" }}> Refresh colors{" "} <Autorenew style={{ marginLeft: "0.25rem", color: "inherit", }} /> </span> } title={"Refresh colors"} onClick={() => setColorSeed(colorSeed + 1)} style={{ margin: "0.25rem -0.5rem", height: "2rem", borderRadius: 0, textAlign: "center", }} ></Button> </> ); }; const ColorBy = ({ modal }) => { const [colorBy, setColorBy] = useRecoilState<string>( selectors.appConfigOption({ modal, key: "color_by" }) ); return ( <> <PopoutSectionTitle>Color by</PopoutSectionTitle> <TabOption active={colorBy} options={["field", "instance", "label"].map((value) => { return { text: value, title: `Color by ${value}`, onClick: () => colorBy !== value && setColorBy(value), }; })} /> </> ); }; const Keypoints = ({ modal }) => { const [shown, setShown] = useRecoilState<boolean>( selectors.appConfigOption({ key: "show_skeletons", modal }) ); const [points, setPoints] = useRecoilState<boolean>( selectors.appConfigOption({ key: "multicolor_keypoints", modal }) ); return ( <> <Checkbox name={"Multicolor keypoints"} value={points} setValue={(value) => setPoints(value)} /> <Checkbox name={"Show keypoint skeletons"} value={shown} setValue={(value) => setShown(value)} /> </> ); }; const Opacity = ({ modal }) => { const theme = useTheme(); const [alpha, setAlpha] = useRecoilState(atoms.alpha(modal)); return ( <> <PopoutSectionTitle style={{ display: "flex", height: 33 }}> <span>Label opacity</span> {alpha !== atoms.DEFAULT_ALPHA && ( <span onClick={() => setAlpha(atoms.DEFAULT_ALPHA)} style={{ cursor: "pointer", margin: "0.25rem" }} title={"Reset label opacity"} > <OpacityRounded /> </span> )} </PopoutSectionTitle> <Slider valueAtom={atoms.alpha(modal)} boundsAtom={constSelector([0, 1])} color={theme.brand} showBounds={false} persistValue={false} showValue={false} onChange={true} style={{ padding: 0 }} int={false} /> </> ); }; const SortFilterResults = ({ modal }) => { const [{ count, asc }, setSortFilterResults] = useRecoilState( atoms.sortFilterResults(modal) ); return ( <> <PopoutSectionTitle>Sort sidebar contents by</PopoutSectionTitle> <TabOption active={count ? "count" : "value"} options={[ { text: "count", title: "Sort by count", onClick: () => !count && setSortFilterResults({ count: true, asc }), }, { text: "value", title: "Sort by value", onClick: () => count && setSortFilterResults({ count: false, asc }), }, ]} /> <Checkbox name={"Reverse"} value={!asc} setValue={(value) => setSortFilterResults({ count, asc: !value })} /> </> ); }; const Patches = ({ modal }) => { const isPatches = useRecoilValue(selectors.isPatchesView); const [crop, setCrop] = useRecoilState(atoms.cropToContent(modal)); if (!isPatches) { return null; } return ( <> <PopoutSectionTitle>Patches</PopoutSectionTitle> <Checkbox name={"Crop to patch"} value={crop} setValue={(value) => setCrop(value)} /> </> ); }; type OptionsProps = { modal: boolean; }; const Options = ({ modal, bounds }: OptionsProps) => { return ( <Popout modal={modal} bounds={bounds}> <ColorBy modal={modal} /> <RefreshButton modal={modal} /> <Opacity modal={modal} /> <SortFilterResults modal={modal} /> <Keypoints modal={modal} /> <Patches modal={modal} /> </Popout> ); }; export default React.memo(Options);
25.015152
80
0.538663
fd9d27739c7f8a59a573f7f9a08b5ffb25fcebe4
514
css
CSS
index.css
eKhattak/graphcs-gen
7f3294735750d96d5b74e359e7587df76de4b9c6
[ "MIT" ]
1
2020-09-23T15:00:23.000Z
2020-09-23T15:00:23.000Z
index.css
khattakdev/graphcs-gen
7f3294735750d96d5b74e359e7587df76de4b9c6
[ "MIT" ]
null
null
null
index.css
khattakdev/graphcs-gen
7f3294735750d96d5b74e359e7587df76de4b9c6
[ "MIT" ]
null
null
null
.square { height: 60px; width: 60px; position: absolute; transform: translate(-50%, -50%); background: salmon; } .pentagon { position: absolute; transform: translate(-50%, -50%); width: 54px; box-sizing: content-box; border-width: 50px 18px 0; border-style: solid; border-color: salmon transparent; } .pentagon:before { content: ""; position: absolute; top: -85px; left: -18px; border-width: 0 45px 35px; border-style: solid; border-color: transparent transparent salmon; }
18.357143
47
0.669261
8d6e52eb2fb302c4af6578cbf46cda61b153124b
10,994
js
JavaScript
public/js/validaFicha.js
Muhligeer/redesFinal
9b5a18bf6340b60160324381f794feee67e88fa8
[ "MIT" ]
null
null
null
public/js/validaFicha.js
Muhligeer/redesFinal
9b5a18bf6340b60160324381f794feee67e88fa8
[ "MIT" ]
null
null
null
public/js/validaFicha.js
Muhligeer/redesFinal
9b5a18bf6340b60160324381f794feee67e88fa8
[ "MIT" ]
null
null
null
function vercpf(cpf) { cpf = tirarMask(cpf); if (cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999") return false; add = 0; for (i = 0; i < 9; i ++) add += parseInt(cpf.charAt(i)) * (10 - i); rev = 11 - (add % 11); if (rev == 10 || rev == 11) rev = 0; if (rev != parseInt(cpf.charAt(9))) return false; add = 0; for (i = 0; i < 10; i ++) add += parseInt(cpf.charAt(i)) * (11 - i); rev = 11 - (add % 11); if (rev == 10 || rev == 11) rev = 0; if (rev != parseInt(cpf.charAt(10))) return false; return true; } function validaNome(nome) { if(nome.value == null || nome.value == ""){ document.getElementById("erro_nome").style.color = "red"; document.getElementById("erro_nome").innerText = "Nome é obrigatório"; } else{ document.getElementById("erro_nome").innerText = ''; } } function validaCPF(cpf) { if(cpf.value == null || cpf.value == ""){ document.getElementById("erro_cpf").style.color = "red"; document.getElementById("erro_cpf").innerText = "CPF é obrigatório"; } else{ document.getElementById("erro_cpf").innerText = ''; } } function validaRG(rg) { if(rg.value == null || rg.value == ""){ document.getElementById("erro_rg").style.color = "red"; document.getElementById("erro_rg").innerText = "RG é obrigatório"; } else{ document.getElementById("erro_rg").innerText = ''; } } function validaCelular(celular) { if(celular.value == null || celular.value == ""){ document.getElementById("erro_celular").style.color = "red"; document.getElementById("erro_celular").innerText = "Telefone é obrigatório"; } else{ document.getElementById("erro_celular").innerText = ''; } } function checkMail(mail) { var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/); if (typeof (mail) == "string") { if (er.test(mail)) { return true; } } else if (typeof (mail) == "object") { if (er.test(mail.value)) { return true; } } else { return false; } } function validaEmail(email) { if(email.value == null || email.value == ""){ document.getElementById('erro_email').style.color = "red"; document.getElementById('erro_email').innerText = 'Email é obrigatório'; }else{ if( !checkMail(email)) { document.getElementById('erro_email').style.color = "red"; document.getElementById('erro_email').innerText = 'Email incorreto'; }else{ document.getElementById('erro_email').innerText = ''; } } } function validaDepartamento(dpto) { if(dpto.value == null || dpto.value == ""){ document.getElementById("erro_dpto").style.color = "red"; document.getElementById("erro_dpto").innerText = "Departamento é obrigatório"; } else{ document.getElementById("erro_dpto").innerText = ''; } } function validaCargo(cargo) { if(cargo.value == null || cargo.value == ""){ document.getElementById("erro_cargo").style.color = "red"; document.getElementById("erro_cargo").innerText = "Cargo é obrigatório"; } else{ document.getElementById("erro_cargo").innerText = ''; } } function validaCEP(cep) { if(cep.value == null || cep.value == ""){ document.getElementById("erro_cep").style.color = "red"; document.getElementById("erro_cep").innerText = "CEP é obrigatório"; } else{ document.getElementById("erro_cep").innerText = ''; } } function validaBairro(bairro) { if(bairro.value == null || bairro.value == ""){ document.getElementById("erro_bairro").style.color = "red"; document.getElementById("erro_bairro").innerText = "Bairro é obrigatório"; } else{ document.getElementById("erro_bairro").innerText = ''; } } function validaRua(rua) { if(rua.value == null || rua.value == ""){ document.getElementById("erro_rua").style.color = "red"; document.getElementById("erro_rua").innerText = "Rua é obrigatório"; } else{ document.getElementById("erro_rua").innerText = ''; } } function validaNumero(numero) { if(numero.value == null || numero.value == ""){ document.getElementById("erro_numero").style.color = "red"; document.getElementById('erro_numero').innerText = 'Número é obrigatório.'; }else{ document.getElementById("erro_numero").innerText = ''; } } function tirarMascara() { var cpf = document.forms["formularioCadastroFuncionario"]["cpf"].value; var rg = document.forms["formularioCadastroFuncionario"]["rg"].value; var celular = document.forms["formularioCadastroFuncionario"]["celular"].value; var cep = document.forms["formularioCadastroFuncionario"]["cep"].value; cpf = tirarMask(cpf); rg = tirarMask(rg); celular = tirarMask(celular); cep = tirarMask(cep); document.forms["formularioCadastroFuncionario"]["cpf"].value = cpf; document.forms["formularioCadastroFuncionario"]["rg"].value = rg; document.forms["formularioCadastroFuncionario"]["celular"].value = celular; document.forms["formularioCadastroFuncionario"]["cep"].value = cep; } function tirarMask(v){ var pbd = v.replace('.', ''); pbd = pbd.replace('.',''); pbd = pbd.replace('-',''); pbd = pbd.replace(' ',''); pbd = pbd.replace('(',''); pbd = pbd.replace(')',''); return pbd; } function validaFormularioFuncionario() { var nome = document.forms["formularioCadastroFuncionario"]["nomeFuncionario"].value; var email = document.forms["formularioCadastroFuncionario"]["email"].value; var cpf = document.forms["formularioCadastroFuncionario"]["cpf"].value; var rg = document.forms["formularioCadastroFuncionario"]["rg"].value; var celular = document.forms["formularioCadastroFuncionario"]["celular"].value; var dpto = document.forms["formularioCadastroFuncionario"]["departamento"].value; var cargo = document.forms["formularioCadastroFuncionario"]["cargo"].value; var cep = document.forms["formularioCadastroFuncionario"]["cep"].value; var estado = document.forms["formularioCadastroFuncionario"]["nomeEstado"].value; var cidade = document.forms["formularioCadastroFuncionario"]["nomeCidade"].value; var bairro = document.forms["formularioCadastroFuncionario"]["bairro"].value; var rua = document.forms["formularioCadastroFuncionario"]["rua"].value; var numero = document.forms["formularioCadastroFuncionario"]["numero"].value; if (nome == null || nome == "") { document.getElementById("erro_nome").style.color = "red"; document.getElementById("erro_nome").innerText = "Nome é obrigatório"; return false; } if (cpf == null || cpf == "") { document.getElementById("erro_cpf").style.color = "red"; document.getElementById("erro_cpf").innerText = "CPF é obrigatório"; return false; } else { if (vercpf(cpf)==false) { document.getElementById("erro_cpf").style.color = "red"; document.getElementById("erro_cpf").innerText = "CPF Inválido"; return false; } } if (rg == null || rg == "") { document.getElementById("erro_rg").style.color = "red"; document.getElementById("erro_rg").innerText = "RG é obrigatório"; return false; } if (celular == null || celular == "") { document.getElementById("erro_celular").style.color = "red"; document.getElementById("erro_celular").innerText = "Telefone é obrigatório"; return false; } if (email == null || email == "") { document.getElementById('erro_email').style.color = "red"; document.getElementById('erro_email').innerText = 'Email é obrigatório'; return false; } else { if (!(checkMail(email))) { document.getElementById('erro_email').style.color = "red"; document.getElementById('erro_email').innerText = 'Email incorreto'; return false; } } if (dpto == null || dpto == "") { document.getElementById("erro_dpto").style.color = "red"; document.getElementById("erro_dpto").innerText = "Departamento é obrigatório"; return false; } if (cargo == null || cargo == "") { document.getElementById("erro_cargo").style.color = "red"; document.getElementById("erro_cargo").innerText = "Cargo é obrigatório"; return false; } if (cep == null || cep == "") { document.getElementById("erro_cep").style.color = "red"; document.getElementById("erro_cep").innerText = "CEP é obrigatório"; return false; } if (estado == null || estado == "") { document.getElementById("erro_estado").style.color = "red"; document.getElementById("erro_estado").innerText = "Estado é obrigatório"; return false; } if (cidade == null || cidade == "") { document.getElementById("erro_cidade").style.color = "red"; document.getElementById("erro_cidade").innerText = "Cidade é obrigatório"; return false; } if (bairro == null || bairro == "") { document.getElementById("erro_bairro").style.color = "red"; document.getElementById("erro_bairro").innerText = "Bairro é obrigatório"; return false; } if (rua == null || rua == "") { document.getElementById("erro_rua").style.color = "red"; document.getElementById("erro_rua").innerText = "Rua é obrigatório"; return false; } if (numero == null || numero == "") { document.getElementById('erro_numero').style.color = "red"; document.getElementById('erro_numero').innerHTML = 'Numero incorreto'; return false; } return true; }
35.012739
265
0.567037
583a2074d30f8b89f26afcbf51af6bbbc7f2fb2c
740
css
CSS
src/app/components/Question/question.css
ohtu-aikavali2/aikavali2-front
921ece59fdef2713140d619752da2a9aa9d2a75f
[ "MIT" ]
null
null
null
src/app/components/Question/question.css
ohtu-aikavali2/aikavali2-front
921ece59fdef2713140d619752da2a9aa9d2a75f
[ "MIT" ]
null
null
null
src/app/components/Question/question.css
ohtu-aikavali2/aikavali2-front
921ece59fdef2713140d619752da2a9aa9d2a75f
[ "MIT" ]
null
null
null
.questionContainer { height: 100%; display: flex; flex-direction: column; margin: 0 20px 0 20px; } .titleContainer { padding-left: 10px; padding-right: 10px; padding-bottom: 40px; display: block; text-align: center; overflow-wrap: break-word; justify-content: center; } .dragAndDropQuestion { text-align: center; } .fillInQuestion { margin-bottom: 70px; padding-bottom: 10px; } .rowContainer { font-size: 16px; } .likertScale { display: flex; justify-content: center; font-size: 50px; cursor: pointer; } .answerLoading { position: absolute; bottom: 10px; left: 0; right: 0; margin: 0 20px 0 20px; } @media only screen and (max-width: 700px) { .itemGrid { font-size: 2.5vw; } }
14.8
43
0.663514
dee2b58dd7923c86e6a62af8031f428ac76c0105
26,084
rs
Rust
pallets/did/src/lib.rs
JAMBO-NETWORK/substrate-node
2aa6c13ebf8e436efd25e8cc5c345701cf798175
[ "MIT" ]
2
2021-03-27T23:59:52.000Z
2021-03-28T00:00:13.000Z
pallets/did/src/lib.rs
JAMBO-NETWORK/substrate-node
2aa6c13ebf8e436efd25e8cc5c345701cf798175
[ "MIT" ]
null
null
null
pallets/did/src/lib.rs
JAMBO-NETWORK/substrate-node
2aa6c13ebf8e436efd25e8cc5c345701cf798175
[ "MIT" ]
null
null
null
#![cfg_attr(not(feature = "std"), no_std)] mod check; mod harsh; mod tests; use codec::{Decode, Encode}; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, ensure, traits::{Currency, ExistenceRequirement, ReservableCurrency}, weights::Weight, }; use frame_system::{ensure_root, ensure_signed}; use harsh::HarshBuilder; use sp_io::hashing::blake2_256; use sp_runtime::{ traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, Hash, SaturatedConversion, Zero}, DispatchResult, Permill, RuntimeDebug, }; use sp_std::vec::Vec; pub trait Config: pallet_balances::Config + pallet_timestamp::Config { type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>; } pub type Did = Vec<u8>; #[derive(Encode, Decode, Default, Clone, PartialEq, RuntimeDebug)] pub struct ExternalAddress { btc: Vec<u8>, eth: Vec<u8>, eos: Vec<u8>, } #[derive(Encode, Decode, Default, Clone, PartialEq, RuntimeDebug)] pub struct LockedRecords<Balance, Moment> { locked_time: Moment, locked_period: Moment, locked_funds: Balance, rewards_ratio: u64, max_quota: u64, } #[derive(Encode, Decode, Default, Clone, PartialEq, RuntimeDebug)] pub struct UnlockedRecords<Balance, Moment> { unlocked_time: Moment, unlocked_funds: Balance, } #[derive(Encode, Decode, Default, Clone, PartialEq, RuntimeDebug)] pub struct MetadataRecord<AccountId, Hash, Balance, Moment> { address: AccountId, superior: Hash, creator: AccountId, did: Did, locked_records: Option<LockedRecords<Balance, Moment>>, unlocked_records: Option<UnlockedRecords<Balance, Moment>>, donate: Option<Balance>, social_account: Option<Hash>, subordinate_count: u64, group_name: Option<Vec<u8>>, external_address: ExternalAddress, } #[derive(Encode, Decode, Default, Clone, PartialEq, RuntimeDebug)] pub struct OldMetadataRecord<AccountId, Hash, Balance, Moment> { address: AccountId, superior: Hash, creator: AccountId, did: Did, locked_records: Option<LockedRecords<Balance, Moment>>, unlocked_records: Option<UnlockedRecords<Balance, Moment>>, is_partner: bool, social_account: Option<Hash>, subordinate_count: u64, group_name: Option<Vec<u8>>, external_address: ExternalAddress, } decl_error! { pub enum Error for Module<T: Config> { /// invlid type InvalidType, /// did does not exist DidNotExists, /// did already exists DidExists, /// social account has been bound SocialAccountBound, /// the superior does not exsit SuperiorNotExists, /// number overflow Overflow, /// not lock funds NotLockFunds, /// subordinate exceeds max quota ExceedsMaxQuota, /// public key has been taken PublicKeyUsed, /// dont have enough free balance NotEnoughBalance, /// lock at least 10 prm first time LockNotFulfilled, /// unreserved funds UnreservedFundsExceed, /// unlock time has not reached UnlockTimeNotReach, /// invlid address InvalidAddressFormat, /// group name is too long InvalidGroupName, /// you are not eligible to set group name NotEligible, /// Can't send money to yourself SentToSelf, } } decl_storage! { trait Store for Module<T: Config> as DidModule { pub GenesisAccount get(fn genesis_account) config(): T::AccountId; pub BaseQuota get(fn base_quota) config(): u64; pub MinDeposit get(fn min_deposit) config(): T::Balance; pub FeeToPrevious get(fn fee_to_previous) config(): T::Balance; pub Identity get(fn identity): map hasher(twox_64_concat) T::AccountId => Option<(T::Hash, Did)>; pub IdentityOf get(fn identity_of): map hasher(twox_64_concat) T::Hash => Option<T::AccountId>; pub SocialAccount get(fn social_account): map hasher(twox_64_concat) T::Hash => T::Hash; pub Metadata get(fn metadata): map hasher(twox_64_concat) T::Hash => MetadataRecord<T::AccountId, T::Hash, T::Balance, T::Moment>; pub AllDidCount get(fn all_did_count): u64; pub UserKeys get(fn key_by_index): map hasher(twox_64_concat) T::Hash => T::Hash; pub DidIndices get(fn index_by_key) : map hasher(twox_64_concat) T::Hash => Vec<u8>; } } decl_event! { pub enum Event<T> where <T as frame_system::Config>::AccountId, <T as pallet_balances::Config>::Balance, <T as pallet_timestamp::Config>::Moment, { Created(Did, Vec<u8>, Did), Updated(Did, AccountId, Balance), Locked(Did, Balance, Moment, Moment, u64, u64), Unlocked(Did, Balance, Moment), Transfered(Did, Did, Balance, Vec<u8>), AddressAdded(Did, Vec<u8>, Vec<u8>), GroupNameSet(Did, Vec<u8>), } } decl_module! { pub struct Module<T: Config> for enum Call where origin: T::Origin { type Error = Error<T>; fn deposit_event() = default; fn on_runtime_upgrade() -> Weight { // Self::migrate(); 0 } #[weight = 0] pub fn create(origin, pubkey: Vec<u8>, address: T::AccountId, did_type: Vec<u8>, superior: T::Hash, social_account: Option<Vec<u8>>, social_superior: Option<Vec<u8>>) { let sender = ensure_signed(origin)?; let did = Self::generate_did(&pubkey, &did_type); let user_key = T::Hashing::hash(&did); // make sure the did is new ensure!(!<Metadata<T>>::contains_key(&user_key), Error::<T>::DidExists); ensure!(!<Identity<T>>::contains_key(&address), Error::<T>::DidExists); let mut superior_key = superior; let mut social_account_hash = None; if let Some(mut value) = social_account { // bind social account value.append(&mut did_type.to_vec()); let social_hash = T::Hashing::hash(&value); social_account_hash = Some(social_hash); // one social account only can bind one did ensure!(!<SocialAccount<T>>::contains_key(&social_hash), Error::<T>::SocialAccountBound); if let Some(mut value) = social_superior { value.append(&mut did_type.to_vec()); let superior_hash = T::Hashing::hash(&value); ensure!(<SocialAccount<T>>::contains_key(&superior_hash), Error::<T>::SuperiorNotExists); superior_key = Self::social_account(superior_hash); }; } let mut superior_did = Vec::new(); if <Metadata<T>>::contains_key(&superior_key) { let mut superior_metadata = Self::metadata(superior_key); if superior_metadata.address != Self::genesis_account() { let subordinate_count = superior_metadata.subordinate_count.checked_add(1).ok_or(Error::<T>::Overflow)?; ensure!(superior_metadata.locked_records.is_some(), Error::<T>::NotLockFunds); let locked_records = superior_metadata.locked_records.unwrap(); let LockedRecords { max_quota, .. } = locked_records; ensure!(subordinate_count <= max_quota, Error::<T>::ExceedsMaxQuota); superior_metadata.subordinate_count = subordinate_count; superior_metadata.locked_records = Some(locked_records); superior_did = superior_metadata.did.clone(); <Metadata<T>>::insert(&superior_key, superior_metadata); } } if social_account_hash.is_some() { let social_hash = social_account_hash.unwrap(); <SocialAccount<T>>::insert(social_hash, &user_key); } // update metadata let metadata = MetadataRecord { address: address.clone(), superior: superior_key, creator: sender.clone(), did: did.clone(), locked_records: None, social_account: social_account_hash, unlocked_records: None, donate: None, subordinate_count: 0, group_name: None, external_address: ExternalAddress { btc: Vec::new(), eth: Vec::new(), eos: Vec::new(), }, }; <Metadata<T>>::insert(&user_key, metadata); // update address => did <Identity<T>>::insert(&address, (&user_key, &did)); // update user_key => address <IdentityOf<T>>::insert(&user_key, &address); // update did count let all_did_count = Self::all_did_count(); let new_count = all_did_count.checked_add(1) .ok_or(Error::<T>::Overflow)?; <AllDidCount>::put(new_count); let harsher = HarshBuilder::new().salt("jambo did").length(6).init().unwrap(); let idx = harsher.encode(&[all_did_count]).unwrap(); let idx_hash = T::Hashing::hash(&idx); <UserKeys<T>>::insert(&idx_hash, &user_key); <DidIndices<T>>::insert(&user_key, idx); // broadcast event Self::deposit_event(RawEvent::Created(did, pubkey, superior_did)); } #[weight = 0] pub fn update(origin, to: T::AccountId) { let sender = ensure_signed(origin)?; // make sure did exists and new pubkey has not been bound let (user_key, did) = Self::identity(&sender).ok_or(Error::<T>::DidNotExists)?; ensure!(Self::identity(&to).is_none(), Error::<T>::PublicKeyUsed); let money = <pallet_balances::Module<T>>::free_balance(&sender); <pallet_balances::Module<T> as Currency<_>>::transfer(&sender, &to, money, ExistenceRequirement::AllowDeath,)?; // update address => did map <Identity<T>>::remove(&sender); <Identity<T>>::insert(&to, (&user_key, &did)); // update user_key => address <IdentityOf<T>>::insert(user_key, &to); let mut metadata = Self::metadata(&user_key); metadata.address = to.clone(); <Metadata<T>>::insert(user_key, metadata); Self::deposit_event(RawEvent::Updated(did, to, money)); } #[weight = 0] pub fn transfer(origin, to_user: T::Hash, value: T::Balance, memo: Vec<u8>) { let sender = ensure_signed(origin)?; let (from_user, _) = Self::identity(sender).ok_or(Error::<T>::DidNotExists)?; Self::transfer_by_did(from_user, to_user, value, memo)?; } #[weight = 0] pub fn lock(origin, value: T::Balance, period: T::Moment) { let sender = ensure_signed(origin)?; let sender_balance = <pallet_balances::Module<T>>::free_balance(sender.clone()); ensure!(sender_balance >= value, Error::<T>::NotEnoughBalance); let (user_key, did) = Self::identity(&sender).ok_or(Error::<T>::DidNotExists)?; let mut metadata = Self::metadata(&user_key); // make sure the superior exists ensure!(<Metadata<T>>::contains_key(metadata.superior), Error::<T>::SuperiorNotExists); let level2_metadata = Self::metadata(metadata.superior); let locked_funds; let memo = "抵押分成".as_bytes().to_vec(); let mut rewards_ratio = 20;// basis rewards_ratio is 20% if metadata.donate.is_none() { ensure!(value >= Self::min_deposit(), Error::<T>::LockNotFulfilled); let mut rebate = value.checked_div(&2_u32.into()).ok_or(Error::<T>::Overflow)?; if rebate > Self::fee_to_previous() { rebate = Self::fee_to_previous(); } locked_funds = value - rebate; if level2_metadata.superior != Default::default() { let fee1 = Permill::from_percent(80) * rebate; let fee2 = Permill::from_percent(20) * rebate; Self::transfer_by_did(user_key, metadata.superior, fee1, memo.clone())?; Self::transfer_by_did(user_key, level2_metadata.superior, fee2, memo.clone())?; } else { Self::transfer_by_did(user_key, metadata.superior, rebate, memo)?; } <pallet_balances::Module<T>>::reserve(&sender, locked_funds)?; metadata.donate = Some(rebate); } else { let locked_records = metadata.locked_records.unwrap(); let mut donate = metadata.donate.unwrap(); let old_locked_funds = locked_records.locked_funds; let mut new_locked_funds = value; if donate >= Self::fee_to_previous() { // without rebate locked_funds = old_locked_funds + new_locked_funds; } else { // keeping rebate let lack = Self::fee_to_previous() .checked_sub(&donate) .and_then(|n| n.checked_mul(&2_u32.into())) .ok_or(Error::<T>::Overflow)?; let mut rebate = lack / 2_u32.into(); if new_locked_funds < lack { rebate = new_locked_funds / 2_u32.into(); } new_locked_funds = new_locked_funds.checked_sub(&rebate).ok_or(Error::<T>::Overflow)?; locked_funds = old_locked_funds.checked_add(&new_locked_funds).ok_or(Error::<T>::Overflow)?; if level2_metadata.superior != Default::default() { let part1 = Permill::from_percent(80) * rebate; let part2 = Permill::from_percent(20) * rebate; Self::transfer_by_did(user_key, metadata.superior, part1, memo.clone())?; Self::transfer_by_did(user_key, level2_metadata.superior, part2, memo.clone())?; } else { Self::transfer_by_did(user_key, metadata.superior, rebate, memo)?; } donate += rebate; } <pallet_balances::Module<T>>::reserve(&sender, new_locked_funds)?; metadata.donate = Some(donate); } let max_quota = Self::balance_to_u64(locked_funds) * 10; if max_quota >= metadata.subordinate_count { rewards_ratio = 20; }; let locked_time = <pallet_timestamp::Module<T>>::get(); metadata.locked_records = Some(LockedRecords { locked_funds, rewards_ratio, max_quota, locked_time, locked_period: period, }); <Metadata<T>>::insert(user_key, metadata); Self::deposit_event(RawEvent::Locked(did, locked_funds, locked_time, period, rewards_ratio, max_quota)); } #[weight = 0] pub fn force_lock(origin, user: T::Hash, value: T::Balance) { ensure_root(origin)?; ensure!(<Metadata<T>>::contains_key(&user), Error::<T>::DidNotExists); let mut metadata = Self::metadata(&user); let reserved_balance = <pallet_balances::Module<T>>::reserved_balance(&metadata.address); let locked_funds = reserved_balance + value; let donate = if locked_funds >= Self::fee_to_previous() { Self::fee_to_previous() } else { locked_funds }; <pallet_balances::Module<T>>::reserve(&metadata.address, value)?; let max_quota = Self::balance_to_u64(locked_funds) * 10; let rewards_ratio = 20; let locked_time = <pallet_timestamp::Module<T>>::get(); metadata.donate = Some(donate); metadata.locked_records = Some(LockedRecords { locked_funds, rewards_ratio, max_quota, locked_time, locked_period: Zero::zero(), }); <Metadata<T>>::insert(user, metadata); } #[weight = 0] pub fn unlock(origin, value: T::Balance) { let sender = ensure_signed(origin)?; let reserved_balance = <pallet_balances::Module<T>>::reserved_balance(&sender); ensure!(reserved_balance >= value, Error::<T>::UnreservedFundsExceed); let (user_key, did) = Self::identity(&sender).ok_or(Error::<T>::DidNotExists)?; let mut metadata = Self::metadata(&user_key); ensure!(metadata.locked_records.is_some(), Error::<T>::NotLockFunds); let mut locked_records = metadata.locked_records.unwrap(); let LockedRecords { locked_time, locked_period, locked_funds, .. } = locked_records; let now = <pallet_timestamp::Module<T>>::get(); let unlock_till_time = locked_time.checked_add(&locked_period).ok_or(Error::<T>::Overflow)?; ensure!(now >= unlock_till_time, Error::<T>::UnlockTimeNotReach); let unlocked_time = <pallet_timestamp::Module<T>>::get(); let unlocked_records = UnlockedRecords { unlocked_time, unlocked_funds: value, }; let new_locked_funds = locked_funds - value; let new_max_quota = Self::balance_to_u64(new_locked_funds) * 10; let rewards_ratio = if new_max_quota >= metadata.subordinate_count { 20 } else { 100 * (1 - new_max_quota / metadata.subordinate_count) as u64 }; locked_records = LockedRecords { locked_funds: new_locked_funds, rewards_ratio, max_quota: new_max_quota, .. locked_records }; metadata.unlocked_records = Some(unlocked_records); metadata.locked_records = Some(locked_records); <Metadata<T>>::insert(user_key, metadata); <pallet_balances::Module<T>>::unreserve(&sender, value); Self::deposit_event(RawEvent::Unlocked(did, value, unlocked_time)); } #[weight = 0] pub fn add_external_address(origin, add_type: Vec<u8>, address: Vec<u8>) { let sender = ensure_signed(origin)?; let (user_key, did) = Self::identity(&sender).ok_or(Error::<T>::DidNotExists)?; let mut metadata = Self::metadata(&user_key); let mut external_address = metadata.external_address; match &add_type[..] { b"btc" => { check::from(address.clone()).map_err(|_| Error::<T>::InvalidAddressFormat)?; external_address.btc = address.clone(); }, b"eth" => { ensure!(check::is_valid_eth_address(address.clone()), Error::<T>::InvalidAddressFormat); external_address.eth = address.clone(); }, b"eos" => { ensure!(check::is_valid_eos_address(address.clone()), Error::<T>::InvalidAddressFormat); external_address.eos = address.clone(); }, _ => Err(Error::<T>::InvalidType)?, }; metadata.external_address = external_address; <Metadata<T>>::insert(user_key, metadata); Self::deposit_event(RawEvent::AddressAdded(did, add_type, address)); } #[weight = 0] pub fn set_group_name(origin, name: Vec<u8>) { let sender = ensure_signed(origin)?; let (user_key, did) = Self::identity(&sender).ok_or(Error::<T>::DidNotExists)?; let mut metadata = Self::metadata(&user_key); ensure!(name.len() < 50, Error::<T>::InvalidGroupName); ensure!(metadata.locked_records.is_some(), Error::<T>::NotEligible); metadata.group_name = Some(name.clone()); <Metadata<T>>::insert(user_key, metadata); Self::deposit_event(RawEvent::GroupNameSet(did, name)); } #[weight = 0] fn judge(origin, account: T::AccountId) { let sender = ensure_signed(origin)?; if Self::genesis_account() == sender.clone() { let (user_key, _did) = Self::identity(&account).ok_or(Error::<T>::DidNotExists)?; let mut metadata = Self::metadata(&user_key); metadata.creator = account.clone(); <Metadata<T>>::insert(user_key, metadata); } } } } impl<T: Config> Module<T> { fn migrate() { use frame_support::{migration::StorageKeyIterator, Twox64Concat}; for ( who, OldMetadataRecord { address, superior, creator, did, locked_records, unlocked_records, is_partner, social_account, subordinate_count, group_name, external_address, }, ) in StorageKeyIterator::< T::Hash, OldMetadataRecord<T::AccountId, T::Hash, T::Balance, T::Moment>, Twox64Concat, >::new(b"Did", b"Metadata") .drain() { let donate = if is_partner { Some(Self::fee_to_previous()) } else { None }; let new_metadata = MetadataRecord { address, superior, creator, did, locked_records, unlocked_records, donate, social_account, subordinate_count, group_name, external_address, }; Metadata::<T>::insert(who, new_metadata) } } fn u128_to_balance(input: u128) -> T::Balance { input.saturated_into() } fn balance_to_u64(input: T::Balance) -> u64 { input.saturated_into::<u64>() } fn is_sub(mut haystack: &[u8], needle: &[u8]) -> bool { if needle.len() == 0 { return true; } while !haystack.is_empty() { if haystack.starts_with(needle) { return true; } haystack = &haystack[1..]; } false } fn generate_did(pubkey: &[u8], did_type: &[u8]) -> Vec<u8> { // 通过公钥生成hash值 let hash = blake2_256(pubkey); // did的类型 let did = did_type; let mut did = did.to_vec(); // 截取第一步生成的hash的前20位,将did类型附加在最前面 did.append(&mut hash[..20].to_vec()); // 将第二步生成的hash再次hash let ext_hash = blake2_256(&did[..]); // 截取第三步生成的hash的前4位,并附加到第二步生成的hash后面 did.append(&mut ext_hash[..4].to_vec()); did } } impl<T: Config> Module<T> { pub fn transfer_by_did( from_user: T::Hash, to_user: T::Hash, value: T::Balance, memo: Vec<u8>, ) -> DispatchResult { ensure!( <Metadata<T>>::contains_key(&to_user), Error::<T>::DidNotExists ); ensure!(from_user != to_user, Error::<T>::SentToSelf); // get sender balance and check let MetadataRecord { address: from_address, did: from_did, .. } = Self::metadata(&from_user); let sender_balance = <pallet_balances::Module<T>>::free_balance(&from_address); ensure!(sender_balance > value, Error::<T>::NotEnoughBalance); // get receiver balance let MetadataRecord { address: to_address, did: to_did, superior, .. } = Self::metadata(&to_user); let receiver_balance = <pallet_balances::Module<T>>::free_balance(&to_address); // check overflow sender_balance .checked_sub(&value) .ok_or(Error::<T>::Overflow)?; receiver_balance .checked_add(&value) .ok_or(Error::<T>::Overflow)?; // proceeds split let fee_type = b"ads"; if Self::is_sub(&memo, fee_type) { let superior_address = Self::identity_of(superior).ok_or(Error::<T>::SuperiorNotExists)?; let MetadataRecord { locked_records, .. } = Self::metadata(superior); let rewards_ratio = if locked_records.is_some() { locked_records.unwrap().rewards_ratio } else { 0 }; let fee_to_superior = value.clone() * Self::u128_to_balance(rewards_ratio.into()) / Self::u128_to_balance(100); let fee_to_user = value.clone() * Self::u128_to_balance((100 - rewards_ratio).into()) / Self::u128_to_balance(100); <pallet_balances::Module<T> as Currency<_>>::transfer( &from_address, &superior_address, fee_to_superior, ExistenceRequirement::AllowDeath, )?; <pallet_balances::Module<T> as Currency<_>>::transfer( &from_address, &to_address, fee_to_user, ExistenceRequirement::AllowDeath, )?; } else { <pallet_balances::Module<T> as Currency<_>>::transfer( &from_address, &to_address, value, ExistenceRequirement::AllowDeath, )?; } Self::deposit_event(RawEvent::Transfered(from_did, to_did, value, memo)); Ok(()) } }
36.738028
176
0.557085
a9e7cd9180540a44938cf3078bc53840b59840f8
1,750
php
PHP
app/Http/Middleware/CheckIP.php
thewhitewolf2411/bamboo_projec
a410546c600ff922305fcae9a09b233bf389d7bd
[ "MIT" ]
null
null
null
app/Http/Middleware/CheckIP.php
thewhitewolf2411/bamboo_projec
a410546c600ff922305fcae9a09b233bf389d7bd
[ "MIT" ]
7
2020-10-16T07:56:35.000Z
2021-11-15T11:28:48.000Z
app/Http/Middleware/CheckIP.php
thewhitewolf2411/bamboo_projec
a410546c600ff922305fcae9a09b233bf389d7bd
[ "MIT" ]
1
2021-01-08T13:52:44.000Z
2021-01-08T13:52:44.000Z
<?php namespace App\Http\Middleware; use App\Eloquent\WhitelistIP; use Closure; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\URL; class CheckIP { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { // disable middleware locally if(URL::to('/') === 'http://127.0.0.1:8000' || URL::to('/') === 'http://192.168.9.31:8000'){ return $next($request); } $ip = $request->ip(); $whitelisted = WhitelistIP::all()->pluck('ip')->toArray(); #dd($whitelisted, $ip, $request->ip()); if(in_array($ip, $whitelisted)){ return $next($request); } if(Auth::user()){ Auth::logout(); } return redirect('/')->with('blockedinfo', 'You are not authorized to login. Please contact your system administrator.'); } public function get_real_ip() { if (isset($_SERVER["HTTP_CLIENT_IP"])) { return $_SERVER["HTTP_CLIENT_IP"]; } elseif (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) { return $_SERVER["HTTP_X_FORWARDED_FOR"]; } elseif (isset($_SERVER["HTTP_X_FORWARDED"])) { return $_SERVER["HTTP_X_FORWARDED"]; } elseif (isset($_SERVER["HTTP_FORWARDED_FOR"])) { return $_SERVER["HTTP_FORWARDED_FOR"]; } elseif (isset($_SERVER["HTTP_FORWARDED"])) { return $_SERVER["HTTP_FORWARDED"]; } else { return $_SERVER["REMOTE_ADDR"]; } } }
25.362319
128
0.534286
a4ab3f5f3f0ef5874256988adb63a4860b08a2b5
2,087
php
PHP
src/Helpers/authcustomer_helper.php
adnduweb/ci4_ecommerce
6817d71866889c4617b68f321b84668130f31c40
[ "MIT" ]
1
2020-06-23T17:06:47.000Z
2020-06-23T17:06:47.000Z
src/Helpers/authcustomer_helper.php
adnduweb/ci4_ecommerce
6817d71866889c4617b68f321b84668130f31c40
[ "MIT" ]
null
null
null
src/Helpers/authcustomer_helper.php
adnduweb/ci4_ecommerce
6817d71866889c4617b68f321b84668130f31c40
[ "MIT" ]
4
2020-06-14T05:55:19.000Z
2021-10-06T04:11:46.000Z
<?php use Config\Services; if (!function_exists('customer_logged_in')) { /** * Checks to see if the user is logged in. * * * @return bool */ function customer_logged_in() { return Services::authenticationcustomer()->check(); } } if (!function_exists('customer')) { /** * Returns the customer instance for the current logged in customer. * * @return \Myth\Auth\Entities\Customer|null */ function customer() { $authenticate = Services::authenticationcustomer(); $authenticate->check(); return $authenticate->customer(); } } if (!function_exists('customer_id')) { /** * Returns the User ID for the current logged in user. * * @return \Myth\Auth\Entities\Customer|null */ function customer_id() { $authenticate = Services::authenticationcustomer(); $authenticate->check(); return $authenticate->id(); } } if (!function_exists('in_groups')) { /** * Ensures that the current user is in at least one of the passed in * groups. The groups can be passed in as either ID's or group names. * You can pass either a single item or an array of items. * * Example: * in_groups([1, 2, 3]); * in_groups(14); * in_groups('admins'); * in_groups( ['admins', 'moderators'] ); * * @param mixed $groups * * @return bool */ function in_groups($groups): bool { $authenticate = Services::authenticationcustomer(); $authorize = Services::authorizationcustomer(); if ($authenticate->check()) { return $authorize->inGroup($groups, $authenticate->id()); } return false; } } if (!function_exists('has_permission')) { /** * Ensures that the current user has the passed in permission. * The permission can be passed in either as an ID or name. * * @param int|string $permission * * @return bool */ function has_permission($permission): bool { $authenticate = Services::authenticationcustomer(); $authorize = Services::authorizationcustomer(); if ($authenticate->check()) { return $authorize->hasPermission($permission, $authenticate->id()) ?? false; } return false; } }
21.739583
79
0.664111
4653f6f61df6430ba04b9d4a159b32509e6b52b0
3,757
php
PHP
vendor/jolicode/jolinotif/src/Notifier/CliBasedNotifier.php
hassanbsee2071/pavyexity_docker_updated
dfd773cc5df971f3816dcf3c958fa311481e1dc7
[ "MIT" ]
1
2021-05-19T21:12:33.000Z
2021-05-19T21:12:33.000Z
vendor/jolicode/jolinotif/src/Notifier/CliBasedNotifier.php
hassanbsee2071/pavyexity_docker_updated
dfd773cc5df971f3816dcf3c958fa311481e1dc7
[ "MIT" ]
null
null
null
vendor/jolicode/jolinotif/src/Notifier/CliBasedNotifier.php
hassanbsee2071/pavyexity_docker_updated
dfd773cc5df971f3816dcf3c958fa311481e1dc7
[ "MIT" ]
null
null
null
<?php /* * This file is part of the JoliNotif project. * * (c) Loïck Piera <pyrech@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Joli\JoliNotif\Notifier; use Joli\JoliNotif\Exception\InvalidNotificationException; use Joli\JoliNotif\Notification; use Joli\JoliNotif\Notifier; use Joli\JoliNotif\Util\OsHelper; use Joli\JoliNotif\Util\PharExtractor; use Symfony\Component\Process\Process; abstract class CliBasedNotifier implements Notifier { const SUPPORT_NONE = -1; const SUPPORT_UNKNOWN = 0; const SUPPORT_NATIVE = 1; const SUPPORT_BINARY_PROVIDED = 2; /** * @var int One of the SUPPORT_XXX constants */ private $support = self::SUPPORT_UNKNOWN; /** * {@inheritdoc} */ public function isSupported(): bool { if (self::SUPPORT_UNKNOWN !== $this->support) { return self::SUPPORT_NONE !== $this->support; } if ($this->isBinaryAvailable()) { $this->support = self::SUPPORT_NATIVE; return true; } if ($this instanceof BinaryProvider && $this->canBeUsed()) { $this->support = self::SUPPORT_BINARY_PROVIDED; return true; } $this->support = self::SUPPORT_NONE; return false; } /** * {@inheritdoc} */ public function send(Notification $notification): bool { if (!$notification->getBody()) { throw new InvalidNotificationException($notification, 'Notification body can not be empty'); } $arguments = $this->getCommandLineArguments($notification); if (self::SUPPORT_BINARY_PROVIDED === $this->support && $this instanceof BinaryProvider) { $dir = rtrim($this->getRootDir(), '/').'/'; $embeddedBinary = $dir.$this->getEmbeddedBinary(); if (PharExtractor::isLocatedInsideAPhar($embeddedBinary)) { $embeddedBinary = PharExtractor::extractFile($embeddedBinary); foreach ($this->getExtraFiles() as $file) { PharExtractor::extractFile($dir.$file); } } $binary = $embeddedBinary; } else { $binary = $this->getBinary(); } $process = new Process(array_merge([$binary], $arguments)); $process->run(); return $this->handleExitCode($process); } /** * Configure the process to run in order to send the notification. */ abstract protected function getCommandLineArguments(Notification $notification): array; /** * Get the binary to check existence. */ abstract protected function getBinary(): string; /** * Check whether a binary is available. */ protected function isBinaryAvailable(): bool { if (OsHelper::isUnix()) { // Do not use the 'which' program to check if a binary exists. // See also http://stackoverflow.com/questions/592620/check-if-a-program-exists-from-a-bash-script $process = new Process([ 'sh', '-c', 'command -v $0', $this->getBinary(), ]); } else { // 'where' is available on Windows since Server 2003 $process = new Process([ 'where', $this->getBinary(), ]); } $process->run(); return $process->isSuccessful(); } /** * Return whether the process executed successfully. */ protected function handleExitCode(Process $process): bool { return 0 === $process->getExitCode(); } }
27.224638
110
0.581581
1a9fb7a0f953d389b239523f3c30163590a32b81
354
cs
C#
UCWASDK/UCWASDK/Models/FailedDeliveryParticipant.cs
tcs-devel/UCWA2.0-CS
84942c321de7ee72cc3996131e290af8b16e1698
[ "MIT" ]
29
2016-11-14T16:32:54.000Z
2020-11-17T12:23:07.000Z
UCWASDK/UCWASDK/Models/FailedDeliveryParticipant.cs
tcs-devel/UCWA2.0-CS
84942c321de7ee72cc3996131e290af8b16e1698
[ "MIT" ]
56
2017-02-07T21:35:07.000Z
2019-02-15T11:19:16.000Z
UCWASDK/UCWASDK/Models/FailedDeliveryParticipant.cs
tcs-devel/UCWA2.0-CS
84942c321de7ee72cc3996131e290af8b16e1698
[ "MIT" ]
25
2017-02-28T18:06:09.000Z
2020-11-11T14:57:12.000Z
namespace Microsoft.Skype.UCWA.Models { /// <summary> /// Represents a participant that failed to receive an instant message sent by the user. /// An application can choose to present this information to the user for a reliable messaging experience. /// </summary> public class FailedDeliveryParticipant : Participant { } }
32.181818
111
0.706215
8417b25637bb7204421c63e6d0f569ebf2cccc8a
990
ps1
PowerShell
dev/Sonos-Kids-Controller-master/deploy.ps1
splitti/MuPiBox
4eeab8518dcd358c1f7834fe7dcdab08f3ba61c8
[ "MIT" ]
2
2022-02-11T07:28:31.000Z
2022-03-05T22:29:12.000Z
dev/Sonos-Kids-Controller-master/deploy.ps1
splitti/MuPiBox
4eeab8518dcd358c1f7834fe7dcdab08f3ba61c8
[ "MIT" ]
3
2022-03-07T08:42:11.000Z
2022-03-25T09:57:03.000Z
dev/Sonos-Kids-Controller-master/deploy.ps1
splitti/MuPiBox
4eeab8518dcd358c1f7834fe7dcdab08f3ba61c8
[ "MIT" ]
null
null
null
 remove-item .\deploy -Recurse -Confirm:$false Remove-Item .\deploy.zip -Confirm:$false # build personal web app ionic build --prod # copy everything to deploy directory mkdir deploy Copy-Item www .\deploy\ -Recurse -Confirm:$false Copy-Item server .\deploy\ -Recurse -Confirm:$false Copy-Item server.js .\deploy\ -Confirm:$false Copy-Item package-deploy.json .\deploy\package.json -Confirm:$false Copy-Item README.md .\deploy\ -Confirm:$false # archive Compress-Archive -Path .\deploy\* -DestinationPath .\deploy.zip Write-Host "----------------------------------" Write-Host "----------------------------------" Write-Host "----------------------------------" $confirmation = Read-Host "Deploy to bin-folder y(es) or n(o)" if ($confirmation -eq 'y') { Remove-Item ..\..\bin\nodejs\deploy.zip -Confirm:$false Copy-Item .\deploy.zip ..\..\bin\nodejs\deploy.zip -Confirm:$false Write-Host "Finished with copy" } else { Write-Host "Finished without copy" }
30
70
0.632323
a196ca966c3afdcf7bb1b23932a67608596e2163
261
ts
TypeScript
packages/vuetify/src/mixins/comparable/index.ts
alerodrod/vuetify
1aea9629bdbe252ac0297816ac1a69d6df47448a
[ "MIT" ]
11
2020-07-23T05:55:27.000Z
2022-03-11T12:54:56.000Z
packages/vuetify/src/mixins/comparable/index.ts
alerodrod/vuetify
1aea9629bdbe252ac0297816ac1a69d6df47448a
[ "MIT" ]
8
2020-06-05T20:54:23.000Z
2022-03-12T00:14:30.000Z
packages/vuetify/src/mixins/comparable/index.ts
alerodrod/vuetify
1aea9629bdbe252ac0297816ac1a69d6df47448a
[ "MIT" ]
3
2021-06-27T16:23:52.000Z
2022-03-03T15:54:05.000Z
import Vue, { PropType } from 'vue' import { deepEqual } from '../../util/helpers' export default Vue.extend({ name: 'comparable', props: { valueComparator: { type: Function as PropType<typeof deepEqual>, default: deepEqual, }, }, })
20.076923
51
0.624521
b2d3c8e5ab050897b56580ee534f568ece12bf59
9,020
css
CSS
resources/public/main.css
CrossRef/member-domains
a34e55d2577e794b29498876073aa9b8cc3cccf6
[ "MIT" ]
null
null
null
resources/public/main.css
CrossRef/member-domains
a34e55d2577e794b29498876073aa9b8cc3cccf6
[ "MIT" ]
null
null
null
resources/public/main.css
CrossRef/member-domains
a34e55d2577e794b29498876073aa9b8cc3cccf6
[ "MIT" ]
null
null
null
strong { font-weight: bold; } a { /*text-decoration: underline;*/ } .itemTitle { font-size: 1.5em; } .citeAction { vertical-align: middle !important; text-align: center; } .btn { margin: 5px; } .navbar-brand { text-decoration: none; color: red; } .cr-red { color: #c0473f; } .cr-grey { color: #514746; } a, a:hover, a:visited { color: #c0473f; } .center-block { display: block; margin-left: auto; margin-right: auto; } .dropdown-menu li a:hover { background-color: #c0473f; } .navbar { #font-size: 1.9em; background-color: white; } .navbar-brand { font-size: 1.8em; } .white-shadow { text-shadow: 1px 1px 6px #fff; } .black-shadow { text-shadow: 2px 2px 4px #444; color: #ffffff; } .navbar { border-radius: 0; margin-bottom: 10px; border: 0; border-bottom: 2px solid #eee; border-color: #bbb; } .jumbotron-top h2 { font-size: 2.6em; font-weight: 15; } .jumbotron-top { border-top: 2px solid #eee; border-color: #bbb; padding-top: 12em; padding-bottom: 8em; margin-bottom: 0px; background: url(../img/network-mod.jpg) no-repeat center center; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } .jumbotron-bottom { text-align: center; margin-top: 0px; background-color: #eee; padding: 2em; height: em; } .jumbotron form { margin-top: 2em; } .jumbotron input { font-size: 1.8em; height: 1.8em; } .field-helper { vertical-align: bottom; } .well { background-color: #fcfcfc; } .well p { font-size: 1.1em; } .thumbnail img { width: 200px; height: 150px; } .thumbnail { height: 410px; } .boxy:hover { text-decoration: none; } .boxy:hover > div { webkit-box-shadow: 0px 0px 10px 0px #c0473f; -moz-box-shadow: 0px 0px 10px 0px #c0473f; box-shadow: 0px 0px 10px 0px #c0473f; } .link-icon { margin-right: 5px; } .panel-title { margin-top: 0px; margin-bottom: 20px; } .page-title { margin-bottom: 20px; } .sidebar-block { margin-bottom: 30px; } .table-hover-pointer { cursor: pointer; } .text-grey { color: #bbb; } body { font-size: 17px; /*Needed for some long DOIs and URLs!*/ word-wrap: break-word; } @-webkit-keyframes spinner { 0% { -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); -moz-transform: rotate(360deg); -ms-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } } @-moz-keyframes spinner { 0% { -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); -moz-transform: rotate(360deg); -ms-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } } @-o-keyframes spinner { 0% { -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); -moz-transform: rotate(360deg); -ms-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } } @keyframes spinner { 0% { -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); -moz-transform: rotate(360deg); -ms-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } } /* :not(:required) hides this rule from IE9 and below */ .spinner:not(:required) { -webkit-animation: spinner 1500ms infinite linear; -moz-animation: spinner 1500ms infinite linear; -ms-animation: spinner 1500ms infinite linear; -o-animation: spinner 1500ms infinite linear; animation: spinner 1500ms infinite linear; -webkit-border-radius: 0.5em; -moz-border-radius: 0.5em; -ms-border-radius: 0.5em; -o-border-radius: 0.5em; border-radius: 0.5em; -webkit-box-shadow: rgba(0, 0, 51, 0.3) 1.5em 0 0 0, rgba(0, 0, 51, 0.3) 1.1em 1.1em 0 0, rgba(0, 0, 51, 0.3) 0 1.5em 0 0, rgba(0, 0, 51, 0.3) -1.1em 1.1em 0 0, rgba(0, 0, 51, 0.3) -1.5em 0 0 0, rgba(0, 0, 51, 0.3) -1.1em -1.1em 0 0, rgba(0, 0, 51, 0.3) 0 -1.5em 0 0, rgba(0, 0, 51, 0.3) 1.1em -1.1em 0 0; -moz-box-shadow: rgba(0, 0, 51, 0.3) 1.5em 0 0 0, rgba(0, 0, 51, 0.3) 1.1em 1.1em 0 0, rgba(0, 0, 51, 0.3) 0 1.5em 0 0, rgba(0, 0, 51, 0.3) -1.1em 1.1em 0 0, rgba(0, 0, 51, 0.3) -1.5em 0 0 0, rgba(0, 0, 51, 0.3) -1.1em -1.1em 0 0, rgba(0, 0, 51, 0.3) 0 -1.5em 0 0, rgba(0, 0, 51, 0.3) 1.1em -1.1em 0 0; box-shadow: rgba(0, 0, 51, 0.3) 1.5em 0 0 0, rgba(0, 0, 51, 0.3) 1.1em 1.1em 0 0, rgba(0, 0, 51, 0.3) 0 1.5em 0 0, rgba(0, 0, 51, 0.3) -1.1em 1.1em 0 0, rgba(0, 0, 51, 0.3) -1.5em 0 0 0, rgba(0, 0, 51, 0.3) -1.1em -1.1em 0 0, rgba(0, 0, 51, 0.3) 0 -1.5em 0 0, rgba(0, 0, 51, 0.3) 1.1em -1.1em 0 0; display: inline-block; font-size: 10px; width: 1em; height: 1em; margin: 1.5em; overflow: hidden; text-indent: 100%; } .fadein { -webkit-animation: fadein .5s; /* Safari, Chrome and Opera > 12.1 */ -moz-animation: fadein .5s; /* Firefox < 16 */ -ms-animation: fadein .5s; /* Internet Explorer */ -o-animation: fadein .5s; /* Opera < 12.1 */ animation: fadein .5s; } @keyframes fadein { from { opacity: 0; } to { opacity: 1; } } /* Firefox < 16 */ @-moz-keyframes fadein { from { opacity: 0; } to { opacity: 1; } } /* Safari, Chrome and Opera > 12.1 */ @-webkit-keyframes fadein { from { opacity: 0; } to { opacity: 1; } } /* Internet Explorer */ @-ms-keyframes fadein { from { opacity: 0; } to { opacity: 1; } } /* Opera < 12.1 */ @-o-keyframes fadein { from { opacity: 0; } to { opacity: 1; } } /** Metricsgraphics */ .markers text { fill: black; font-size: 1.1rem !important; opacity: 1; } .x-axis text, .y-axis text, .histogram .axis text { fill: black; font-size: 1.1rem; opacity: 0.5; } .x-axis .label, .y-axis .label, .axis .label { font-size: 0.8rem; text-transform: uppercase; font-weight: 400; } .x-axis-small text, .y-axis-small text, .active-datapoint-small { font-size: 0.6rem; } .x-axis-small .label, .y-axis-small .label { font-size: 0.65rem; } .year-marker text { fill: black; font-size: 1.3rem; opacity: 0.5; } .year-marker line { opacity: 0.2; shape-rendering: crispEdges; stroke: black; stroke-width: 1; } .year-marker-small text { font-size: 0.6rem; } .extra-info { font-size: 0.8em; } .event-table { font-size: 0.9em; } .event-table td { max-width: 30em; } .navbar-header { /*height: 100px;*/ display: block; margin-top: 10px; } body { padding-top: 120px; } @import url("http://fast.fonts.net/lt/1.css?apiType=css&c=e98f5793-4cb3-43cf-9c5a-90c30937c6bd&fontids=903184,903187,903190,903193,903196,903199,903202,903205"); @font-face{ font-family:"HelveticaNeueETW01-45Lt"; src:url("https://assets.crossref.org/private/fonts/903184/e0781a75-0ecb-464e-b6e9-85780ddc0921.eot?#iefix"); src:url("https://assets.crossref.org/private/fonts/903184/e0781a75-0ecb-464e-b6e9-85780ddc0921.eot?#iefix") format("eot"),url("https://assets.crossref.org/private/fonts/903184/b8765d4b-d9a3-48b9-ac65-560e7517cf0e.woff2") format("woff2"),url("https://assets.crossref.org/private/fonts/903184/d7d2e6c6-fc3a-41a5-9b52-648e12e215b2.woff") format("woff"),url("https://assets.crossref.org/private/fonts/903184/cb64744b-d0f7-4ef8-a790-b60d6e3e4f21.ttf") format("truetype"),url("https://assets.crossref.org/private/fonts/903184/ccde919e-a712-41ef-b90f-9efc47661659.svg#ccde919e-a712-41ef-b90f-9efc47661659") format("svg"); } @font-face{ font-family:"HelveticaNeueETW01-65Md"; src:url("https://assets.crossref.org/private/fonts/903196/a747e1ea-ecdf-4f3d-ad47-3df9cfbee3cc.eot?#iefix"); src:url("https://assets.crossref.org/private/fonts/903196/a747e1ea-ecdf-4f3d-ad47-3df9cfbee3cc.eot?#iefix") format("eot"),url("https://assets.crossref.org/private/fonts/903196/3e8a8b56-3cb0-4347-b670-eaaf06b76e9b.woff2") format("woff2"),url("https://assets.crossref.org/private/fonts/903196/07173950-fa69-4b65-9c71-0cf2ec00b51d.woff") format("woff"),url("https://assets.crossref.org/private/fonts/903196/aac5a4b8-ffd3-4529-a098-21b91bc86f9a.ttf") format("truetype"),url("https://assets.crossref.org/private/fonts/903196/2379b081-2371-47d9-8be9-4e39d7892ebf.svg#2379b081-2371-47d9-8be9-4e39d7892ebf") format("svg"); } body { font-family:'HelveticaNeueETW01-45Lt'; font-style: normal !important; } h1, h2, h3 { font-family:'HelveticaNeueETW01-65Md'; }
22.382134
614
0.639024
23c1c6bfcd1b95466535958783f8fb664feb8b5c
366
js
JavaScript
Drivers/CMSIS/docs/DSP/html/group__Fill.js
mlecriva/TrustZone_stm32l5xx
e924d22bb2b11ac363613e372850fb1896ca3a71
[ "MIT" ]
null
null
null
Drivers/CMSIS/docs/DSP/html/group__Fill.js
mlecriva/TrustZone_stm32l5xx
e924d22bb2b11ac363613e372850fb1896ca3a71
[ "MIT" ]
null
null
null
Drivers/CMSIS/docs/DSP/html/group__Fill.js
mlecriva/TrustZone_stm32l5xx
e924d22bb2b11ac363613e372850fb1896ca3a71
[ "MIT" ]
1
2021-09-25T16:44:11.000Z
2021-09-25T16:44:11.000Z
var group__Fill = [ [ "arm_fill_f32", "group__Fill.html#ga2248e8d3901b4afb7827163132baad94", null ], [ "arm_fill_q15", "group__Fill.html#ga76b21c32a3783a2b3334d930a646e5d8", null ], [ "arm_fill_q31", "group__Fill.html#ga69cc781cf337bd0a31bb85c772a35f7f", null ], [ "arm_fill_q7", "group__Fill.html#ga0465cf326ada039ed792f94b033d9ec5", null ] ];
52.285714
85
0.745902
20e972004180c062c9dade7f535d93f168f7dd87
2,500
dart
Dart
lib/services/auth.dart
pranavraagz/watcher
d4d8f43105f8e4af43cb34511ca86fcc278f1549
[ "MIT" ]
null
null
null
lib/services/auth.dart
pranavraagz/watcher
d4d8f43105f8e4af43cb34511ca86fcc278f1549
[ "MIT" ]
null
null
null
lib/services/auth.dart
pranavraagz/watcher
d4d8f43105f8e4af43cb34511ca86fcc278f1549
[ "MIT" ]
null
null
null
import 'package:crosswalk/models/user.dart'; import 'package:crosswalk/services/database.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; class AuthService { final FirebaseAuth _auth = FirebaseAuth.instance; // //This converts the User Object from Firebase which has a lot of unnecessary props, //to a custom model in models/user.dart which takes only a couple of those props CrosswalkUser _userFromFirebaseUser(User user) { return user != null ? CrosswalkUser( uid: user.uid, displayName: user.displayName, email: user.email, ) : null; } //auth change user stream // Stream<CrosswalkUser> get user { // return _auth // .authStateChanges() // .map((User user) => _userFromFirebaseUser(user)); // } Stream<CrosswalkUser> get user { return _auth .authStateChanges() .map((User user) => _userFromFirebaseUser(user)); } Future<CrosswalkUser> get userA { return _auth.authStateChanges().first.then(_userFromFirebaseUser); } Future signInAnon() async { try { UserCredential result = await _auth.signInAnonymously(); //Used to be AuthResult User user = result.user; //Used to be FirebaseUser return _userFromFirebaseUser(user); } catch (e) { print(e.toString()); return null; } } Future signInWithEmailAndPassword(String email, String password) async { try { UserCredential result = await _auth.signInWithEmailAndPassword( email: email, password: password); User user = result.user; return _userFromFirebaseUser(user); } catch (e) { print(e.toString()); return null; } } Future registerWithEmailAndPassword( String email, String password, String displayName) async { try { UserCredential result = await _auth.createUserWithEmailAndPassword( email: email, password: password); User user = result.user; await DatabaseService(uid: user.uid).updateUserData(email, displayName); return _userFromFirebaseUser(user); } catch (e) { print(e.toString()); return null; } } Future getUserDetails() async { CrosswalkUser user; return _auth.currentUser.displayName; } Future signOut() async { try { return await _auth.signOut(); } catch (e) { print(e.toString()); return null; } } }
26.88172
85
0.6532
6da2aeeeacfe1de36ae899760b87f85638b1b4fc
2,066
c
C
content/cpp/sdl2mixer.c
felixroos/blog
d753f5cfd58af28f2da0c6a839c5a83e224867e4
[ "MIT" ]
null
null
null
content/cpp/sdl2mixer.c
felixroos/blog
d753f5cfd58af28f2da0c6a839c5a83e224867e4
[ "MIT" ]
3
2021-03-10T15:56:19.000Z
2022-02-28T01:47:44.000Z
content/cpp/sdl2mixer.c
felixroos/blog
d753f5cfd58af28f2da0c6a839c5a83e224867e4
[ "MIT" ]
null
null
null
#include <SDL2/SDL.h> #define MUS_PATH "HT0D3.wav" // prototype for our audio callback // see the implementation for more information void my_audio_callback(void *userdata, Uint8 *stream, int len); // variable declarations static Uint8 *audio_pos; // global pointer to the audio buffer to be played static Uint32 audio_len; // remaining length of the sample we have to play /* ** PLAYING A SOUND IS MUCH MORE COMPLICATED THAN IT SHOULD BE */ int main(int argc, char* argv[]){ // Initialize SDL. if (SDL_Init(SDL_INIT_AUDIO) < 0) return 1; // local variables static Uint32 wav_length; // length of our sample static Uint8 *wav_buffer; // buffer containing our audio file static SDL_AudioSpec wav_spec; // the specs of our piece of music /* Load the WAV */ // the specs, length and buffer of our wav are filled if( SDL_LoadWAV(MUS_PATH, &wav_spec, &wav_buffer, &wav_length) == NULL ){ return 1; } // set the callback function wav_spec.callback = my_audio_callback; wav_spec.userdata = NULL; // set our global static variables audio_pos = wav_buffer; // copy sound buffer audio_len = wav_length; // copy file length /* Open the audio device */ if ( SDL_OpenAudio(&wav_spec, NULL) < 0 ){ fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError()); exit(-1); } /* Start playing */ SDL_PauseAudio(0); // wait until we're don't playing while ( audio_len > 0 ) { SDL_Delay(1500); } // shut everything down SDL_CloseAudio(); SDL_FreeWAV(wav_buffer); } // audio callback function // here you have to copy the data of your audio buffer into the // requesting audio buffer (stream) // you should only copy as much as the requested length (len) void my_audio_callback(void *userdata, Uint8 *stream, int len) { if (audio_len ==0) return; len = ( len > audio_len ? audio_len : len ); SDL_memcpy (stream, audio_pos, len); // simply copy from one buffer into the other //SDL_MixAudio(stream, audio_pos, len, SDL_MIX_MAXVOLUME);// mix from one buffer into another audio_pos += len; audio_len -= len; }
27.184211
94
0.708132
059cf30378377081cf97418bbede459f2e60708b
2,555
py
Python
core/lexers/lexers.py
nikitinivan/Pycycle
4e850c6fbcf470ebabf834a8feef6c12f92ccade
[ "MIT" ]
2
2017-11-04T16:56:10.000Z
2020-01-18T10:01:09.000Z
core/lexers/lexers.py
nikitinivan/Pycycle
4e850c6fbcf470ebabf834a8feef6c12f92ccade
[ "MIT" ]
null
null
null
core/lexers/lexers.py
nikitinivan/Pycycle
4e850c6fbcf470ebabf834a8feef6c12f92ccade
[ "MIT" ]
null
null
null
from PyQt5.Qsci import * __all__ = ['get_lexer_by_ext', 'set_lexer_by_menu'] LEXERS = { ('AVS', QsciLexerAVS): (), ('Bash', QsciLexerBash): ('sh', 'ksh', 'bash', 'ebuild', 'eclass', 'exheres-0', 'exlib'), ('Batch', QsciLexerBatch): ('cmd', 'btm'), ('Cmake', QsciLexerCMake): ('cmake'), ('CoffeeScript', QsciLexerCoffeeScript): ('coffee'), ('C++', QsciLexerCPP): ('cpp', 'hpp', 'c++', 'h++', 'cc', 'hh', 'cxx', 'hxx', 'C', 'H', 'cp', 'CPP'), ('C#', QsciLexerCSharp): ('cs'), ('CSS', QsciLexerCSS): ('css'), ('D', QsciLexerD): ('d', 'di'), ('Diff', QsciLexerDiff): ('diff', 'patch'), ('Fortran', QsciLexerFortran): ('f03', 'f90', 'F03', 'F90'), ('Fortran77', QsciLexerFortran77): ('f', 'for'), ('HTML', QsciLexerHTML): ('html', 'htm', 'xhtml', 'xslt'), ('IDL', QsciLexerIDL): ('pro'), ('Java', QsciLexerJava): ('java'), ('JavaScript', QsciLexerJavaScript): ('js', 'jsm'), ('Lua', QsciLexerLua): ('lua', 'wlua'), ('Makefile', QsciLexerMakefile): ('mak', 'mk'), ('Matlab', QsciLexerMatlab): ('m'), ('Octave', QsciLexerOctave): ('m'), ('Pascal', QsciLexerPascal): (), ('Perl', QsciLexerPerl): ('pl', 'pm', 't'), ('PO', QsciLexerPO): ('pas', 'inc'), ('PostScript', QsciLexerPostScript): ('ps', 'eps'), ('POV', QsciLexerPOV): ('pov', 'inc'), ('Properties', QsciLexerProperties): ('properties'), ('Python', QsciLexerPython): ('py', 'pyw', 'sc', 'tac', 'sage'), ('Ruby', QsciLexerRuby): ('rb', 'rbw', 'rake', 'gemspec', 'rbx', 'duby'), ('Spice', QsciLexerSpice): ('cir'), ('SQL', QsciLexerSQL): ('sql'), ('TCL', QsciLexerTCL): ('tcl', 'rvt'), ('TeX', QsciLexerTeX): ('tex', 'aux', 'toc'), ('Verilog', QsciLexerVerilog): ('verilog', 'v'), ('VHDL', QsciLexerVHDL): ('vhdl', 'vhd'), ('XML', QsciLexerXML): ('xml', 'xsl', 'rss', 'xslt', 'xsd', 'wsdl', 'wsf'), ('YAML', QsciLexerYAML): ('yaml', 'yml'), } def get_lexer_by_ext(file): """Function return lexer according file extension""" file_name, file_ext = file.split('.') for key, value in LEXERS.items(): if file_ext in value: lexer = key[1] return lexer def set_lexer_by_menu(item): """Function return lexer according menu item""" for key, value in LEXERS.items(): if item in key[0]: lexer = key[1] return lexer def testing(): """Function for testing""" print(get_lexer_by_ext('file.py')) print(set_lexer_by_menu('Python')) if __name__ == '__main__': testing()
36.5
105
0.551468
3862e0cb0572ec3896ab15da273d3e3e6c805c49
319
php
PHP
tests/Application/app/AccountCollection.php
sergiy-petrov/larastan
a5a6bdae060c72a5909479fb37c04a7f9fd84533
[ "MIT" ]
3,703
2018-07-05T21:39:20.000Z
2022-03-31T19:15:47.000Z
tests/Application/app/AccountCollection.php
sergiy-petrov/larastan
a5a6bdae060c72a5909479fb37c04a7f9fd84533
[ "MIT" ]
991
2018-07-05T21:43:56.000Z
2022-03-30T14:26:34.000Z
tests/Application/app/AccountCollection.php
sergiy-petrov/larastan
a5a6bdae060c72a5909479fb37c04a7f9fd84533
[ "MIT" ]
364
2018-07-16T21:48:31.000Z
2022-03-31T21:04:32.000Z
<?php namespace App; use Illuminate\Database\Eloquent\Collection; /** * @template TModel * @extends Collection<TModel> */ class AccountCollection extends Collection { /** * @return self<TModel> */ public function filterByActive(): self { return $this->where('active', true); } }
15.190476
44
0.636364
da9416ae9ddb08c743d213b86a8851ce64e04f7d
367
php
PHP
tests/bootstrap.php
JShadowMan/PHPDesignPatterns
6af47598510c5848f7d4515f1174967fd60da341
[ "MIT" ]
null
null
null
tests/bootstrap.php
JShadowMan/PHPDesignPatterns
6af47598510c5848f7d4515f1174967fd60da341
[ "MIT" ]
null
null
null
tests/bootstrap.php
JShadowMan/PHPDesignPatterns
6af47598510c5848f7d4515f1174967fd60da341
[ "MIT" ]
null
null
null
<?php /** * Bootstrap.php * * @package Here * @author ShadowMan <shadowman@shellboot.com> * @copyright Copyright (C) 2016-2017 ShadowMan * @license MIT License * @link https://github.com/JShadowMan/DesignPatterns */ $loader = include __DIR__ . '/../vendor/autoload.php'; $loader->addPsr4('DesignPatterns\\', array('src', 'tests/'));
26.214286
62
0.637602
b2c899b3b1e8e02934c62f7057ab4502f3a9707a
984
dart
Dart
lib/bloc/universal_link/universal_link_bloc.dart
fossabot/glacius-mobile
7b5c64f6f4adb0c3820fa55897ea76831bb0aef6
[ "MIT" ]
1
2020-10-06T12:45:32.000Z
2020-10-06T12:45:32.000Z
lib/bloc/universal_link/universal_link_bloc.dart
fossabot/glacius-mobile
7b5c64f6f4adb0c3820fa55897ea76831bb0aef6
[ "MIT" ]
1
2019-12-10T08:46:07.000Z
2019-12-10T08:46:07.000Z
lib/bloc/universal_link/universal_link_bloc.dart
fossabot/glacius-mobile
7b5c64f6f4adb0c3820fa55897ea76831bb0aef6
[ "MIT" ]
2
2019-12-10T08:38:41.000Z
2020-01-04T16:55:40.000Z
import 'package:bloc/bloc.dart'; import 'package:glacius_mobile/bloc/universal_link/universal_link.dart'; import 'package:uni_links/uni_links.dart'; import 'package:flutter/services.dart'; class UniversalLinkBloc extends Bloc<UniversalLinkEvent, UniversalLinkState> { @override UniversalLinkState get initialState => UniversalLinkInitial(); @override Stream<UniversalLinkState> mapEventToState(UniversalLinkEvent event) async* { if (event is CheckIfAppCameFromLinks) { try { Uri initialLink = await getInitialUri(); if (initialLink == null) { yield UniversalLinkCheckCompleted(isCameFromUniversalLink: false); } else { yield UniversalLinkCheckCompleted( isCameFromUniversalLink: true, action: initialLink.host, path: initialLink.path, ); } } on PlatformException { yield UniversalLinkCheckCompleted(isCameFromUniversalLink: false); } } } }
32.8
79
0.697154
9528a3a1f0a9478e84cad21ad797e2718d03be86
2,497
go
Go
cmd/oy-expose/main_test.go
o11ydev/oy-toolkit
97c5a534e3a48bcedcec7654cd3320ad007026c1
[ "Apache-2.0" ]
5
2022-03-15T19:31:39.000Z
2022-03-24T20:09:03.000Z
cmd/oy-expose/main_test.go
o11ydev/oy-toolkit
97c5a534e3a48bcedcec7654cd3320ad007026c1
[ "Apache-2.0" ]
null
null
null
cmd/oy-expose/main_test.go
o11ydev/oy-toolkit
97c5a534e3a48bcedcec7654cd3320ad007026c1
[ "Apache-2.0" ]
1
2022-03-16T11:59:13.000Z
2022-03-16T11:59:13.000Z
// Copyright 2022 The o11y toolkit Authors // spdx-license-identifier: apache-2.0 // // 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 ( "io" "io/ioutil" "net/http" "net/http/httptest" "net/url" "os" "os/exec" "testing" "time" "github.com/stretchr/testify/require" ) var mainPath = os.Args[0] func TestMain(m *testing.M) { for i, arg := range os.Args { if arg == "-test.main" { os.Args = append(os.Args[:i], os.Args[i+1:]...) main() return } } exitCode := m.Run() os.Exit(exitCode) } func TestExpose(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode.") } testServer := httptest.NewServer(nil) testURL := testServer.URL testServer.Close() u, err := url.Parse(testURL) require.NoError(t, err) tmpfile, err := os.CreateTemp("", "metrics") require.NoError(t, err) defer os.Remove(tmpfile.Name()) run := exec.Command(mainPath, "-test.main", "--web.listen-address="+u.Host, tmpfile.Name()) // Log stderr in case of failure. stderr, err := run.StderrPipe() require.NoError(t, err) go func() { slurp, _ := ioutil.ReadAll(stderr) t.Log(string(slurp)) }() err = run.Start() require.NoError(t, err) done := make(chan error, 1) go func() { done <- run.Wait() }() select { case err := <-done: t.Errorf("oy-expose should be still running: %v", err) case <-time.After(1 * time.Second): } resp, err := http.Get(testURL + "/metrics") require.NoError(t, err) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Contains(t, string(body), "node_textfile_scrape_error 0") os.Remove(tmpfile.Name()) resp, err = http.Get(testURL + "/metrics") require.NoError(t, err) body, err = io.ReadAll(resp.Body) require.NoError(t, err) require.Contains(t, string(body), "node_textfile_scrape_error 1") select { case err := <-done: t.Errorf("oy-expose should be still running: %v", err) case <-time.After(5 * time.Second): require.NoError(t, run.Process.Kill()) <-done } }
23.780952
92
0.67481
663bcf7cbf97b88a431e5ba63e8f74a5b5e7fc19
6,062
py
Python
international_data_preprocessing/money.py
emcarlson2017/international-data-preprocessing
dee729c7348ffc77547dd5ca9d4c09daba4f4c66
[ "MIT" ]
null
null
null
international_data_preprocessing/money.py
emcarlson2017/international-data-preprocessing
dee729c7348ffc77547dd5ca9d4c09daba4f4c66
[ "MIT" ]
null
null
null
international_data_preprocessing/money.py
emcarlson2017/international-data-preprocessing
dee729c7348ffc77547dd5ca9d4c09daba4f4c66
[ "MIT" ]
null
null
null
"""The money module includes an object representation of money, and functions to parse strings into Money.""" from .country import Country from ._util import check_single_row import pandas as pd import re import os import os.path dirpath = os.path.dirname(os.path.realpath(__file__)) _country_to_currency = pd.read_csv( os.path.join(dirpath, 'data/country_currency.csv')) _currencies = pd.read_csv(os.path.join(dirpath, 'data/currencies.csv')) _country_to_currency_dict = {} for row in _country_to_currency.itertuples(): _country_to_currency_dict[row.country] = row.currency class Money: """The Money class contains all functions to parse and retrieve money values in any currency.""" def __init__(self, amount, currency_abbv, currency_full=None): """Initialize Money instance. Args: amount: the numeric amount of money, regardless of currency. currency_abbv: the 3 letter abbreviation of the currency. currency_full: optional, the full name of the currency. """ self.amount = amount self.currency_abbv = currency_abbv self.currency_full = currency_full def get(self, attr): """Retrieve attribute from an instance of the Money class. Args: attr: name of attribute to retrieve, one of (amount, abbv, full). Returns: the value of the requested attribute. Raises: ValueError: if the input is not one of the 3 attributes. """ if attr == 'amount': return self.amount elif attr == 'abbv': return self.currency_abbv elif attr == 'full': return self.currency_full else: raise ValueError( "attr must be one of the following: amount, currency_abbv, currency_full") @staticmethod def parse(input, currency=None): """Parses money value strings into Money objects. Args: input: string containing the money value in <amount currency> or <currency amount> format, or <amount> format if currency is provided separately. currency: optional, string containing the currency code or full currency name. Returns: the Currency object. Raises: ValueError: if the input is not in the format specified above. """ input = str(input).strip() if currency: if not re.fullmatch('[0-9]+\\.?[0-9]*', input): raise ValueError( "Input must be a numeric value or number in string representation when currency is specified.") row = _currencies[(_currencies['abbreviation'] == currency) | ( _currencies['full_name'] == currency)] check_single_row(row, "Currency provided must be a valid 3 letter abbreviation from https://www.ifcmarkets.com/en/about-forex/currencies-and-abbreviations") return Money( float(input), row.iloc[0]['abbreviation'], row.iloc[0]['full_name']) amount = None match = re.fullmatch('([0-9]+\\.?[0-9]*)\\s*([a-zA-Z\\s]+)', input) if match: amount = match.group(0) currency = match.group(1) else: match = re.fullmatch('([a-zA-Z\\s]+)\\s*([0-9]+\\.?[0-9]*)', input) if match: amount = match.group(1) currency = match.group(0) else: raise ValueError( "Input must be of the form <amount currency> or <currency amount> if currency is not provided.") row = _currencies[(_currencies['abbreviation'] == currency) | (_currencies['full_name'] == currency)] check_single_row(row, "Currency must be a valid 3 letter abbreviation from https://www.ifcmarkets.com/en/about-forex/currencies-and-abbreviations") return Money( float(amount), row.iloc[0]['abbreviation'], row.iloc[0]['full_name']) def country_to_primary_currency( df, country_col_name, output_col_name=None, in_place=True): """Provides currency code given a country in any standard notation. For countries with more than one currency, the primary or most commonly used one is selected. Args: df: the data frame. country_col_name: the name of the column with country in alpha2, alpha3, UN, full, or short format. output_col_name: new column name if in_place is False. in_place: if True, overwrite output to input column; if False, write output to new column. """ new_col = df[country_col_name].map(Country.parse).map( lambda x: _country_to_currency_dict[x.get('alpha3')]) if in_place: df[country_col_name] = new_col else: if not output_col_name: raise ValueError( "output_col_name must be provided when operation is not in place.") df[output_col_name] = new_col def parse_money(df, input_col_name, output_types=None, output_col_names=None, in_place=True): """Parses and separates money values (e.g. EUR 52.50) into its amount and/or currency. Args: df: the data frame. input_col_name: the name of the column with money values. output_types: one or more of ['amount', 'abbv', 'full']. output_col_names: new column names if in_place is False. in_place: if True, overwrite output to input column; if False, write output to new column. """ new_col = df[input_col_name].map(Money.parse) if in_place: df[input_col_name] = new_col.map( lambda x: str(x.get('amount')) + x.get('abbv')) else: if len(output_types) != len(output_col_names): raise ValueError( "output_types and output_col_names must be of the same length") for i in range(len(output_types)): df[output_col_names[i]] = new_col.map( lambda x: x.get(output_types[i]))
39.881579
163
0.623062
798f43a0373da3bdcb71606bc62dd64805a3b397
4,824
php
PHP
system/Database/DBResult.php
voyager-php/voyager
5ea5b371d3ebadd44b9f0f6dcabd41698b52a736
[ "MIT" ]
13
2020-12-02T00:31:59.000Z
2021-07-08T06:22:24.000Z
system/Database/DBResult.php
voyager-php/voyager
5ea5b371d3ebadd44b9f0f6dcabd41698b52a736
[ "MIT" ]
null
null
null
system/Database/DBResult.php
voyager-php/voyager
5ea5b371d3ebadd44b9f0f6dcabd41698b52a736
[ "MIT" ]
2
2020-12-02T10:04:52.000Z
2020-12-05T08:08:15.000Z
<?php namespace Voyager\Database; use Voyager\App\Request; use Voyager\Util\Data\Bundle; class DBResult extends DBResponse { /** * Store result in bundle objects. * * @var \Voyager\Util\Data\Bundle */ private $bundle; /** * Return result bundle. * * @return \Voyager\Util\Data\Bundle */ public function fetch() { if(is_null($this->bundle)) { $this->bundle = new Bundle($this->conn->fetch()); $this->conn->freeResult(); } return $this->bundle; } /** * Return the very first result. * * @return mixed */ public function first() { $this->fetch(); return $this->bundle->first(); } /** * Return the very last result. * * @return mixed */ public function last() { $this->fetch(); return $this->bundle->last(); } /** * Return row by index number. * * @param int $index * @return mixed */ public function get(int $index) { if($index <= $this->numRows()) { $this->fetch(); return $this->bundle->get($index); } } /** * Return total number of rows. * * @return int */ public function numRows() { $this->fetch(); return (int)$this->bundle->size(); } /** * Return true if result has now rows. * * @return bool */ public function empty() { return $this->numRows() === 0; } /** * Return result as array. * * @return array */ public function toArray() { $this->fetch(); return $this->bundle->toArray(); } /** * Return json encoded result. * * @return string */ public function toJson() { $this->fetch(); return $this->bundle->toJson(); } /** * Transform database result. * * @param string $class * @return $this */ public function transform(string $class) { $this->bundle = $this->fetch()->transform($class); return $this; } /** * Add new column to result. * * @param string $key * @param mixed $value * @return $this */ public function addColumn(string $key, $value) { $this->fetch(); $this->bundle->addColumn($key, $value); return $this; } /** * Return list of value of a column. * * @param string $key * @return array */ public function column(string $key) { $this->fetch(); return $this->bundle->column($key); } /** * If result is just one row, automatically get * values by calling it as property. * * @param string $name * @return mixed */ public function __get(string $name) { if($this->numRows() === 1) { $data = $this->first(); if($data->has($name)) { return $data->{$name}; } } } /** * Paginate the results from database. * * @param \Voyager\App\Request $request * @return \Voyager\Util\Data\Collection */ public function paginate(Request $request) { $maximum = 5; $data = $this->fetch(); $total = (int) $this->numRows(); $page = (int) $request->get('page', 1); $per_page = (int) $request->get('per_page', 10); $total_page = (int) ceil($total / $per_page); $start = ($page * $per_page) - $per_page; $end = $start + $per_page; $result = []; $min = $page; $max = ($min - 1) + $maximum; if($max > $total_page) { $max = $total_page; } $diff = ($max - $min) + 1; if($diff < $maximum) { $min -= ($maximum - $diff); } if($min <= 0) { $min = 1; } for($i = $start + 1; $i <= $end; $i++) { if($i <= $total) { $result[] = $data->get($i - 1)->toArray(); } } if($total === 0) { app()->code = 404; } return $request->apiResponse($result, [ 'total' => $total, 'paginate' => true, 'page' => $page, 'per_page' => $per_page, 'total_page' => $total_page, 'rows' => sizeof($result), 'pages' => [ 'min' => $min, 'max' => $max, ], ]); } }
19.219124
61
0.42869
b2d2cdd1ca7c5c7e19205dec4fc7550d4066fa95
31,242
css
CSS
public/assets/css/style2.css
Janakh/Ei-sGallery
75d50452ebebccf03732c562fff37ef66fe2bf67
[ "MIT" ]
1
2018-12-08T03:32:55.000Z
2018-12-08T03:32:55.000Z
public/assets/css/style2.css
Janakh/Ei-sGallery
75d50452ebebccf03732c562fff37ef66fe2bf67
[ "MIT" ]
null
null
null
public/assets/css/style2.css
Janakh/Ei-sGallery
75d50452ebebccf03732c562fff37ef66fe2bf67
[ "MIT" ]
null
null
null
@import url("https://fonts.googleapis.com/css?family=Source+Sans+Pro"); @-webkit-keyframes fade-in { from { visibility: hidden; opacity: 0; } to { visibility: visible; opacity: 1; } } @keyframes fade-in { from { visibility: hidden; opacity: 0; } to { visibility: visible; opacity: 1; } } @-webkit-keyframes slide-show { to { -webkit-transform: translateY(0); transform: translateY(0); } } @keyframes slide-show { to { -webkit-transform: translateY(0); transform: translateY(0); } } body { width: 100%; height: 100vh; background: url(https://subtlepatterns.com/patterns/use_your_illusion.png); font-family: 'Open Sans', sans-serif; text-rendering: optimizeLegibility; } main { width: 100vw; height: 100vh; display: flex; align-items: center; justify-content: center; text-align: center; } h1 { color:#e5e7e9 ; font-size: 55px; } p { line-height: 1.5; } nav { margin-top: 50px; } .button { padding: 15px 20px; border: 2px solid white; border-radius: 5px; font-size: 13px; font-weight: 700; text-transform: uppercase; text-decoration: none; color: white; } .button:hover, .button.is-active { color: #be93c5; background-color: white; } .top-left { position: fixed; z-index: 1000; display: flex; align-items: center; padding: 20px; color: #fff; line-height: 1.3; box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.35); max-width: 350px; margin: 20px; top: 0; left: 0; -webkit-transform: translateX(-420px); transform: translateX(-420px); } @-webkit-keyframes slide-in-left { to { -webkit-transform: translateX(0); transform: translateX(0); } } @keyframes slide-in-left { to { -webkit-transform: translateX(0); transform: translateX(0); } } .top-left.do-show { animation: slide-in-left 1s ease-in-out forwards, slide-in-left 1s ease-in-out reverse forwards 5s; } .top-left[data-notification-status="notice"] { background-color: #29B6F6; } .top-left[data-notification-status="notice"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23077CB2'/%3E%3Cpath d='M11.016,6.984V9h1.968V6.984H11.016z M11.016,17.016h1.968v-6h-1.968V17.016z' fill='%23077CB2'/%3E%3C/svg%3E") center/cover no-repeat; } .top-left[data-notification-status="warning"] { background-color: #FFCA28; } .top-left[data-notification-status="warning"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23C19100'/%3E%3Cpath d='M11.016,17.016h1.968V15h-1.968V17.016z M11.016,6.983v6.001h1.968V6.983H11.016z' fill='%23C19100'/%3E%3C/svg%3E") center/cover no-repeat; } .top-left[data-notification-status="error"] { background-color: #EF5350; } .top-left[data-notification-status="error"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23C71612'/%3E%3Cpath d='M13.406,12l2.578,2.578l-1.406,1.406L12,13.406l-2.578,2.578l-1.406-1.406L10.594,12L8.016,9.421l1.406-1.405L12,10.593 l2.578-2.577l1.406,1.405L13.406,12z' fill='%23C71612'/%3E%3C/svg%3E") center/cover no-repeat; } .top-left[data-notification-status="success"] { background-color: #66BB6A; } .top-left[data-notification-status="success"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%233A813D'/%3E%3Cpath d='M10.477,13.136l5.085-5.085l1.406,1.406l-6.492,6.492l-3.446-3.445l1.406-1.406L10.477,13.136z' fill='%233A813D'/%3E%3C/svg%3E") center/cover no-repeat; } .top-left[data-notification-status="question"] { background-color: #8D6E63; } .top-left[data-notification-status="question"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23513F39'/%3E%3Cpath d='M12.001,6.314h-0.002c-1.996,0-3.609,1.614-3.609,3.609h1.784c0-0.977,0.85-1.784,1.826-1.784 c0.977,0,1.827,0.807,1.827,1.784c0,1.826-2.718,1.614-2.718,4.544h1.784c0-2.038,2.717-2.294,2.717-4.544 C15.609,7.928,13.997,6.314,12.001,6.314z M11.109,17.186h1.784v-1.826h-1.784V17.186z' fill='%23513F39'/%3E%3C/svg%3E") center/cover no-repeat; } .top-left[data-notification-status="plain"] { background-color: #333; } .top-right { position: fixed; z-index: 1000; display: flex; align-items: center; padding: 20px; color: #fff; line-height: 1.3; box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.35); visibility: hidden; opacity: 0; max-width: 350px; margin: 20px; top: 0; right: 0; } .top-right.do-show { animation: fade-in 1s ease-in-out forwards, fade-in 1s ease-in-out reverse forwards 3s; } .top-right[data-notification-status="notice"] { background-color: #29B6F6; } .top-right[data-notification-status="notice"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23077CB2'/%3E%3Cpath d='M11.016,6.984V9h1.968V6.984H11.016z M11.016,17.016h1.968v-6h-1.968V17.016z' fill='%23077CB2'/%3E%3C/svg%3E") center/cover no-repeat; } .top-right[data-notification-status="warning"] { background-color: #FFCA28; } .top-right[data-notification-status="warning"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23C19100'/%3E%3Cpath d='M11.016,17.016h1.968V15h-1.968V17.016z M11.016,6.983v6.001h1.968V6.983H11.016z' fill='%23C19100'/%3E%3C/svg%3E") center/cover no-repeat; } .top-right[data-notification-status="error"] { background-color: #EF5350; } .top-right[data-notification-status="error"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23C71612'/%3E%3Cpath d='M13.406,12l2.578,2.578l-1.406,1.406L12,13.406l-2.578,2.578l-1.406-1.406L10.594,12L8.016,9.421l1.406-1.405L12,10.593 l2.578-2.577l1.406,1.405L13.406,12z' fill='%23C71612'/%3E%3C/svg%3E") center/cover no-repeat; } .top-right[data-notification-status="success"] { background-color: #66BB6A; } .top-right[data-notification-status="success"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%233A813D'/%3E%3Cpath d='M10.477,13.136l5.085-5.085l1.406,1.406l-6.492,6.492l-3.446-3.445l1.406-1.406L10.477,13.136z' fill='%233A813D'/%3E%3C/svg%3E") center/cover no-repeat; } .top-right[data-notification-status="question"] { background-color: #8D6E63; } .top-right[data-notification-status="question"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23513F39'/%3E%3Cpath d='M12.001,6.314h-0.002c-1.996,0-3.609,1.614-3.609,3.609h1.784c0-0.977,0.85-1.784,1.826-1.784 c0.977,0,1.827,0.807,1.827,1.784c0,1.826-2.718,1.614-2.718,4.544h1.784c0-2.038,2.717-2.294,2.717-4.544 C15.609,7.928,13.997,6.314,12.001,6.314z M11.109,17.186h1.784v-1.826h-1.784V17.186z' fill='%23513F39'/%3E%3C/svg%3E") center/cover no-repeat; } .top-right[data-notification-status="plain"] { background-color: #333; } .bottom-right { position: fixed; z-index: 1000; display: flex; align-items: center; padding: 20px; color: #fff; line-height: 1.3; box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.35); max-width: 350px; margin: 20px; bottom: 0; right: 0; -webkit-transform: translateX(420px); transform: translateX(420px); } @-webkit-keyframes slide-in-right { to { -webkit-transform: translateX(0); transform: translateX(0); } } @keyframes slide-in-right { to { -webkit-transform: translateX(0); transform: translateX(0); } } .bottom-right.do-show { animation: slide-in-right 1s ease-in-out forwards, slide-in-right 1s ease-in-out reverse forwards 3s; } .bottom-right[data-notification-status="notice"] { background-color: #29B6F6; } .bottom-right[data-notification-status="notice"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23077CB2'/%3E%3Cpath d='M11.016,6.984V9h1.968V6.984H11.016z M11.016,17.016h1.968v-6h-1.968V17.016z' fill='%23077CB2'/%3E%3C/svg%3E") center/cover no-repeat; } .bottom-right[data-notification-status="warning"] { background-color: #FFCA28; } .bottom-right[data-notification-status="warning"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23C19100'/%3E%3Cpath d='M11.016,17.016h1.968V15h-1.968V17.016z M11.016,6.983v6.001h1.968V6.983H11.016z' fill='%23C19100'/%3E%3C/svg%3E") center/cover no-repeat; } .bottom-right[data-notification-status="error"] { background-color: #EF5350; } .bottom-right[data-notification-status="error"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23C71612'/%3E%3Cpath d='M13.406,12l2.578,2.578l-1.406,1.406L12,13.406l-2.578,2.578l-1.406-1.406L10.594,12L8.016,9.421l1.406-1.405L12,10.593 l2.578-2.577l1.406,1.405L13.406,12z' fill='%23C71612'/%3E%3C/svg%3E") center/cover no-repeat; } .bottom-right[data-notification-status="success"] { background-color: #66BB6A; } .bottom-right[data-notification-status="success"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%233A813D'/%3E%3Cpath d='M10.477,13.136l5.085-5.085l1.406,1.406l-6.492,6.492l-3.446-3.445l1.406-1.406L10.477,13.136z' fill='%233A813D'/%3E%3C/svg%3E") center/cover no-repeat; } .bottom-right[data-notification-status="question"] { background-color: #8D6E63; } .bottom-right[data-notification-status="question"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23513F39'/%3E%3Cpath d='M12.001,6.314h-0.002c-1.996,0-3.609,1.614-3.609,3.609h1.784c0-0.977,0.85-1.784,1.826-1.784 c0.977,0,1.827,0.807,1.827,1.784c0,1.826-2.718,1.614-2.718,4.544h1.784c0-2.038,2.717-2.294,2.717-4.544 C15.609,7.928,13.997,6.314,12.001,6.314z M11.109,17.186h1.784v-1.826h-1.784V17.186z' fill='%23513F39'/%3E%3C/svg%3E") center/cover no-repeat; } .bottom-right[data-notification-status="plain"] { background-color: #333; } .bottom-left { position: fixed; z-index: 1000; display: flex; align-items: center; padding: 20px; color: #fff; line-height: 1.3; box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.35); visibility: hidden; opacity: 0; max-width: 350px; margin: 20px; bottom: 0; left: 0; } .bottom-left.do-show { animation: fade-in 1s ease-in-out forwards, fade-in 1s ease-in-out reverse forwards 3s; } .bottom-left[data-notification-status="notice"] { background-color: #29B6F6; } .bottom-left[data-notification-status="notice"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23077CB2'/%3E%3Cpath d='M11.016,6.984V9h1.968V6.984H11.016z M11.016,17.016h1.968v-6h-1.968V17.016z' fill='%23077CB2'/%3E%3C/svg%3E") center/cover no-repeat; } .bottom-left[data-notification-status="warning"] { background-color: #FFCA28; } .bottom-left[data-notification-status="warning"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23C19100'/%3E%3Cpath d='M11.016,17.016h1.968V15h-1.968V17.016z M11.016,6.983v6.001h1.968V6.983H11.016z' fill='%23C19100'/%3E%3C/svg%3E") center/cover no-repeat; } .bottom-left[data-notification-status="error"] { background-color: #EF5350; } .bottom-left[data-notification-status="error"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23C71612'/%3E%3Cpath d='M13.406,12l2.578,2.578l-1.406,1.406L12,13.406l-2.578,2.578l-1.406-1.406L10.594,12L8.016,9.421l1.406-1.405L12,10.593 l2.578-2.577l1.406,1.405L13.406,12z' fill='%23C71612'/%3E%3C/svg%3E") center/cover no-repeat; } .bottom-left[data-notification-status="success"] { background-color: #66BB6A; } .bottom-left[data-notification-status="success"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%233A813D'/%3E%3Cpath d='M10.477,13.136l5.085-5.085l1.406,1.406l-6.492,6.492l-3.446-3.445l1.406-1.406L10.477,13.136z' fill='%233A813D'/%3E%3C/svg%3E") center/cover no-repeat; } .bottom-left[data-notification-status="question"] { background-color: #8D6E63; } .bottom-left[data-notification-status="question"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23513F39'/%3E%3Cpath d='M12.001,6.314h-0.002c-1.996,0-3.609,1.614-3.609,3.609h1.784c0-0.977,0.85-1.784,1.826-1.784 c0.977,0,1.827,0.807,1.827,1.784c0,1.826-2.718,1.614-2.718,4.544h1.784c0-2.038,2.717-2.294,2.717-4.544 C15.609,7.928,13.997,6.314,12.001,6.314z M11.109,17.186h1.784v-1.826h-1.784V17.186z' fill='%23513F39'/%3E%3C/svg%3E") center/cover no-repeat; } .bottom-left[data-notification-status="plain"] { background-color: #333; } .bar-top { position: fixed; z-index: 1000; display: flex; align-items: center; padding: 20px; color: #fff; line-height: 1.3; box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.35); top: 0; right: 0; left: 0; width: 100%; -webkit-transform: translateY(-100%); transform: translateY(-100%); } .bar-top.do-show { animation: slide-show 1s forwards, slide-show 1s reverse forwards 3s; } .bar-top[data-notification-status="notice"] { background-color: #29B6F6; } .bar-top[data-notification-status="notice"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23077CB2'/%3E%3Cpath d='M11.016,6.984V9h1.968V6.984H11.016z M11.016,17.016h1.968v-6h-1.968V17.016z' fill='%23077CB2'/%3E%3C/svg%3E") center/cover no-repeat; } .bar-top[data-notification-status="warning"] { background-color: #FFCA28; } .bar-top[data-notification-status="warning"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23C19100'/%3E%3Cpath d='M11.016,17.016h1.968V15h-1.968V17.016z M11.016,6.983v6.001h1.968V6.983H11.016z' fill='%23C19100'/%3E%3C/svg%3E") center/cover no-repeat; } .bar-top[data-notification-status="error"] { background-color: #EF5350; } .bar-top[data-notification-status="error"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23C71612'/%3E%3Cpath d='M13.406,12l2.578,2.578l-1.406,1.406L12,13.406l-2.578,2.578l-1.406-1.406L10.594,12L8.016,9.421l1.406-1.405L12,10.593 l2.578-2.577l1.406,1.405L13.406,12z' fill='%23C71612'/%3E%3C/svg%3E") center/cover no-repeat; } .bar-top[data-notification-status="success"] { background-color: #66BB6A; } .bar-top[data-notification-status="success"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%233A813D'/%3E%3Cpath d='M10.477,13.136l5.085-5.085l1.406,1.406l-6.492,6.492l-3.446-3.445l1.406-1.406L10.477,13.136z' fill='%233A813D'/%3E%3C/svg%3E") center/cover no-repeat; } .bar-top[data-notification-status="question"] { background-color: #8D6E63; } .bar-top[data-notification-status="question"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23513F39'/%3E%3Cpath d='M12.001,6.314h-0.002c-1.996,0-3.609,1.614-3.609,3.609h1.784c0-0.977,0.85-1.784,1.826-1.784 c0.977,0,1.827,0.807,1.827,1.784c0,1.826-2.718,1.614-2.718,4.544h1.784c0-2.038,2.717-2.294,2.717-4.544 C15.609,7.928,13.997,6.314,12.001,6.314z M11.109,17.186h1.784v-1.826h-1.784V17.186z' fill='%23513F39'/%3E%3C/svg%3E") center/cover no-repeat; } .bar-top[data-notification-status="plain"] { background-color: #333; } .bar-bottom { position: fixed; z-index: 1000; display: flex; align-items: center; padding: 20px; color: #fff; line-height: 1.3; box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.35); visibility: hidden; opacity: 0; bottom: 0; right: 0; left: 0; width: 100%; } .bar-bottom.do-show { animation: fade-in 1s ease-in-out forwards, fade-in 1s ease-in-out reverse forwards 3s; } .bar-bottom[data-notification-status="notice"] { background-color: #29B6F6; } .bar-bottom[data-notification-status="notice"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23077CB2'/%3E%3Cpath d='M11.016,6.984V9h1.968V6.984H11.016z M11.016,17.016h1.968v-6h-1.968V17.016z' fill='%23077CB2'/%3E%3C/svg%3E") center/cover no-repeat; } .bar-bottom[data-notification-status="warning"] { background-color: #FFCA28; } .bar-bottom[data-notification-status="warning"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23C19100'/%3E%3Cpath d='M11.016,17.016h1.968V15h-1.968V17.016z M11.016,6.983v6.001h1.968V6.983H11.016z' fill='%23C19100'/%3E%3C/svg%3E") center/cover no-repeat; } .bar-bottom[data-notification-status="error"] { background-color: #EF5350; } .bar-bottom[data-notification-status="error"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23C71612'/%3E%3Cpath d='M13.406,12l2.578,2.578l-1.406,1.406L12,13.406l-2.578,2.578l-1.406-1.406L10.594,12L8.016,9.421l1.406-1.405L12,10.593 l2.578-2.577l1.406,1.405L13.406,12z' fill='%23C71612'/%3E%3C/svg%3E") center/cover no-repeat; } .bar-bottom[data-notification-status="success"] { background-color: #66BB6A; } .bar-bottom[data-notification-status="success"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%233A813D'/%3E%3Cpath d='M10.477,13.136l5.085-5.085l1.406,1.406l-6.492,6.492l-3.446-3.445l1.406-1.406L10.477,13.136z' fill='%233A813D'/%3E%3C/svg%3E") center/cover no-repeat; } .bar-bottom[data-notification-status="question"] { background-color: #8D6E63; } .bar-bottom[data-notification-status="question"]:before { content: ''; display: block; width: 30px; height: 30px; min-width: 30px; margin-right: 20px; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M12 3.984c4.407 0 8.016 3.609 8.016 8.016 0 4.406-3.608 8.016-8.016 8.016S3.984 16.407 3.984 12 7.593 3.984 12 3.984m0-2C6.478 1.984 1.984 6.477 1.984 12c0 5.521 4.493 10.016 10.016 10.016S22.016 17.522 22.016 12c0-5.523-4.495-10.016-10.016-10.016zm0 2c4.407 0 8.016 3.609 8.016' fill='%23513F39'/%3E%3Cpath d='M12.001,6.314h-0.002c-1.996,0-3.609,1.614-3.609,3.609h1.784c0-0.977,0.85-1.784,1.826-1.784 c0.977,0,1.827,0.807,1.827,1.784c0,1.826-2.718,1.614-2.718,4.544h1.784c0-2.038,2.717-2.294,2.717-4.544 C15.609,7.928,13.997,6.314,12.001,6.314z M11.109,17.186h1.784v-1.826h-1.784V17.186z' fill='%23513F39'/%3E%3C/svg%3E") center/cover no-repeat; } .bar-bottom[data-notification-status="plain"] { background-color: #333; }
51.983361
784
0.689424
259571f36c91e8c9fd71813bca578c70053a8a0b
681
js
JavaScript
plugins/ui-main/app/controller/page.js
bitorjs/ui
c6cb6624d135101594951c1ee39461367db6dd2d
[ "MIT" ]
null
null
null
plugins/ui-main/app/controller/page.js
bitorjs/ui
c6cb6624d135101594951c1ee39461367db6dd2d
[ "MIT" ]
null
null
null
plugins/ui-main/app/controller/page.js
bitorjs/ui
c6cb6624d135101594951c1ee39461367db6dd2d
[ "MIT" ]
null
null
null
import { Controller, Get, Post } from 'bitorjs-decorators'; // import Toast from '../../packages/Toast'; @Controller('/') export default class { @Get('/:page?') async a(req) { let r = await this.ctx.$service.ff.aa(); console.log(r) const data = this.ctx.$store.state.ttt.data; const asyncView = import(`../view/src/${req.params.page}`) asyncView.then(res => { let items = data.filter(item => { return item.name == req.params.page; }) // this.ctx.Store.root.setItem("title", items[0].label); this.ctx.render(res.default) }).catch(res => { // Toast.fail('未找到页面') this.ctx.app.redirect('/') }) } }
23.482759
62
0.578561
435568be8b045cde271f32225527166bb1f4ab82
4,254
tsx
TypeScript
src/services/userService.tsx
xmj-alliance/xmjcraft-client-react
3300039698828b480b9c1294b410b7a6adc80d16
[ "MIT" ]
null
null
null
src/services/userService.tsx
xmj-alliance/xmjcraft-client-react
3300039698828b480b9c1294b410b7a6adc80d16
[ "MIT" ]
1
2022-02-13T18:58:50.000Z
2022-02-13T18:58:50.000Z
src/services/userService.tsx
xmj-alliance/xmjcraft-client-react
3300039698828b480b9c1294b410b7a6adc80d16
[ "MIT" ]
null
null
null
import { loader } from "graphql.macro"; import { useQuery, useMutation } from "@apollo/client"; import User from "../models/user"; import CUDMessage from "../models/cudMessage"; const GET_USERS = loader("./userGraph/getList.graphql"); const GET_USER = loader("./userGraph/getSingle.graphql"); const ADD_USER = loader("./userGraph/addSingle.graphql"); const UPDATE_USER = loader("./userGraph/updateSingle.graphql"); const DELETE_USER = loader("./userGraph/deleteSingle.graphql"); export const useUserList = () => { const { loading: isQueryLoading, error: queryError, data } = useQuery<{users: User[]}>(GET_USERS); if (queryError) { console.error(queryError); } const users = (data? data.users: undefined); return { isQueryLoading, queryError, users } } export const useUserDetail = (dbname?: string) => { const { loading: isQueryLoading, error: queryError, data } = useQuery<{user: User}>( GET_USER, { variables: { dbname: dbname } } ); if (queryError) { console.error(queryError); } const user = (data? data.user: undefined); return { isQueryLoading, queryError, user } } export const useUserAddition = (newUser: User) => { return useMutation( ADD_USER, { update: (cache, response) => { const message = response.data.addUser as CUDMessage; if (!message.ok) { return; } // update local cache const cacheResponse = cache.readQuery<{users: User[]}>({ query: GET_USERS }); if (!cacheResponse) { return; } cache.writeQuery({ query: GET_USERS, data: { users: cacheResponse.users.concat(newUser)}, }); } } ); } export const useUserUpdate = (updatedUser?: User) => { return useMutation( UPDATE_USER, { update: (cache, response) => { const message = response.data.updateUser as CUDMessage; if (!message.ok) { return; } if (!updatedUser) { return; } // update getSingle cache cache.writeQuery({ query: GET_USER, variables: { dbname: updatedUser.dbname }, data: { user: updatedUser }, }); // update getList cache let cacheResponse: {users: User[]} | null = null; try { cacheResponse = cache.readQuery({ query: GET_USERS }); } catch (error) { console.log(error); } if (!cacheResponse) { return; } let userInCacheIndex = cacheResponse.users.findIndex(u => u.dbname === updatedUser.dbname); if (userInCacheIndex < 0) { return; } const newUsers = cacheResponse.users.slice(); newUsers[userInCacheIndex] = updatedUser; const newData = { users: newUsers } cache.writeQuery({ query: GET_USERS, data: newData, }); } } ); } export const useUserDeletion = (dbname?: string) => { return useMutation( DELETE_USER, { update: (cache, response) => { const message = response.data.deleteUser as CUDMessage; if (!message.ok) { return; } if (!dbname) { return; } // update getSingle cache (we have a problem here. not in fact evicted) // cache.evict(dbname) cache.gc(); // cache.writeQuery({ // query: getSingleDefs, // variables: { // dbname: dbname // }, // data: {user: null}, // }); // update getList cache let cacheResponse: {users: User[]} | null = null; try { cacheResponse = cache.readQuery({ query: GET_USERS }); } catch (error) { console.log(error); } if (!cacheResponse) { return; } const newData = { users: cacheResponse.users.filter((u) => u.dbname !== dbname) } cache.writeQuery({ query: GET_USERS, data: newData, }); } } ); }
20.354067
100
0.5315
0499e524bb700504d56583762a0496b66a220938
1,350
kt
Kotlin
app/src/main/java/za/org/grassroot2/presenter/fragment/BaseFragmentPresenter.kt
grassrootza/grassroot-android-v2
a5851bfe2790ea965ebb7330b8cbb48abf9c4d4c
[ "BSD-3-Clause" ]
null
null
null
app/src/main/java/za/org/grassroot2/presenter/fragment/BaseFragmentPresenter.kt
grassrootza/grassroot-android-v2
a5851bfe2790ea965ebb7330b8cbb48abf9c4d4c
[ "BSD-3-Clause" ]
null
null
null
app/src/main/java/za/org/grassroot2/presenter/fragment/BaseFragmentPresenter.kt
grassrootza/grassroot-android-v2
a5851bfe2790ea965ebb7330b8cbb48abf9c4d4c
[ "BSD-3-Clause" ]
4
2018-02-11T11:58:59.000Z
2018-03-06T13:52:48.000Z
package za.org.grassroot2.presenter.fragment import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import timber.log.Timber import za.org.grassroot2.view.FragmentView abstract class BaseFragmentPresenter<T : FragmentView> { protected lateinit var view: T private val disposables = CompositeDisposable() abstract fun onViewCreated() open fun attach(view: T) { this.view = view EventBus.getDefault().register(this) } open fun detach(view: T) { disposables.clear() EventBus.getDefault().unregister(this) } protected fun disposableOnDetach(d: Disposable) { if (!disposables.isDisposed) { disposables.add(d) } } @Subscribe fun emptyEvent(o: Any) { } fun handleNetworkConnectionError(t: Throwable) { Timber.d(t) view.handleNoConnection() } fun handleNetworkUploadError(t: Throwable) { Timber.d(t) view.handleNoConnectionUpload() } fun io(): Scheduler = Schedulers.io() fun main(): Scheduler = AndroidSchedulers.mainThread() }
23.684211
58
0.701481
b8e0b910d0f79ab66b96f3295287fcf04b5226c9
1,335
h
C
src/pragma_openmp.h
mjklemm/nwchem-tce-triples-kernels
1ad8c18d1a01e65c1a451d5640e05079fc82de80
[ "Apache-2.0" ]
8
2018-03-29T01:59:31.000Z
2022-01-14T01:00:43.000Z
src/pragma_openmp.h
mjklemm/nwchem-tce-triples-kernels
1ad8c18d1a01e65c1a451d5640e05079fc82de80
[ "Apache-2.0" ]
null
null
null
src/pragma_openmp.h
mjklemm/nwchem-tce-triples-kernels
1ad8c18d1a01e65c1a451d5640e05079fc82de80
[ "Apache-2.0" ]
5
2018-08-13T23:25:59.000Z
2022-01-12T17:30:36.000Z
#ifndef PRAGMA_OPENMP_H #define PRAGMA_OPENMP_H #if defined(_OPENMP) && (( __STDC_VERSION__ >= 199901L ) || (__cplusplus >= 201103L )) #define PRAGMA(x) _Pragma(#x) #define OMP_PARALLEL PRAGMA(omp parallel) #define OMP_PARALLEL_FOR PRAGMA(omp parallel for schedule(static)) #define OMP_PARALLEL_FOR_SIMD PRAGMA(omp parallel for simd schedule(static)) #define OMP_FOR PRAGMA(omp for schedule(static)) #define OMP_FOR_SIMD PRAGMA(omp for simd schedule(static)) #define OMP_PARALLEL_FOR_COLLAPSE(n) PRAGMA(omp parallel for collapse(n) schedule(static)) #define OMP_PARALLEL_FOR_COLLAPSE2 OMP_PARALLEL_FOR_COLLAPSE(2) #define OMP_PARALLEL_FOR_COLLAPSE3 OMP_PARALLEL_FOR_COLLAPSE(3) #define OMP_PARALLEL_FOR_COLLAPSE4 OMP_PARALLEL_FOR_COLLAPSE(4) #define OMP_PARALLEL_FOR_REDUCE_ADD(r) PRAGMA(omp parallel for reduction (+ : r) schedule(static)) #define OMP_PARALLEL_FOR_SIMD_REDUCE_ADD(r) PRAGMA(omp parallel for simd reduction (+ : r) schedule(static)) #else #warning No OpenMP, either because compiler does not understand OpenMP or C99/C++11 _Pragma. #define OMP_PARALLEL #define OMP_PARALLEL_FOR #define OMP_FOR #define OMP_PARALLEL_FOR_COLLAPSE(n) #define OMP_PARALLEL_FOR_COLLAPSE2 #define OMP_PARALLEL_FOR_COLLAPSE3 #define OMP_PARALLEL_FOR_COLLAPSE4 #define OMP_PARALLEL_FOR_REDUCE_ADD(r) #endif #endif // PRAGMA_OPENMP_H
35.131579
108
0.820225
8192d4b9f65b414c43ebdcfefc6e59b2e1ae60a3
2,355
sql
SQL
SQL/DevSnippets/TimeExecution.sql
badlydressedboy/ssms-extended-templates
0461596e5e16a17bee41bf7f815cbbdae7028a20
[ "MIT" ]
null
null
null
SQL/DevSnippets/TimeExecution.sql
badlydressedboy/ssms-extended-templates
0461596e5e16a17bee41bf7f815cbbdae7028a20
[ "MIT" ]
null
null
null
SQL/DevSnippets/TimeExecution.sql
badlydressedboy/ssms-extended-templates
0461596e5e16a17bee41bf7f815cbbdae7028a20
[ "MIT" ]
null
null
null
/******INSERT INTO TOP OF TEST CODE*****/ declare @message varchar(500) declare @starttime datetime declare @stepstarttime datetime set @starttime = getdate() set @stepstarttime = getdate() /***************************************/ --CREATE THESE 2 PROCEDURES-------------------------------------------- alter PROCEDURE usp_PrintTestStepInfo (@stepname varchar(100), @starttime datetime, @stepstarttime datetime OUTPUT) AS BEGIN DECLARE @now datetime DECLARE @steptime bigint SET @steptime = datediff(ms,@stepstarttime,GETDATE()) SET @now = GETDATE() IF OBJECT_ID('TEMPDB..PerfTestData') is null CREATE TABLE TEMPDB..PerfTestData(stepname varchar(500), time bigint) INSERT TEMPDB..PerfTestData VALUES (@stepname, @steptime) declare @message varchar(500) SET @message = @stepname + '; Step Time: ' + convert(varchar(20),@steptime) + ' Running Time: ' + convert(varchar(20), datediff(ms,@starttime,@now)) --RAISERROR(@message, 0, 1) WITH NOWAIT--this line can really increase exe times, only use if necessary SET @stepstarttime = @now END CREATE PROCEDURE usp_DisplayTestStepInfoPercentages AS BEGIN DECLARE @totaltime float SET @totaltime = (select SUM(time) FROM TEMPDB..PerfTestData) * 1.0 select @totaltime as totaltime SELECT stepname, time, cast((time/@totaltime)*100 as decimal(12,2)) as percentage FROM TEMPDB..PerfTestData ORDER BY time desc DELETE FROM TEMPDB..PerfTestData END ---------------------------------------------------------------------------------------- --USAGE --CALL AFTER EVERY STEP IN TEST CODE exec usp_PrintTestStepInfo '1', @starttime, @stepstarttime OUTPUT--increment message string as calls are made --CALL AT THE END OF THE TEST CODE exec usp_DisplayTestStepInfoPercentages /**************NOTES************ The RAISERROR in usp_PrintTestStepInfo can fck exe time, it is expensive so only enable if totally necessary This is the definitive time that should be used when performance testing Actual execution plan query cost % does not take parrallelism into account and gives estimated cost based on 1 core So is not a real 'timing' of the way the execution took place The actual exe plan will tell you what operations were performed but the cost estimates arent that helpful Use profiler if you need to verify timings *******************************/
32.260274
115
0.684926
f3dd895fd45ec8e46107b8ef19e343f3f018f9c4
5,007
sql
SQL
liidimanageri_2.sql
Web-projektitII/Liidimanageri
deaf8c4eac62d6512b372e0a685dc7a01754b204
[ "MIT" ]
null
null
null
liidimanageri_2.sql
Web-projektitII/Liidimanageri
deaf8c4eac62d6512b372e0a685dc7a01754b204
[ "MIT" ]
null
null
null
liidimanageri_2.sql
Web-projektitII/Liidimanageri
deaf8c4eac62d6512b372e0a685dc7a01754b204
[ "MIT" ]
4
2020-04-27T06:28:42.000Z
2021-11-06T10:31:53.000Z
-- phpMyAdmin SQL Dump -- version 4.9.0.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: 11.05.2020 klo 09:50 -- Palvelimen versio: 10.4.6-MariaDB -- PHP Version: 7.3.9 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: `liidimanageri` -- -- -------------------------------------------------------- -- -- Rakenne taululle `alembic_version` -- CREATE TABLE `alembic_version` ( `version_num` varchar(32) COLLATE utf16_swedish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf16 COLLATE=utf16_swedish_ci; -- -- Vedos taulusta `alembic_version` -- INSERT INTO `alembic_version` (`version_num`) VALUES ('63abadb6da8e'); -- -------------------------------------------------------- -- -- Rakenne taululle `liidit` -- CREATE TABLE `liidit` ( `id` int(11) NOT NULL, `nimi` varchar(64) COLLATE utf16_swedish_ci DEFAULT NULL, `puhelinnumero` varchar(15) COLLATE utf16_swedish_ci DEFAULT NULL, `sahkoposti` varchar(64) COLLATE utf16_swedish_ci DEFAULT NULL, `yksikko` varchar(64) COLLATE utf16_swedish_ci DEFAULT NULL, `yhteinen` varchar(1) COLLATE utf16_swedish_ci DEFAULT NULL, `user_id` int(11) DEFAULT NULL, `updated` datetime DEFAULT NULL, `todennakoisyys` decimal(2,2) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf16 COLLATE=utf16_swedish_ci; -- -- Vedos taulusta `liidit` -- INSERT INTO `liidit` (`id`, `nimi`, `puhelinnumero`, `sahkoposti`, `yksikko`, `yhteinen`, `user_id`, `updated`, `todennakoisyys`) VALUES (1, 'Yritys Oy', '358505111969', 'yritys@yritys.fi', 'IT', '0', 1, '2020-04-26 20:06:10', '0.00'), (6, 'Yritys1 Oy', '358505111968', 'yritys1@yritys.fi', 'HR', '0', 1, '2020-04-27 05:38:21', '0.50'), (7, 'Yritys2 Oy', '358505111967', 'yritys2@yritys.fi', 'Business', '1', 1, '2020-04-27 05:49:11', '0.00'), (8, 'Yritys3 Oy', '358505111966', 'yritys3@yritys.fi', 'HR', '0', 1, '2020-04-27 06:06:59', '0.50'), (31, 'Yritys4 Oy', '358505111965', 'yritys4@yritys.fi', 'Business', NULL, 1, '2020-04-27 16:52:31', '0.00'), (32, 'Yritys5 Oy', '358505111964', 'yritys5@yritys.fi', 'Business', NULL, 1, '2020-04-27 16:54:17', '0.50'); -- -------------------------------------------------------- -- -- Rakenne taululle `roles` -- CREATE TABLE `roles` ( `id` int(11) NOT NULL, `name` varchar(64) COLLATE utf16_swedish_ci DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf16 COLLATE=utf16_swedish_ci; -- -------------------------------------------------------- -- -- Rakenne taululle `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `email` varchar(64) COLLATE utf16_swedish_ci DEFAULT NULL, `username` varchar(64) COLLATE utf16_swedish_ci DEFAULT NULL, `role_id` int(11) DEFAULT NULL, `password_hash` varchar(128) COLLATE utf16_swedish_ci DEFAULT NULL, `confirmed` tinyint(1) DEFAULT NULL ) ; -- -- Vedos taulusta `users` -- INSERT INTO `users` (`id`, `email`, `username`, `role_id`, `password_hash`, `confirmed`) VALUES (1, 'jukka.aula@kolumbus.fi', 'Jukka', NULL, 'pbkdf2:sha256:150000$HBFs2q3l$7fac075bb43429b7f49d9ea0a7635fc8d5b22edb5e6f3da64dd1a6be4fff1eac', 1); -- -- Indexes for dumped tables -- -- -- Indexes for table `alembic_version` -- ALTER TABLE `alembic_version` ADD PRIMARY KEY (`version_num`); -- -- Indexes for table `liidit` -- ALTER TABLE `liidit` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `nimi` (`nimi`), ADD UNIQUE KEY `puhelinnumero` (`puhelinnumero`), ADD UNIQUE KEY `ix_liidit_sahkoposti` (`sahkoposti`), ADD KEY `user_id` (`user_id`); -- -- Indexes for table `roles` -- ALTER TABLE `roles` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `name` (`name`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `ix_users_username` (`username`), ADD UNIQUE KEY `ix_users_email` (`email`), ADD KEY `role_id` (`role_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `liidit` -- ALTER TABLE `liidit` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=34; -- -- AUTO_INCREMENT for table `roles` -- ALTER TABLE `roles` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- Rajoitteet vedostauluille -- -- -- Rajoitteet taululle `liidit` -- ALTER TABLE `liidit` ADD CONSTRAINT `liidit_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Rajoitteet taululle `users` -- ALTER TABLE `users` ADD CONSTRAINT `users_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`); 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.360656
146
0.664869
cc8246a434d7e641b2dd9c62ffd05621df8c410c
599
h
C
Windows/allegro/include/allegro5/internal/aintern_prim_soft.h
Coolcord/Trake
3950fe2d99abcfd5e202191e4ba50e89c622e7c9
[ "MIT" ]
4
2015-04-27T01:13:05.000Z
2018-03-26T13:27:36.000Z
Windows/allegro/include/allegro5/internal/aintern_prim_soft.h
Coolcord/Trake
3950fe2d99abcfd5e202191e4ba50e89c622e7c9
[ "MIT" ]
null
null
null
Windows/allegro/include/allegro5/internal/aintern_prim_soft.h
Coolcord/Trake
3950fe2d99abcfd5e202191e4ba50e89c622e7c9
[ "MIT" ]
null
null
null
#ifndef __al_included_allegro5_aintern_prim_soft_h #define __al_included_allegro5_aintern_prim_soft_h struct ALLEGRO_BITMAP; struct ALLEGRO_VERTEX; int _al_draw_prim_soft(ALLEGRO_BITMAP* texture, const void* vtxs, const ALLEGRO_VERTEX_DECL* decl, int start, int end, int type); int _al_draw_prim_indexed_soft(ALLEGRO_BITMAP* texture, const void* vtxs, const ALLEGRO_VERTEX_DECL* decl, const int* indices, int num_vtx, int type); void _al_line_2d(ALLEGRO_BITMAP* texture, ALLEGRO_VERTEX* v1, ALLEGRO_VERTEX* v2); void _al_point_2d(ALLEGRO_BITMAP* texture, ALLEGRO_VERTEX* v); #endif
42.785714
151
0.814691
8c1e8f158ec87e1db923a951a697fb298a17c3b9
1,583
cs
C#
sdk/dotnet/Azure/Outputs/OceanVirtualNodeGroupAutoscaleAutoscaleHeadroom.cs
pulumi/pulumi-spotinst
75592d6293d63f6cec703722f2e02ff1fb1cca44
[ "ECL-2.0", "Apache-2.0" ]
4
2019-12-21T20:50:43.000Z
2021-12-01T20:57:38.000Z
sdk/dotnet/Azure/Outputs/OceanVirtualNodeGroupAutoscaleAutoscaleHeadroom.cs
pulumi/pulumi-spotinst
75592d6293d63f6cec703722f2e02ff1fb1cca44
[ "ECL-2.0", "Apache-2.0" ]
103
2019-12-09T22:03:16.000Z
2022-03-30T17:07:34.000Z
sdk/dotnet/Azure/Outputs/OceanVirtualNodeGroupAutoscaleAutoscaleHeadroom.cs
pulumi/pulumi-spotinst
75592d6293d63f6cec703722f2e02ff1fb1cca44
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.SpotInst.Azure.Outputs { [OutputType] public sealed class OceanVirtualNodeGroupAutoscaleAutoscaleHeadroom { /// <summary> /// Configure the number of CPUs to allocate for the headroom. CPUs are denoted in millicores, where 1000 millicores = 1 vCPU. /// </summary> public readonly int? CpuPerUnit; /// <summary> /// How many GPU cores should be allocated for headroom unit. /// </summary> public readonly int? GpuPerUnit; /// <summary> /// Configure the amount of memory (MiB) to allocate the headroom. /// </summary> public readonly int? MemoryPerUnit; /// <summary> /// The number of headroom units to maintain, where each unit has the defined CPU, memory and GPU. /// </summary> public readonly int NumOfUnits; [OutputConstructor] private OceanVirtualNodeGroupAutoscaleAutoscaleHeadroom( int? cpuPerUnit, int? gpuPerUnit, int? memoryPerUnit, int numOfUnits) { CpuPerUnit = cpuPerUnit; GpuPerUnit = gpuPerUnit; MemoryPerUnit = memoryPerUnit; NumOfUnits = numOfUnits; } } }
31.66
134
0.628553
38b2126a5a81f8a573fc523c142a3dc43384968f
1,618
php
PHP
custom/plugins/SwagPayPal/src/RestApi/V1/Resource/DisputeResource.php
masystech/pompidu
9929f5cf0d1afd96c9020b95ce1d60aa3f6b1677
[ "MIT" ]
null
null
null
custom/plugins/SwagPayPal/src/RestApi/V1/Resource/DisputeResource.php
masystech/pompidu
9929f5cf0d1afd96c9020b95ce1d60aa3f6b1677
[ "MIT" ]
null
null
null
custom/plugins/SwagPayPal/src/RestApi/V1/Resource/DisputeResource.php
masystech/pompidu
9929f5cf0d1afd96c9020b95ce1d60aa3f6b1677
[ "MIT" ]
null
null
null
<?php declare(strict_types=1); /* * (c) shopware AG <info@shopware.com> * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Swag\PayPal\RestApi\V1\Resource; use Swag\PayPal\RestApi\Client\PayPalClientFactoryInterface; use Swag\PayPal\RestApi\V1\Api\Disputes; use Swag\PayPal\RestApi\V1\Api\Disputes\Item as DisputeItem; use Swag\PayPal\RestApi\V1\RequestUriV1; class DisputeResource { /** * @var PayPalClientFactoryInterface */ private $payPalClientFactory; public function __construct(PayPalClientFactoryInterface $payPalClientFactory) { $this->payPalClientFactory = $payPalClientFactory; } public function list(?string $salesChannelId, ?string $disputeStateFilter = null): Disputes { $queryParameter = []; if ($disputeStateFilter !== null) { $queryParameter['dispute_state'] = $disputeStateFilter; } $requestUri = \sprintf('%s?%s', RequestUriV1::DISPUTES_RESOURCE, \http_build_query($queryParameter)); $response = $this->payPalClientFactory->getPayPalClient($salesChannelId)->sendGetRequest( $requestUri ); return (new Disputes())->assign($response); } public function get(string $disputeId, ?string $salesChannelId): DisputeItem { $response = $this->payPalClientFactory->getPayPalClient($salesChannelId)->sendGetRequest( \sprintf('%s/%s', RequestUriV1::DISPUTES_RESOURCE, $disputeId) ); return (new DisputeItem())->assign($response); } }
31.72549
109
0.689122
2589b1cabe83be17fcb208ccecaade69aa9ab695
2,631
js
JavaScript
assets/controllers/select/country_controller.js
benjaminjonard/koillection
67cfbbce3726cb84ec3d4b02ce01c60039ea0cd0
[ "MIT" ]
1
2020-04-19T05:09:20.000Z
2020-04-19T05:09:20.000Z
assets/controllers/select/country_controller.js
benjaminjonard/koillection
67cfbbce3726cb84ec3d4b02ce01c60039ea0cd0
[ "MIT" ]
10
2017-04-28T16:12:50.000Z
2020-05-02T15:45:23.000Z
assets/controllers/select/country_controller.js
benjaminjonard/koillection
67cfbbce3726cb84ec3d4b02ce01c60039ea0cd0
[ "MIT" ]
1
2020-04-19T22:53:36.000Z
2020-04-19T22:53:36.000Z
import { Controller } from 'stimulus'; import Translator from "../../js/translator.min"; import { TsSelect2 } from "../../node_modules/ts-select2/dist/core"; /* stimulusFetch: 'lazy' */ export default class extends Controller { connect() { let self = this; new TsSelect2(this.element, { templateSelection: function (country) { if (!country.id) { return ''; } console.log(country) return self.htmlToElement( '<div><span class="flag">' + country.element.dataset.flag + '</span><span>' + country.text + '</span></div>' ); }, templateResult: function (country) { if (!country.id) { return self.htmlToElement('<div><span class="select-placeholder">' + Translator.trans('select2.none') + '</span></div>'); } return self.htmlToElement( '<div><span class="flag">' + country.element.dataset.flag + '</span><span>' + country.text + '</span></div>' ); }, language: { noResults: function () { return Translator.trans('select2.no_results'); }, searching: function () { return Translator.trans('select2.searching'); } }, sorter: function (data) { if(data && data.length>1 && data[0].rank){ data.sort(function(a,b) {return (a.rank > b.rank) ? -1 : ((b.rank > a.rank) ? 1 : 0);} ); } return data; }, matcher:function(params, data) { if (typeof params.term === 'undefined' || params.term.trim() === '') { return data; } if (typeof data.text === 'undefined') { return null; } let idx = data.text.toLowerCase().indexOf(params.term.toLowerCase()); if (idx > -1) { let rank = { 'rank': (params.term.length / data.text.length) + (data.text.length-params.term.length-idx)/(3*data.text.length) }; return {...rank, ...data}; } return null; } }) } htmlToElement(html) { let template = document.createElement('template'); html = html.trim(); template.innerHTML = html; return template.content.firstChild; } }
35.554054
141
0.45496
88c9a66a9a624f90f38fe9e6f1fd10a47c84682c
897
cs
C#
WRLDCWarehouse.Core/Entities/BusReactor.cs
POSOCO/wrldc_data_warehouse_csharp
946a6576150f1ad32f5451fbed8fef1fcca3c8d8
[ "MIT" ]
null
null
null
WRLDCWarehouse.Core/Entities/BusReactor.cs
POSOCO/wrldc_data_warehouse_csharp
946a6576150f1ad32f5451fbed8fef1fcca3c8d8
[ "MIT" ]
null
null
null
WRLDCWarehouse.Core/Entities/BusReactor.cs
POSOCO/wrldc_data_warehouse_csharp
946a6576150f1ad32f5451fbed8fef1fcca3c8d8
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace WRLDCWarehouse.Core.Entities { public class BusReactor { public int BusReactorId { get; set; } [Required] public string Name { get; set; } public int BusReactorNumber { get; set; } public decimal MvarCapacity { get; set; } public DateTime CommDate { get; set; } public DateTime CodDate { get; set; } public DateTime DecommDate { get; set; } public Bus Bus { get; set; } public int BusId { get; set; } public Substation Substation { get; set; } public int SubstationId { get; set; } public State State { get; set; } public int StateId { get; set; } public IList<BusReactorOwner> BusReactorOwners { get; set; } public int WebUatId { get; set; } } }
28.03125
68
0.615385
38afc1065979195282f2886c2705df72568aeba6
5,151
php
PHP
resources/views/partials/admin/header.blade.php
babakmoeinifar/acgo
8a8abe12b08ec8d7b950be21a494e6ab8aee96f4
[ "MIT" ]
null
null
null
resources/views/partials/admin/header.blade.php
babakmoeinifar/acgo
8a8abe12b08ec8d7b950be21a494e6ab8aee96f4
[ "MIT" ]
null
null
null
resources/views/partials/admin/header.blade.php
babakmoeinifar/acgo
8a8abe12b08ec8d7b950be21a494e6ab8aee96f4
[ "MIT" ]
null
null
null
@php $users=\Auth::user(); $profile=asset(Storage::url('avatar/')); $currantLang = $users->currentLanguage(); $languages=Utility::languages(); @endphp <div class="navbar-bg"></div> <nav class="navbar navbar-expand-lg main-navbar"> <form class="form-inline mr-auto search-element" method="post"> <div class="easy-autocomplete"><input type="hidden" name="_token" value="ifSnVqGphjkOu1aqYvyflvadZqTOLssR8oVLlL9q" id="eac-5343" style="" autocomplete="off"> <div class="easy-autocomplete-container" id="eac-container-eac-5343"> <ul></ul> </div> </div> {{-- <ul class="navbar-nav mr-3">--}} {{-- <li><a href="#" data-toggle="sidebar" class="nav-link nav-link-lg"><i class="fas fa-bars"></i></a></li>--}} {{-- <li><a href="#" data-toggle="search" class="nav-link nav-link-lg d-sm-none"><i class="fas fa-search"></i></a></li>--}} {{-- </ul>--}} </form> <ul class="navbar-nav navbar-right"> @can('manage language') <li class="dropdown dropdown-list-toggle"><a href="#" data-toggle="dropdown" class="nav-link notification-toggle nav-link-lg language-dd"><i class="fas fa-language"></i></a> <div class="dropdown-menu dropdown-list dropdown-menu-right"> <div class="dropdown-header">{{__('Choose Language')}} </div> @can('create language') <a href="{{route('manage.language',[$currantLang])}}" class="dropdown-item btn manage-language-btn"> <span> {{ __('Create & Customize') }}</span> </a> @endcan <div class="dropdown-list-content dropdown-list-icons"> @foreach($languages as $language) @if(\Auth::guard('customer')->check()) <a href="{{route('customer.change.language',$language)}}" class="dropdown-item dropdown-item-unread @if($language == $currantLang) active-language @endif"> <span> {{Str::upper($language)}}</span> </a> @elseif(\Auth::guard('vender')->check()) <a href="{{route('vender.change.language',$language)}}" class="dropdown-item dropdown-item-unread @if($language == $currantLang) active-language @endif"> <span> {{Str::upper($language)}}</span> </a> @else <a href="{{route('change.language',$language)}}" class="dropdown-item dropdown-item-unread @if($language == $currantLang) active-language @endif"> <span> {{Str::upper($language)}}</span> </a> @endif @endforeach </div> </div> </li> @endcan <li class="dropdown"><a href="#" data-toggle="dropdown" class="nav-link dropdown-toggle nav-link-lg nav-link-user"> <img alt="image" src="{{(!empty($users->avatar)? $profile.'/'.$users->avatar : $profile.'/avatar.png')}}" class="rounded-circle mr-1"> <div class="d-sm-none d-lg-inline-block">{{__('Hi')}}, {{\Auth::user()->name}}</div> </a> <div class="dropdown-menu dropdown-menu-right"> <div class="dropdown-title">{{__('Welcome!')}}</div> @if(\Auth::guard('customer')->check()) <a href="{{route('customer.profile')}}" class="dropdown-item has-icon"> <i class="far fa-user"></i> {{__('My profile')}} </a> @elseif(\Auth::guard('vender')->check()) <a href="{{route('vender.profile')}}" class="dropdown-item has-icon"> <i class="far fa-user"></i> {{__('My profile')}} </a> @else <a href="{{route('profile')}}" class="dropdown-item has-icon"> <i class="far fa-user"></i> {{__('My profile')}} </a> @endif <div class="dropdown-divider"></div> <a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('frm-logout').submit();" class="dropdown-item has-icon text-danger"> <i class="fas fa-sign-out-alt"></i> <span>{{__('Logout')}}</span> </a> @if(\Auth::guard('customer')->check()) <form id="frm-logout" action="{{ route('customer.logout') }}" method="POST" class="d-none"> {{ csrf_field() }} </form> @else <form id="frm-logout" action="{{ route('logout') }}" method="POST" class="d-none"> {{ csrf_field() }} </form> @endif </div> </li> </ul> </nav>
57.233333
187
0.472141
d333a792b22287a53e6a8e9be7bfa42740958cef
1,508
css
CSS
src/modules/Dashboard/components/stateless/FilterForm/style.css
viseo-asia/cycle-hire-app-admin
a15c7ce3aa0433b266e5665bf05980d31f7bbbcc
[ "MIT" ]
null
null
null
src/modules/Dashboard/components/stateless/FilterForm/style.css
viseo-asia/cycle-hire-app-admin
a15c7ce3aa0433b266e5665bf05980d31f7bbbcc
[ "MIT" ]
6
2018-04-11T03:13:12.000Z
2018-04-23T02:54:15.000Z
src/modules/Dashboard/components/stateless/FilterForm/style.css
viseo-asia/cycle-hire-app-admin
a15c7ce3aa0433b266e5665bf05980d31f7bbbcc
[ "MIT" ]
null
null
null
/* Extra small devices (portrait phones, less than 576px) No media query since this is the default in Bootstrap */ .filter-form-container { padding: 30px; background-color: rgb(40, 63, 137); color: #fff; } .filter-form-container .date-picker input { color: white !important; } .filter-form-container .date-picker-container span, .filter-form-container .form-area-container span, .filter-form-container .form-docking-station-container span{ color: rgb(72, 181, 222); font-size: 12px; } .filter-form-container .date-picker > div { padding-bottom: 20px; width: 100% !important; } .filter-form-container .reset-button-container { display: block !important; } .filter-form-container .date-picker-container { padding: 0 15px; } /* Small devices (landscape phones, 576px and up) */ @media (min-width: 576px) {} /* Medium devices (tablets, 768px and up) */ @media (min-width: 768px) {} /* Large devices (desktops, 992px and up) */ @media (min-width: 992px) { .filter-form-container { padding: 10px; } .filter-form-container .date-picker-container { float: left; width: 350px; } .filter-form-container .form-area-container, .filter-form-container .form-docking-station-container { float: left; width: 280px; } .filter-form-container .reset-button-container { display: none !important; } } /* Extra large devices (large desktops, 1200px and up) */ @media (min-width: 1200px) {}
24.721311
60
0.661804
743844b5c6848ff5e31c7a40539d7c8bc4c2e27d
1,568
css
CSS
public/assets/css/animate.css
garybarredaamaro/cleverpro
52cab6cba6e2788dff9156dff2cc7a5a0ac99383
[ "MIT" ]
null
null
null
public/assets/css/animate.css
garybarredaamaro/cleverpro
52cab6cba6e2788dff9156dff2cc7a5a0ac99383
[ "MIT" ]
null
null
null
public/assets/css/animate.css
garybarredaamaro/cleverpro
52cab6cba6e2788dff9156dff2cc7a5a0ac99383
[ "MIT" ]
null
null
null
.animate-enter { -webkit-animation: enter 125ms cubic-bezier(0.075, 0.820, 0.165, 1.000); animation: enter 125ms cubic-bezier(0.075, 0.820, 0.165, 1.000); display: block; position: relative; } @-webkit-keyframes enter { from { opacity: 0; height: 0px; } 20% { opacity: .5; } 40% { opacity: .15; color: red; } 60% { opacity: .75; } 80% { opacity: .3; } to { opacity: 1; height: 30px; } } @keyframes enter { from { opacity: 0; height: 0px; } 20% { opacity: .5; } 40% { opacity: .15; color: red; } 60% { opacity: .75; } 80% { opacity: .3; } to { opacity: 1; height: 30px; } } .animate-leave { -webkit-animation: leave 125ms cubic-bezier(0.075, 0.820, 0.165, 1.000); animation: leave 125ms cubic-bezier(0.075, 0.820, 0.165, 1.000); display: block; position: relative; } @-webkit-keyframes leave { to { opacity: 0; height: 0px; } 80% { opacity: .25; } 60% { opacity: .10; color: red; } 40% { opacity: .5; } 20% { opacity: .30; } from { opacity: 1; height: 30px; } } @keyframes leave { to { opacity: 0; height: 0px; } 80% { opacity: .25; } 60% { opacity: .10; color: red; } 40% { opacity: .5; } 20% { opacity: .30; } from { opacity: 1; height: 30px; } }
15.223301
76
0.452806
f4dc0386dde98b79ba554ef6719dc82cfc2d7e6f
641
ts
TypeScript
src/CollisionBox.ts
PxlBuzzard/game2020
b8bc6a9608c3925203bf086a8bddd6557c180602
[ "MIT" ]
null
null
null
src/CollisionBox.ts
PxlBuzzard/game2020
b8bc6a9608c3925203bf086a8bddd6557c180602
[ "MIT" ]
3
2021-06-17T13:22:22.000Z
2022-02-13T21:42:07.000Z
src/CollisionBox.ts
PxlBuzzard/game2020
b8bc6a9608c3925203bf086a8bddd6557c180602
[ "MIT" ]
null
null
null
import { useType, useNewComponent, Geometry, Polygon, Vector, Physics, useDraw, } from "@hex-engine/2d"; export default function CollisionBox( width: number, height: number, position: Vector ): void { useType(CollisionBox); const geometry = useNewComponent(() => Geometry({ shape: Polygon.rectangle(new Vector(width, height)), position: position, }) ); useNewComponent(() => Physics.Body(geometry, { isStatic: true })); useDraw((context) => { context.fillStyle = "#aaa"; //geometry.shape.draw(context, "fill"); }); }
20.03125
70
0.578783
e38c1aaffde78647d3970df7c3dacc580698349c
8,229
rb
Ruby
nuget/lib/dependabot/nuget/file_fetcher.rb
amclin/dependabot-core
fae1ce8cba6cb33e814efc87e9691b24ac318b55
[ "0BSD", "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
nuget/lib/dependabot/nuget/file_fetcher.rb
amclin/dependabot-core
fae1ce8cba6cb33e814efc87e9691b24ac318b55
[ "0BSD", "Naumen", "Condor-1.1", "MS-PL" ]
346
2019-08-20T14:35:46.000Z
2021-07-31T08:08:43.000Z
nuget/lib/dependabot/nuget/file_fetcher.rb
amclin/dependabot-core
fae1ce8cba6cb33e814efc87e9691b24ac318b55
[ "0BSD", "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
# frozen_string_literal: true require "dependabot/file_fetchers" require "dependabot/file_fetchers/base" module Dependabot module Nuget class FileFetcher < Dependabot::FileFetchers::Base require_relative "file_fetcher/import_paths_finder" require_relative "file_fetcher/sln_project_paths_finder" def self.required_files_in?(filenames) return true if filenames.any? { |f| f.match?(/^packages\.config$/i) } return true if filenames.any? { |f| f.end_with?(".sln") } return true if filenames.any? { |f| f.match?("^src$") } filenames.any? { |name| name.match?(%r{^[^/]*\.[a-z]{2}proj$}) } end def self.required_files_message "Repo must contain a .(cs|vb|fs)proj file or a packages.config." end private def fetch_files fetched_files = [] fetched_files += project_files fetched_files += directory_build_files fetched_files += imported_property_files fetched_files += packages_config_files fetched_files << nuget_config if nuget_config fetched_files << global_json if global_json fetched_files = fetched_files.uniq if project_files.none? && packages_config_files.none? if @missing_sln_project_file_errors&.any? raise @missing_sln_project_file_errors.first end raise( Dependabot::DependencyFileNotFound, File.join(directory, "<anything>.(cs|vb|fs)proj") ) end fetched_files end def project_files @project_files ||= begin project_files = [] project_files << csproj_file if csproj_file project_files << vbproj_file if vbproj_file project_files << fsproj_file if fsproj_file project_files += sln_project_files project_files end rescue Octokit::NotFound, Gitlab::Error::NotFound raise( Dependabot::DependencyFileNotFound, File.join(directory, "<anything>.(cs|vb|fs)proj") ) end def packages_config_files return @packages_config_files if @packages_config_files candidate_paths = [*project_files.map { |f| File.dirname(f.name) }, "."].uniq @packages_config_files ||= candidate_paths.map do |dir| file = repo_contents(dir: dir). find { |f| f.name.casecmp("packages.config").zero? } fetch_file_from_host(File.join(dir, file.name)) if file end.compact end def sln_file_names sln_files = repo_contents.select { |f| f.name.end_with?(".sln") } src_dir = repo_contents.any? { |f| f.name == "src" && f.type == "dir" } # If there are no sln files but there is a src directory, check that dir if sln_files.none? && src_dir sln_files = repo_contents(dir: "src"). select { |f| f.name.end_with?(".sln") }.map(&:dup). map { |file| file.tap { |f| f.name = "src/" + f.name } } end # Return `nil` if no sln files were found return if sln_files.none? sln_files.map(&:name) end def directory_build_files return @directory_build_files if @directory_build_files_checked @directory_build_files_checked = true attempted_paths = [] @directory_build_files = [] # Don't need to insert "." here, because Directory.Build.props files # can only be used by project files (not packages.config ones) project_files.map { |f| File.dirname(f.name) }.uniq.map do |dir| possible_paths = dir.split("/").flat_map.with_index do |_, i| base = dir.split("/").first(i + 1).join("/") possible_build_file_paths(base) end.reverse possible_paths += [ "Directory.Build.props", "Directory.build.props", "Directory.Build.targets", "Directory.build.targets" ] possible_paths.each do |path| break if attempted_paths.include?(path) attempted_paths << path file = fetch_file_if_present(path) @directory_build_files << file if file end end @directory_build_files end def possible_build_file_paths(base) [ Pathname.new(base + "/Directory.Build.props").cleanpath.to_path, Pathname.new(base + "/Directory.build.props").cleanpath.to_path, Pathname.new(base + "/Directory.Build.targets").cleanpath.to_path, Pathname.new(base + "/Directory.build.targets").cleanpath.to_path ] end def sln_project_files return [] unless sln_files @sln_project_files ||= begin paths = sln_files.flat_map do |sln_file| SlnProjectPathsFinder. new(sln_file: sln_file). project_paths end paths.map do |path| fetch_file_from_host(path) rescue Dependabot::DependencyFileNotFound => e @missing_sln_project_file_errors ||= [] @missing_sln_project_file_errors << e # Don't worry about missing files too much for now (at least # until we start resolving properties) nil end.compact end end def sln_files return unless sln_file_names @sln_files ||= sln_file_names. map { |sln_file_name| fetch_file_from_host(sln_file_name) }. select { |file| file.content.valid_encoding? } end def csproj_file @csproj_file ||= begin file = repo_contents.find { |f| f.name.end_with?(".csproj") } fetch_file_from_host(file.name) if file end end def vbproj_file @vbproj_file ||= begin file = repo_contents.find { |f| f.name.end_with?(".vbproj") } fetch_file_from_host(file.name) if file end end def fsproj_file @fsproj_file ||= begin file = repo_contents.find { |f| f.name.end_with?(".fsproj") } fetch_file_from_host(file.name) if file end end def nuget_config @nuget_config ||= begin file = repo_contents. find { |f| f.name.casecmp("nuget.config").zero? } file = fetch_file_from_host(file.name) if file file&.tap { |f| f.support_file = true } end end def global_json @global_json ||= fetch_file_if_present("global.json") end def imported_property_files imported_property_files = [] files = [*project_files, *directory_build_files] files.each do |proj_file| previously_fetched_files = project_files + imported_property_files imported_property_files += fetch_imported_property_files( file: proj_file, previously_fetched_files: previously_fetched_files ) end imported_property_files end def fetch_imported_property_files(file:, previously_fetched_files:) paths = ImportPathsFinder.new(project_file: file).import_paths + ImportPathsFinder.new(project_file: file).project_reference_paths paths.flat_map do |path| next if previously_fetched_files.map(&:name).include?(path) next if file.name == path next if path.include?("$(") fetched_file = fetch_file_from_host(path) grandchild_property_files = fetch_imported_property_files( file: fetched_file, previously_fetched_files: previously_fetched_files + [file] ) [fetched_file, *grandchild_property_files] rescue Dependabot::DependencyFileNotFound # Don't worry about missing files too much for now (at least # until we start resolving properties) nil end.compact end end end end Dependabot::FileFetchers.register("nuget", Dependabot::Nuget::FileFetcher)
31.895349
80
0.596184
362286ef7668881162b39da0e1e1b6c8babb3604
805
go
Go
vendor/github.com/vmware/go-vmware-nsxt/upgrade/logical_switch_info.go
Kristian-ZH/gardener-extension-provider-vsphere
61dedd9de991d0fdf9bfa3ae733216ccb30e1640
[ "MIT" ]
122
2018-02-15T14:47:55.000Z
2022-03-28T17:17:39.000Z
vendor/github.com/vmware/go-vmware-nsxt/upgrade/logical_switch_info.go
Kristian-ZH/gardener-extension-provider-vsphere
61dedd9de991d0fdf9bfa3ae733216ccb30e1640
[ "MIT" ]
100
2020-02-04T07:02:31.000Z
2022-03-29T14:49:37.000Z
vendor/github.com/vmware/go-vmware-nsxt/upgrade/logical_switch_info.go
Kristian-ZH/gardener-extension-provider-vsphere
61dedd9de991d0fdf9bfa3ae733216ccb30e1640
[ "MIT" ]
29
2020-01-31T11:50:49.000Z
2022-03-08T10:15:59.000Z
/* Copyright © 2017 VMware, Inc. All Rights Reserved. SPDX-License-Identifier: BSD-2-Clause Generated by: https://github.com/swagger-api/swagger-codegen.git */ package upgrade type LogicalSwitchInfo struct { // Number of instances on this logical switch InstancesCount int64 `json:"instances_count,omitempty"` // Flag to identify if this is the default logical switch IsDefaultLogicalSwitch bool `json:"is_default_logical_switch,omitempty"` // Name of the logical switch LogicalSwitchDisplayName string `json:"logical_switch_display_name,omitempty"` // ID of the logical switch LogicalSwitchId string `json:"logical_switch_id,omitempty"` // This tag is applied on cloud compute resource to be attached to this logical switch NsxSwitchTag string `json:"nsx_switch_tag,omitempty"` }
32.2
87
0.785093
b5943180d070cad3863e2b6191a1171421ee98ab
249
rb
Ruby
kitchen-tests/cookbooks/end_to_end/recipes/_sysctl.rb
bobchaos/chef
b84d384a058d2159c610771beccfe7728c28a688
[ "Apache-2.0" ]
1
2015-08-03T23:21:15.000Z
2015-08-03T23:21:15.000Z
kitchen-tests/cookbooks/end_to_end/recipes/_sysctl.rb
bobchaos/chef
b84d384a058d2159c610771beccfe7728c28a688
[ "Apache-2.0" ]
null
null
null
kitchen-tests/cookbooks/end_to_end/recipes/_sysctl.rb
bobchaos/chef
b84d384a058d2159c610771beccfe7728c28a688
[ "Apache-2.0" ]
null
null
null
# # Cookbook:: end_to_end # Recipe:: sysctl # sysctl "vm.swappiness" do value 19 end sysctl "kernel.msgmax" do value 9000 end sysctl "kernel.msgmax" do action :remove end sysctl_param "bogus.sysctl_val" do value 9000 action :remove end
11.857143
34
0.722892
e258ff324f614b881f4d977f44e64c367f14bf95
41
js
JavaScript
Client/src/Redux/costants.js
porosh2002/Boilerplate-code
409ad5c89c25d855038057b451e975c02ad54837
[ "RSA-MD" ]
null
null
null
Client/src/Redux/costants.js
porosh2002/Boilerplate-code
409ad5c89c25d855038057b451e975c02ad54837
[ "RSA-MD" ]
null
null
null
Client/src/Redux/costants.js
porosh2002/Boilerplate-code
409ad5c89c25d855038057b451e975c02ad54837
[ "RSA-MD" ]
null
null
null
export const SET_USER_ID = 'SET_USER_ID';
41
41
0.804878
4fe5c526c6e9ac03a7fe87b042ee373c83e82f33
9,467
rb
Ruby
lib/graphql/compatibility/query_parser_specification.rb
speakingcode/graphql-ruby
90022e09d3d96031c44c6c0fe87304f36f319bbb
[ "MIT" ]
7
2018-11-14T17:09:39.000Z
2020-11-11T02:14:19.000Z
lib/graphql/compatibility/query_parser_specification.rb
bertiecroll/graphql-ruby
7fc54bf322ed9cde9db594c519ae41539d41b33b
[ "MIT" ]
3
2020-07-17T01:28:50.000Z
2021-05-08T20:18:41.000Z
lib/graphql/compatibility/query_parser_specification.rb
bertiecroll/graphql-ruby
7fc54bf322ed9cde9db594c519ae41539d41b33b
[ "MIT" ]
2
2018-06-10T05:51:36.000Z
2020-02-07T16:19:56.000Z
# frozen_string_literal: true require "graphql/compatibility/query_parser_specification/query_assertions" require "graphql/compatibility/query_parser_specification/parse_error_specification" module GraphQL module Compatibility # This asserts that a given parse function turns a string into # the proper tree of {{GraphQL::Language::Nodes}}. module QueryParserSpecification # @yieldparam query_string [String] A query string to parse # @yieldreturn [GraphQL::Language::Nodes::Document] # @return [Class<Minitest::Test>] A test suite for this parse function def self.build_suite(&block) Class.new(Minitest::Test) do include QueryAssertions include ParseErrorSpecification @@parse_fn = block def parse(query_string) @@parse_fn.call(query_string) end def test_it_parses_queries document = parse(QUERY_STRING) query = document.definitions.first assert_valid_query(query) assert_valid_fragment(document.definitions.last) assert_valid_variable(query.variables.first) field = query.selections.first assert_valid_field(field) assert_valid_variable_argument(field.arguments.first) assert_valid_literal_argument(field.arguments.last) assert_valid_directive(field.directives.first) fragment_spread = query.selections[1].selections.last assert_valid_fragment_spread(fragment_spread) assert_valid_typed_inline_fragment(query.selections[2]) assert_valid_typeless_inline_fragment(query.selections[3]) end def test_it_parses_unnamed_queries document = parse("{ name, age, height }") operation = document.definitions.first assert_equal 1, document.definitions.length assert_equal "query", operation.operation_type assert_equal nil, operation.name assert_equal 3, operation.selections.length end def test_it_parses_the_introspection_query parse(GraphQL::Introspection::INTROSPECTION_QUERY) end def test_it_parses_inputs query_string = %| { field( int: 3, float: 4.7e-24, bool: false, string: "☀︎🏆 \\b \\f \\n \\r \\t \\" \u00b6 \\u00b6 / \\/", enum: ENUM_NAME, array: [7, 8, 9] object: {a: [1,2,3], b: {c: "4"}} unicode_bom: "\xef\xbb\xbfquery" keywordEnum: on nullValue: null nullValueInObject: {a: null, b: "b"} nullValueInArray: ["a", null, "b"] blockString: """ Hello, World """ ) } | document = parse(query_string) inputs = document.definitions.first.selections.first.arguments assert_equal 3, inputs[0].value, "Integers" assert_equal 0.47e-23, inputs[1].value, "Floats" assert_equal false, inputs[2].value, "Booleans" assert_equal %|☀︎🏆 \b \f \n \r \t " ¶ ¶ / /|, inputs[3].value, "Strings" assert_instance_of GraphQL::Language::Nodes::Enum, inputs[4].value assert_equal "ENUM_NAME", inputs[4].value.name, "Enums" assert_equal [7,8,9], inputs[5].value, "Lists" obj = inputs[6].value assert_equal "a", obj.arguments[0].name assert_equal [1,2,3], obj.arguments[0].value assert_equal "b", obj.arguments[1].name assert_equal "c", obj.arguments[1].value.arguments[0].name assert_equal "4", obj.arguments[1].value.arguments[0].value assert_equal %|\xef\xbb\xbfquery|, inputs[7].value, "Unicode BOM" assert_equal "on", inputs[8].value.name, "Enum value 'on'" assert_instance_of GraphQL::Language::Nodes::NullValue, inputs[9].value args = inputs[10].value.arguments assert_instance_of GraphQL::Language::Nodes::NullValue, args.find{ |arg| arg.name == 'a' }.value assert_equal 'b', args.find{ |arg| arg.name == 'b' }.value values = inputs[11].value assert_equal 'a', values[0] assert_instance_of GraphQL::Language::Nodes::NullValue, values[1] assert_equal 'b', values[2] block_str_value = inputs[12].value assert_equal "Hello,\n World", block_str_value end def test_it_doesnt_parse_nonsense_variables query_string_1 = "query Vars($var1) { cheese(id: $var1) { flavor } }" query_string_2 = "query Vars2($var1: Int = $var1) { cheese(id: $var1) { flavor } }" err_1 = assert_raises(GraphQL::ParseError) do parse(query_string_1) end assert_equal [1,17], [err_1.line, err_1.col] err_2 = assert_raises(GraphQL::ParseError) do parse(query_string_2) end assert_equal [1,26], [err_2.line, err_2.col] end def test_enum_value_definitions_have_a_position document = parse(""" enum Enum { VALUE } """) assert_equal [3, 17], document.definitions[0].values[0].position end def test_field_definitions_have_a_position document = parse(""" type A { field: String } """) assert_equal [3, 17], document.definitions[0].fields[0].position end def test_input_value_definitions_have_a_position document = parse(""" input A { field: String } """) assert_equal [3, 17], document.definitions[0].fields[0].position end def test_parses_when_there_are_no_interfaces schema = " type A { a: String } " document = parse(schema) assert_equal [], document.definitions[0].interfaces.map(&:name) end def test_parses_implements_with_leading_ampersand schema = " type A implements & B { a: String } " document = parse(schema) assert_equal ["B"], document.definitions[0].interfaces.map(&:name) assert_equal [2, 35], document.definitions[0].interfaces[0].position end def test_parses_implements_with_leading_ampersand_and_multiple_interfaces schema = " type A implements & B & C { a: String } " document = parse(schema) assert_equal ["B", "C"], document.definitions[0].interfaces.map(&:name) assert_equal [2, 35], document.definitions[0].interfaces[0].position assert_equal [2, 39], document.definitions[0].interfaces[1].position end def test_parses_implements_without_leading_ampersand schema = " type A implements B { a: String } " document = parse(schema) assert_equal ["B"], document.definitions[0].interfaces.map(&:name) assert_equal [2, 33], document.definitions[0].interfaces[0].position end def test_parses_implements_without_leading_ampersand_and_multiple_interfaces schema = " type A implements B & C { a: String } " document = parse(schema) assert_equal ["B", "C"], document.definitions[0].interfaces.map(&:name) assert_equal [2, 33], document.definitions[0].interfaces[0].position assert_equal [2, 37], document.definitions[0].interfaces[1].position end def test_supports_old_syntax_for_parsing_multiple_interfaces schema = " type A implements B, C { a: String } " document = parse(schema) assert_equal ["B", "C"], document.definitions[0].interfaces.map(&:name) assert_equal [2, 33], document.definitions[0].interfaces[0].position assert_equal [2, 36], document.definitions[0].interfaces[1].position end end end QUERY_STRING = %| query getStuff($someVar: Int = 1, $anotherVar: [String!] ) @skip(if: false) { myField: someField(someArg: $someVar, ok: 1.4) @skip(if: $anotherVar) @thing(or: "Whatever") anotherField(someArg: [1,2,3]) { nestedField ... moreNestedFields @skip(if: true) } ... on OtherType @include(unless: false){ field(arg: [{key: "value", anotherKey: 0.9, anotherAnotherKey: WHATEVER}]) anotherField } ... { id } } fragment moreNestedFields on NestedType @or(something: "ok") { anotherNestedField @enum(directive: true) } | end end end
35.724528
108
0.5516
23ef476e9cb056bdbc4b1bab4ec1d9d19d3364bd
676
js
JavaScript
static/js/codeinput.js
sgaist/nodebb-plugin-codeinput
aad83c61eaf2ea0d11fa5f3f0d451c9ed5526d10
[ "MIT" ]
null
null
null
static/js/codeinput.js
sgaist/nodebb-plugin-codeinput
aad83c61eaf2ea0d11fa5f3f0d451c9ed5526d10
[ "MIT" ]
null
null
null
static/js/codeinput.js
sgaist/nodebb-plugin-codeinput
aad83c61eaf2ea0d11fa5f3f0d451c9ed5526d10
[ "MIT" ]
null
null
null
$('document').ready(function() { require(['composer', 'composer/controls'], function(composer, controls) { composer.addButton('fa fa-code', function(textarea, selectionStart, selectionEnd) { if(selectionStart === selectionEnd){ controls.insertIntoTextarea(textarea, "```\n//your code here\n```"); controls.updateTextareaSelection(textarea, selectionStart + 4, selectionStart + 20); } else { controls.wrapSelectionInTextareaWith(textarea, '```\n', '\n```'); controls.updateTextareaSelection(textarea, selectionStart + 4, selectionEnd + 4); } }); }); });
52
100
0.599112
e7579491809c59f1f476a2bd1f6c21e03810ff1c
5,348
php
PHP
login_register/exportData/ExportCustomerData/index.php
RifaiM/i-hostconf
7b218b2c5bf5f8f56d1066a3a2f8edf0387f5e5d
[ "MIT" ]
null
null
null
login_register/exportData/ExportCustomerData/index.php
RifaiM/i-hostconf
7b218b2c5bf5f8f56d1066a3a2f8edf0387f5e5d
[ "MIT" ]
null
null
null
login_register/exportData/ExportCustomerData/index.php
RifaiM/i-hostconf
7b218b2c5bf5f8f56d1066a3a2f8edf0387f5e5d
[ "MIT" ]
2
2020-11-04T08:20:25.000Z
2020-11-06T07:37:01.000Z
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <meta http-equiv="X-UA-Compatible" content="ie-edge"> <link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet"> <title>Live search Database</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Popper JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css" integrity="sha256-mmgLkCYLUQbXn0B1SRqzHar6dCnv9oZFPEC1g1cwlkk=" crossorigin="anonymous" /> <link rel="stylesheet" href="../css/customer.css"> <link rel="icon" type="image/png" href="../img/I-HostConf.png" /> </head> <body class="bg-secondary"> <nav class="navbar navbar-expand-md bg-dark navbar-dark"> <!-- Brand --> <a class="navbar-brand" href="#"><img src="../img/I-HostConf.png"></a> <!-- Toggler/collapsibe Button --> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar"> <span class="navbar-toggler-icon"></span> </button> <!-- Navbar links --> <div class="collapse navbar-collapse" id="collapsibleNavbar"> <ul class="navbar-nav"> <li class="nav-item"> <form method="post" action="export.php"> <input type="submit" name="export" value="CSV Export"/> </form> </li> <li class="nav-item"> <a class="dashboard" href="/Conference/login_register/admin/admin.php">Dashboard</i></a> </li> <li class="nav-item"> </li> </ul> </div> </nav> <div class="container-fluid"> <div class="row justify-content-center"> <div class="col-md-10 bg-light mt-2 rounded pb-3"> <h2 class="text-primary p-2" >Search Data Customer</h2> <hr> <a href="#menu" id="toggle"><span></span></a> <div id="menu"> <ul> <li><a href="/Conference/login_register/exportData/ExportLoginData/index.php" >Export data User Login</a></li> <li><a href="/Conference/login_register/exportData/ExportOrdersData/index.php" >Export data Orders</a></li> <li><a href="/Conference/login_register/exportData/ExportAddressData/index.php" >Export data Addresses</a></li> <li><a href="/Conference/login_register/exportData/ExportPaymentsData/index.php" >Export data Payments</a></li> </ul> </div> <div class="form-inline pl-3"> <label for="search" class="font-weight-bold lead text-dark" >Search</label>&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="search" id="search_text" class="form-control form-control-md rounded-2 border-secondary" placeholder="type here.." > </div> <?php include '../config.php'; $stmt = $conn->prepare("SELECT * FROM customers ORDER BY id ASC"); $stmt->execute(); $result = $stmt->get_result(); ?> <table class="table table-hover table-light table-stripped" id="table-data" > <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>Created at</th> <th>Updated at</th> </tr> </thead> <tbody> <?php while($row = $result->fetch_assoc()) { ?> <tr> <td><?= $row['id']; ?></td> <td><?= $row['name']; ?></td> <td><?= $row['email']; ?></td> <td><?= $row['created_at']; ?></td> <td><?= $row['updated_at']; ?></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <script type="text/javascript"> $(document).ready(function() { $("#search_text").keyup(function() { var search = $(this).val(); $.ajax({ url: 'action.php', method: 'post', data: {query:search}, success: function(response) { $("#table-data").html(response); } }); }); }); </script> <script src="../js/menu.js"></script> </body> </html>
43.479675
199
0.489903
c47dd1920ebc401e7714ad43dcd2773e70a57d3d
4,424
cc
C++
DQMOffline/L1Trigger/src/L1TCommon.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
DQMOffline/L1Trigger/src/L1TCommon.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
DQMOffline/L1Trigger/src/L1TCommon.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "DQMOffline/L1Trigger/interface/L1TCommon.h" #include "DataFormats/Math/interface/deltaR.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include <iostream> namespace dqmoffline { namespace l1t { std::vector<unsigned int> getTriggerIndices(const std::vector<std::string> &requestedTriggers, const std::vector<std::string> &triggersInEvent) { std::vector<unsigned int> triggerIndices; for (auto requestedTriggerName : requestedTriggers) { std::string name(requestedTriggerName); std::size_t wildcarPosition = name.find("*"); if (wildcarPosition != std::string::npos) { // take everything up to the wildcard name = name.substr(0, wildcarPosition - 1); } unsigned int triggerIndex = 0; for (auto triggerName : triggersInEvent) { if (triggerName.find(name) != std::string::npos) { triggerIndices.push_back(triggerIndex); break; } ++triggerIndex; } } return triggerIndices; } std::vector<bool> getTriggerResults(const std::vector<unsigned int> &triggers, const edm::TriggerResults &triggerResults) { std::vector<bool> results; results.resize(triggers.size()); for (unsigned int index = 0; index < triggers.size(); ++index) { if (triggers[index] >= triggerResults.size()) { results[index] = false; continue; } if (triggerResults.accept(triggers[index])) { results[index] = true; } else { results[index] = false; } } return results; } std::vector<unsigned int> getFiredTriggerIndices(const std::vector<unsigned int> &triggers, const std::vector<bool> &triggerResults) { std::vector<unsigned int> results; // std::copy_if instead? for (unsigned int i = 0; i < triggerResults.size(); ++i) { if (triggerResults[i]) { results.push_back(triggers[i]); } } return results; } bool passesAnyTriggerFromList(const std::vector<unsigned int> &triggers, const edm::TriggerResults &triggerResults) { std::vector<bool> results = dqmoffline::l1t::getTriggerResults(triggers, triggerResults); if (std::count(results.begin(), results.end(), true) == 0) { return false; } return true; } trigger::TriggerObjectCollection getTriggerObjects(const std::vector<edm::InputTag> &hltFilters, const trigger::TriggerEvent &triggerEvent) { trigger::TriggerObjectCollection triggerObjects = triggerEvent.getObjects(); trigger::TriggerObjectCollection results; for (auto filter : hltFilters) { const unsigned filterIndex = triggerEvent.filterIndex(filter); if (filterIndex < triggerEvent.sizeFilters()) { const trigger::Keys triggerKeys(triggerEvent.filterKeys(filterIndex)); const size_t nTriggers = triggerEvent.filterIds(filterIndex).size(); for (size_t i = 0; i < nTriggers; ++i) { results.push_back(triggerObjects[triggerKeys[i]]); } } } // sort by ET typedef trigger::TriggerObject trigObj; std::sort(results.begin(), results.end(), [](const trigObj &obj1, const trigObj &obj2) { return obj1.et() > obj2.et(); }); return results; } std::vector<edm::InputTag> getHLTFilters(const std::vector<unsigned int> &triggers, const HLTConfigProvider &hltConfig, const std::string triggerProcess) { std::vector<edm::InputTag> results; for (auto trigger : triggers) { unsigned int hltIndexOffset(2); unsigned int moduleIndex = hltConfig.size(trigger) - hltIndexOffset; const std::vector<std::string> modules(hltConfig.moduleLabels(trigger)); std::string module(modules[moduleIndex]); edm::InputTag filterInputTag = edm::InputTag(module, "", triggerProcess); results.push_back(filterInputTag); } return results; } trigger::TriggerObjectCollection getMatchedTriggerObjects( double eta, double phi, double maxDeltaR, const trigger::TriggerObjectCollection triggerObjects) { trigger::TriggerObjectCollection results; typedef trigger::TriggerObject trigObj; std::copy_if(triggerObjects.begin(), triggerObjects.end(), std::back_inserter(results), [eta, phi, maxDeltaR](const trigObj &obj) { return deltaR(obj.eta(), obj.phi(), eta, phi) < maxDeltaR; }); return results; } } // l1t } // dqmoffline
32.529412
80
0.667043
1aa277be8a7c66e5d8398dd28e2a5e0dd0e5f86a
2,585
py
Python
Python/file.py
MarcMeinhardt/2DTerrainGeneration
396e035ee13f96da09eeb299cde6884ea3faabcd
[ "MIT" ]
1
2022-03-12T22:28:02.000Z
2022-03-12T22:28:02.000Z
Python/file.py
MarcMeinhardt/2DTerrainGeneration
396e035ee13f96da09eeb299cde6884ea3faabcd
[ "MIT" ]
null
null
null
Python/file.py
MarcMeinhardt/2DTerrainGeneration
396e035ee13f96da09eeb299cde6884ea3faabcd
[ "MIT" ]
null
null
null
# # Author : Marc Meinhardt # Build Date : 07/20/2021 # Title : Generative Art # from PIL import ImageTk, Image, ImageChops, ImageFilter import os, os.path # MARKUP - : Properties imageName = "chunk1" fileExtension = ".jpg" mainDirPath = "." inputPath = "input" size_1020 = (1020,1020) # MARKUP - : filters # Rank Filter # Marble Filter # Diffuse Filter # Bump Filter # Noise Filter # Pointillize Filter # Smear Filter # Despeckle Filter # Oil Filter # Sharpen Filter # Edge Filter # Laplace Filter filters = { "blur": ImageFilter.BLUR, "contour": ImageFilter.CONTOUR, "detail": ImageFilter.DETAIL, "edge enhance": ImageFilter.EDGE_ENHANCE, "edge enhance more": ImageFilter.EDGE_ENHANCE_MORE, "emboss": ImageFilter.EMBOSS, "find edges": ImageFilter.FIND_EDGES, "sharpen": ImageFilter.SHARPEN, "smooth": ImageFilter.SMOOTH, "smooth more": ImageFilter.SMOOTH_MORE, "box blur": ImageFilter.BoxBlur(10), "gaussian blur": ImageFilter.GaussianBlur(25), "unsharp mark": ImageFilter.UnsharpMask, "rank filter": ImageFilter.RankFilter(size=3, rank=0), "median": ImageFilter.MedianFilter(size=3), } # MARKUP - : Functions if __name__ == "__main__": for f in os.listdir(inputPath): if f.endswith(fileExtension): im = Image.open(os.path.join(inputPath,f)) fn, fext = os.path.splitext(f) print( f, "|", "image size :", im.size, "|", "colour mode: ", im.mode ) ####################### # MARKUP - : Image Processing imLevel1_ProcessedRank = im.filter(filters["rank filter"]) imLevel2_ProcessedRank = imLevel1_ProcessedRank.filter(filters["median"]) #imProcessedRank = im.filter(ImageFilter.RankFilter(size=3, rank=8)) #imProcessedMedian = imProcessedRank.filter(ImageFilter.MedianFilter(size=3)) #imProcessedBlur = imProcessedMedian.filter(ImageFilter.BLUR) #imProcessedEmboss = imProcessedBlur.filter(ImageFilter.EMBOSS) #imProcessedFindEdges = imProcessedBlur.filter(ImageFilter.FIND_EDGES) ####################### # MARKUP - : save images in folders imLevel2_ProcessedRank.save('./output/{}_processed{}'.format(fn, fext)) # MARKUP - : convert to png and save in png folder # i.save('./output/pngs/{}.png'.format(fn)) # MARKUP - : resize and save in 1020 folder #i.thumbnail(size_1020) #i.save('output/{}_1020{}'.format(fn, fext))
24.619048
89
0.629014
ef4d24e2b0a43a6ca1fe973a3e48ee63231ff965
1,077
c
C
ui_menu.c
Ydos2/MUL_my_hunter_2019
27524b2ab654c675e2b6d0f1987c46cd11078867
[ "MIT" ]
null
null
null
ui_menu.c
Ydos2/MUL_my_hunter_2019
27524b2ab654c675e2b6d0f1987c46cd11078867
[ "MIT" ]
null
null
null
ui_menu.c
Ydos2/MUL_my_hunter_2019
27524b2ab654c675e2b6d0f1987c46cd11078867
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2019 ** ui_menu ** File description: ** ui_menu */ #include "include/frambuffer.h" #include "include/my.h" void game_over(sfRenderWindow *window, ui_t *ui_struct) { if (ui_struct->sound_die == 0) { sound_die(); ui_struct->sound_die = 1; } display_ui_gameover(window); } void create_menu(sfRenderWindow *window, ui_t *ui_struct) { display_ui_menu(window); } void display_ui_menu(sfRenderWindow *window) { int c = 0; sfVector2f position_score; position_score.x = 650; position_score.y = 350; sfFont* font = NULL; sfText *score = NULL; font = sfFont_createFromFile("krisha/Krisha-Regular.otf"); score = sfText_create(); sfText_setString(score, "Start to HUNT!"); sfText_setFont(score, font); sfText_setCharacterSize(score, 200); sfText_setOutlineColor(score, sfWhite); sfText_setOutlineThickness(score, 2); sfText_setPosition(score, position_score); sfText_setColor(score, sfBlack); sfRenderWindow_drawText(window, score, NULL); sfFont_destroy(font); }
23.933333
62
0.694522
141fa0517a2fd1b1d4f95ced44c3bd0af6939b1d
6,421
ts
TypeScript
test/test-files/brighterscript/project-with-bsfmt/node_modules/brighterscript/dist/Scope.d.ts
andersondanilo/ale
843c8f9dfa8f8982fc455459158c55bc4bc061c2
[ "BSD-2-Clause" ]
null
null
null
test/test-files/brighterscript/project-with-bsfmt/node_modules/brighterscript/dist/Scope.d.ts
andersondanilo/ale
843c8f9dfa8f8982fc455459158c55bc4bc061c2
[ "BSD-2-Clause" ]
null
null
null
test/test-files/brighterscript/project-with-bsfmt/node_modules/brighterscript/dist/Scope.d.ts
andersondanilo/ale
843c8f9dfa8f8982fc455459158c55bc4bc061c2
[ "BSD-2-Clause" ]
null
null
null
import type { CompletionItem, Position, Range } from 'vscode-languageserver'; import { Location } from 'vscode-languageserver'; import type { CallableContainer, BsDiagnostic, BscFile } from './interfaces'; import type { Program } from './Program'; import type { NamespaceStatement, Statement, NewExpression, FunctionStatement, ClassStatement } from './parser'; import { ParseMode } from './parser'; import { Cache } from './Cache'; /** * A class to keep track of all declarations within a given scope (like source scope, component scope) */ export declare class Scope { name: string; dependencyGraphKey: string; program: Program; constructor(name: string, dependencyGraphKey: string, program: Program); /** * Indicates whether this scope needs to be validated. * Will be true when first constructed, or anytime one of its dependencies changes */ readonly isValidated: boolean; protected programHandles: (() => void)[]; protected cache: Cache; /** * A dictionary of namespaces, indexed by the lower case full name of each namespace. * If a namespace is declared as "NameA.NameB.NameC", there will be 3 entries in this dictionary, * "namea", "namea.nameb", "namea.nameb.namec" */ get namespaceLookup(): Record<string, NamespaceContainer>; /** * Get the class with the specified name. * @param className - the all-lower-case namespace-included class name */ getClass(className: string): ClassStatement; /** * A dictionary of all classes in this scope. This includes namespaced classes always with their full name. * The key is stored in lower case */ private getClassMap; /** * The list of diagnostics found specifically for this scope. Individual file diagnostics are stored on the files themselves. */ protected diagnostics: BsDiagnostic[]; protected onDependenciesChanged(key: string): void; /** * Clean up all event handles */ dispose(): void; /** * Does this scope know about the given namespace name? * @param namespaceName - the name of the namespace (i.e. "NameA", or "NameA.NameB", etc...) */ isKnownNamespace(namespaceName: string): boolean; /** * Get the parent scope for this scope (for source scope this will always be the globalScope). * XmlScope overrides this to return the parent xml scope if available. * For globalScope this will return null. */ getParentScope(): Scope; /** * Get the file with the specified pkgPath */ getFile(pathAbsolute: string): BscFile; getFiles(): BscFile[]; get fileCount(): number; /** * Get the list of errors for this scope. It's calculated on the fly, so * call this sparingly. */ getDiagnostics(): BsDiagnostic[]; addDiagnostics(diagnostics: BsDiagnostic[]): void; /** * Get the list of callables available in this scope (either declared in this scope or in a parent scope) */ getAllCallables(): CallableContainer[]; /** * Get the callable with the specified name. * If there are overridden callables with the same name, the closest callable to this scope is returned * @param name */ getCallableByName(name: string): import("./interfaces").Callable; enumerateFiles(callback: (file: BscFile) => void): void; /** * Get the list of callables explicitly defined in files in this scope. * This excludes ancestor callables */ getOwnCallables(): CallableContainer[]; /** * Builds a tree of namespace objects */ buildNamespaceLookup(): Record<string, NamespaceContainer>; getNamespaceStatements(): NamespaceStatement[]; protected logDebug(...args: any[]): void; private _debugLogComponentName; validate(force?: boolean): void; /** * Mark this scope as invalid, which means its `validate()` function needs to be called again before use. */ invalidate(): void; private detectVariableNamespaceCollisions; /** * Find various function collisions */ private diagnosticDetectFunctionCollisions; getNewExpressions(): AugmentedNewExpression[]; private validateClasses; /** * Detect calls to functions with the incorrect number of parameters * @param file * @param callableContainersByLowerName */ private diagnosticDetectFunctionCallsWithWrongParamCount; /** * Detect local variables (function scope) that have the same name as scope calls * @param file * @param callableContainerMap */ private diagnosticDetectShadowedLocalVars; /** * Detect calls to functions that are not defined in this scope * @param file * @param callablesByLowerName */ private diagnosticDetectCallsToUnknownFunctions; /** * Create diagnostics for any duplicate function declarations * @param callablesByLowerName */ private diagnosticFindDuplicateFunctionDeclarations; /** * Get the list of all script imports for this scope */ private getScriptImports; /** * Verify that all of the scripts imported by each file in this scope actually exist */ private diagnosticValidateScriptImportPaths; /** * Find the file with the specified relative path * @param relativePath */ protected getFileByRelativePath(relativePath: string): BscFile; /** * Determine if this scope is referenced and known by the file. * @param file */ hasFile(file: BscFile): boolean; /** * Get all callables as completionItems */ getCallablesAsCompletions(parseMode: ParseMode): CompletionItem[]; /** * Get the definition (where was this thing first defined) of the symbol under the position */ getDefinition(file: BscFile, position: Position): Location[]; /** * Scan all files for property names, and return them as completions */ getPropertyNameCompletions(): CompletionItem[]; } interface NamespaceContainer { file: BscFile; fullName: string; nameRange: Range; lastPartName: string; statements: Statement[]; classStatements: Record<string, ClassStatement>; functionStatements: Record<string, FunctionStatement>; namespaces: Record<string, NamespaceContainer>; } interface AugmentedNewExpression extends NewExpression { file: BscFile; } export {};
36.902299
129
0.683538
b33ee475b56ebbde098d5bba263d8b5d4412f847
539
py
Python
website/forms.py
yx1302317313/HexoWeb
7d37c58a1108f34795c5cbe161d3c0405ddb6795
[ "MIT" ]
null
null
null
website/forms.py
yx1302317313/HexoWeb
7d37c58a1108f34795c5cbe161d3c0405ddb6795
[ "MIT" ]
4
2021-03-19T11:30:54.000Z
2021-06-09T19:11:10.000Z
website/forms.py
yx1302317313/HexoWeb
7d37c58a1108f34795c5cbe161d3c0405ddb6795
[ "MIT" ]
null
null
null
from django.forms import ModelForm from .models import Website class WebsiteForm(ModelForm): class Meta: model = Website fields = ['title', 'subtitle', 'author', 'per_page', 'url', 'desc', 'keyword', 'repository', 'branch', 'git_username', 'git_email', 'git_password'] def save(self, commit=True): website = super().save(commit) return website def is_valid(self): is_valid = super().is_valid() if not is_valid: return False return True
25.666667
86
0.595547
3855971b74e52a068463f49f73e830a8a0d42d6c
433
dart
Dart
flutterdemo/demo12/lib/tool_tips_demo.dart
qilong-io/flutter_shop
915d62d28e4f1cde16b74f86e29fb2a9474d5c64
[ "Apache-2.0" ]
null
null
null
flutterdemo/demo12/lib/tool_tips_demo.dart
qilong-io/flutter_shop
915d62d28e4f1cde16b74f86e29fb2a9474d5c64
[ "Apache-2.0" ]
null
null
null
flutterdemo/demo12/lib/tool_tips_demo.dart
qilong-io/flutter_shop
915d62d28e4f1cde16b74f86e29fb2a9474d5c64
[ "Apache-2.0" ]
null
null
null
import 'package:flutter/material.dart'; class ToolTipsDemo extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('tool tips demo')), body: Center( child: Tooltip( message: '不要碰我,我怕痒!', child: Image.network( 'http://pic1.win4000.com/wallpaper/2018-02-01/5a72d6ee6b46f.jpg'), ), ), ); } }
24.055556
80
0.600462
6ec680516eec29386c82aa4e625f7c06fbd0c5cd
1,923
dart
Dart
staggered_animations/lib/src/presentation/features/grid/card_grid_screen.dart
fredgrott/material_you_playground
e79e41d9cd475a040aa24ff7611f2c4ce70eba89
[ "BSD-3-Clause" ]
1
2022-02-05T02:55:43.000Z
2022-02-05T02:55:43.000Z
staggered_animations/lib/src/presentation/features/grid/card_grid_screen.dart
fredgrott/material_you_playground
e79e41d9cd475a040aa24ff7611f2c4ce70eba89
[ "BSD-3-Clause" ]
null
null
null
staggered_animations/lib/src/presentation/features/grid/card_grid_screen.dart
fredgrott/material_you_playground
e79e41d9cd475a040aa24ff7611f2c4ce70eba89
[ "BSD-3-Clause" ]
1
2022-02-04T10:53:39.000Z
2022-02-04T10:53:39.000Z
// Copyright 2021 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; import 'package:staggered_animations/src/presentation/widgets/auto_refresh.dart'; import 'package:staggered_animations/src/presentation/widgets/empty_card.dart'; class CardGridScreen extends StatefulWidget { const CardGridScreen({Key? key}) : super(key: key); @override _CardGridScreenState createState() => _CardGridScreenState(); } class _CardGridScreenState extends State<CardGridScreen> { @override Widget build(BuildContext context) { const columnCount = 3; return AutoRefresh( duration: const Duration(milliseconds: 2000), child: Scaffold( appBar: AppBar( title: PlatformText('Staggered Animations'), centerTitle: true, ), body: SafeArea( child: AnimationLimiter( child: GridView.count( childAspectRatio: 1.0, padding: const EdgeInsets.all(8.0), crossAxisCount: columnCount, children: List.generate( 100, (int index) { return AnimationConfiguration.staggeredGrid( columnCount: columnCount, position: index, duration: const Duration(milliseconds: 375), child: const ScaleAnimation( scale: 0.5, child: FadeInAnimation( child: EmptyCard(), ), ), ); }, ), ), ), ), ), ); } }
32.59322
81
0.590224
a33ba9d6b43946587c491edd6b2f89c18b26a244
4,404
h
C
MeshModelingToolCP_Solution/Codes/SparseMatrixStorage.h
PacosLelouch/MeshModelingToolCP
22965f7d0bc2dd14cfa372c023b041a0bbf152ed
[ "BSD-2-Clause" ]
null
null
null
MeshModelingToolCP_Solution/Codes/SparseMatrixStorage.h
PacosLelouch/MeshModelingToolCP
22965f7d0bc2dd14cfa372c023b041a0bbf152ed
[ "BSD-2-Clause" ]
null
null
null
MeshModelingToolCP_Solution/Codes/SparseMatrixStorage.h
PacosLelouch/MeshModelingToolCP
22965f7d0bc2dd14cfa372c023b041a0bbf152ed
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include "TypesCommonMinimal.h" #include <cassert> BEGIN_NAMESPACE(AAShapeUp) struct RowSparseStorageData { void clear() { m_elements.clear(); m_rowAddrs.clear(); m_nRows = 0; } std::vector<std::pair<i32, scalar> > m_elements; std::vector<i32> m_rowAddrs; i32 m_nRows = 0; }; // Contiguous row-wise storage of the element in a sparse matrix class RowSparseStorage { public: void clear() { m_data.clear(); } bool initFromTransposedMatrix(const ColMSMatrix& matTransposed) { m_data.m_elements.clear(); m_data.m_rowAddrs.clear(); m_data.m_nRows = i32(matTransposed.cols()); for (i64 k = 0; k < matTransposed.outerSize(); ++k) { m_data.m_rowAddrs.push_back(i32(m_data.m_elements.size())); for (ColMSMatrix::InnerIterator it(matTransposed, k); it; ++it) { m_data.m_elements.push_back(std::make_pair(i32(it.row()), scalar(it.value()))); } } m_data.m_rowAddrs.push_back(i32(m_data.m_elements.size())); return true; } template<typename TMatrix, typename TVector> void evaluate(i32 rowIdx, const TMatrix& mat, TVector& resVec) const { i32 addrBegin = m_data.m_rowAddrs[rowIdx], addrEnd = m_data.m_rowAddrs[rowIdx + 1]; for (i32 i = addrBegin; i < addrEnd; ++i) { const std::pair<i32, scalar>& curEntry = m_data.m_elements[i]; resVec += mat.col(curEntry.first) * curEntry.second; } } i32 getNRows() const { return m_data.m_nRows; } protected: RowSparseStorageData m_data; }; // Row-wise storage of the diagonally dominant matrix for Jacobi iteration class JacobiRowSparseStorage { public: void clear() { m_data.clear(); } bool initFromTransposedMatrix(const ColMSMatrix& matTransposed) { m_data.m_elements.clear(); m_data.m_rowAddrs.clear(); m_data.m_nRows = i32(matTransposed.cols()); for (i64 k = 0; k < matTransposed.outerSize(); ++k) { m_data.m_rowAddrs.push_back(i32(m_data.m_elements.size())); scalar diagValue = scalar(1); scalar offDiagValues = scalar(0); bool hasDiag = false; for (ColMSMatrix::InnerIterator it(matTransposed, k); it; ++it) { if (it.row() == it.col()) { diagValue = it.value(); hasDiag = true; } else { m_data.m_elements.push_back(std::make_pair(i32(it.row()), scalar(it.value()))); offDiagValues += glm::abs(it.value()); } } if (!hasDiag) { // Error diagonal elements for Jacobi system matrix. return false; } m_data.m_elements.push_back(std::make_pair(-1, scalar(diagValue))); } m_data.m_rowAddrs.push_back(i32(m_data.m_elements.size())); return true; } template<typename TMatrix, typename TVector> void evaluate(i32 rowIdx, const TMatrix& mat, TVector& resVec) const { i32 addrBegin = m_data.m_rowAddrs[rowIdx], addrEnd = m_data.m_rowAddrs[rowIdx + 1] - 1; for (i32 i = addrBegin; i < addrEnd; ++i) { const std::pair<i32, scalar>& curEntry = m_data.m_elements[i]; resVec -= mat.col(curEntry.first) * curEntry.second; } resVec /= m_data.m_elements[addrEnd].second; } i32 getNRows() const { return m_data.m_nRows; } scalar getDiagonal(i32 rowIdx) const { return m_data.m_elements[m_data.m_rowAddrs[rowIdx + 1] - 1].second; } void setDiagonal(i32 rowIdx, scalar value) { m_data.m_elements[m_data.m_rowAddrs[rowIdx + 1] - 1].second = value; } void getDiagonals(VectorX& diag) const { diag.resize(m_data.m_nRows); for (i32 i = 0; i < m_data.m_nRows; ++i) { diag(i) = getDiagonal(i); } } void setDiagonals(const VectorX& diag) { assert(static_cast<i32>(diag.size()) == m_data.m_nRows); for (i32 i = 0; i < m_data.m_nRows; ++i) { setDiagonal(i, diag(i)); } } protected: RowSparseStorageData m_data; }; END_NAMESPACE()
27.525
119
0.572888
2a0c95463c2dddf5128595d7fedff047ae74c2f8
1,838
dart
Dart
lib/src/models/MyCustomerDeliveryFeeModel.dart
anilmanchanda24M/foodboss_seller_app
748472dffd07905e540b447d557b72dac26ac0e9
[ "MIT" ]
null
null
null
lib/src/models/MyCustomerDeliveryFeeModel.dart
anilmanchanda24M/foodboss_seller_app
748472dffd07905e540b447d557b72dac26ac0e9
[ "MIT" ]
null
null
null
lib/src/models/MyCustomerDeliveryFeeModel.dart
anilmanchanda24M/foodboss_seller_app
748472dffd07905e540b447d557b72dac26ac0e9
[ "MIT" ]
null
null
null
// To parse this JSON data, do // // final myCustomerDeliveryFeeModel = myCustomerDeliveryFeeModelFromJson(jsonString); import 'dart:convert'; MyCustomerDeliveryFeeModel myCustomerDeliveryFeeModelFromJson(String str) => MyCustomerDeliveryFeeModel.fromJson(json.decode(str)); String myCustomerDeliveryFeeModelToJson(MyCustomerDeliveryFeeModel data) => json.encode(data.toJson()); class MyCustomerDeliveryFeeModel { MyCustomerDeliveryFeeModel({ this.success, this.data, this.message, }); bool success; Data data; String message; factory MyCustomerDeliveryFeeModel.fromJson(Map<String, dynamic> json) => MyCustomerDeliveryFeeModel( success: json["success"], data: Data.fromJson(json["data"]), message: json["message"], ); Map<String, dynamic> toJson() => { "success": success, "data": data.toJson(), "message": message, }; } class Data { Data({ this.id, this.userId, this.restaurantId, this.deliveryChargeAmount, this.createdAt, this.updatedAt, }); int id; int userId; int restaurantId; int deliveryChargeAmount; DateTime createdAt; DateTime updatedAt; factory Data.fromJson(Map<String, dynamic> json) => Data( id: json["id"], userId: json["user_id"], restaurantId: json["restaurant_id"], deliveryChargeAmount: json["delivery_charge_amount"], createdAt: DateTime.parse(json["created_at"]), updatedAt: DateTime.parse(json["updated_at"]), ); Map<String, dynamic> toJson() => { "id": id, "user_id": userId, "restaurant_id": restaurantId, "delivery_charge_amount": deliveryChargeAmount, "created_at": createdAt.toIso8601String(), "updated_at": updatedAt.toIso8601String(), }; }
25.178082
89
0.662133
a456a89259497f1279095aa3db570f94fecf870e
341
h
C
head/contrib/ntp/include/ntp_sprintf.h
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
4
2017-04-06T21:39:15.000Z
2019-10-09T17:34:14.000Z
head/contrib/ntp/include/ntp_sprintf.h
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
null
null
null
head/contrib/ntp/include/ntp_sprintf.h
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
1
2020-01-04T06:36:39.000Z
2020-01-04T06:36:39.000Z
/* * Handle ancient char* *s*printf*() systems */ #ifdef SPRINTF_CHAR # define SPRINTF(x) strlen(sprintf/**/x) # define SNPRINTF(x) strlen(snprintf/**/x) # define VSNPRINTF(x) strlen(vsnprintf/**/x) #else # define SPRINTF(x) ((size_t)sprintf x) # define SNPRINTF(x) ((size_t)snprintf x) # define VSNPRINTF(x) ((size_t)vsnprintf x) #endif
24.357143
44
0.695015
ed2259ed60c8c8e7b11781f06e19f16a54bf7307
4,088
h
C
src/submodules/operators/int2x2.operators.h
maihd/hlslmath
63dfc2b2de8d2e47e87282d7006b44a6b37401be
[ "Unlicense" ]
3
2019-09-26T16:52:00.000Z
2020-09-06T09:14:36.000Z
src/submodules/operators/int2x2.operators.h
maihd/hlslmath
63dfc2b2de8d2e47e87282d7006b44a6b37401be
[ "Unlicense" ]
null
null
null
src/submodules/operators/int2x2.operators.h
maihd/hlslmath
63dfc2b2de8d2e47e87282d7006b44a6b37401be
[ "Unlicense" ]
null
null
null
inline int2x2 operator-(const int2x2& m) { return int2x2( -m[0][0], -m[0][1], -m[1][0], -m[1][1]); } inline int2x2& operator++(int2x2& m) { ++m[0][0]; ++m[0][1]; ++m[1][0]; ++m[1][1]; return m; } inline int2x2& operator--(int2x2& m) { --m[0][0]; --m[0][1]; --m[1][0]; --m[1][1]; return m; } inline int2x2 operator++(int2x2& m, int) { const int2x2 result = m; ++m; return result; } inline int2x2 operator--(int2x2& m, int) { const int2x2 result = m; --m; return result; } inline int2x2 operator+(const int2x2& a, const int2x2& b) { return int2x2( a[0][0] + b[0][0], a[0][1] + b[0][1], a[1][0] + b[1][0], a[1][1] + b[1][1]); } inline int2x2 operator-(const int2x2& a, const int2x2& b) { return int2x2( a[0][0] - b[0][0], a[0][1] - b[0][1], a[1][0] - b[1][0], a[1][1] - b[1][1]); } inline int2x2 operator*(const int2x2& a, const int2x2& b) { return int2x2( a[0][0] * b[0][0], a[0][1] * b[0][1], a[1][0] * b[1][0], a[1][1] * b[1][1]); } inline int2x2 operator/(const int2x2& a, const int2x2& b) { return int2x2( a[0][0] / b[0][0], a[0][1] / b[0][1], a[1][0] / b[1][0], a[1][1] / b[1][1]); } inline int2x2 operator+(const int2x2& a, int b) { return int2x2( a[0][0] + b, a[0][1] + b, a[1][0] + b, a[1][1] + b); } inline int2x2 operator-(const int2x2& a, int b) { return int2x2( a[0][0] - b, a[0][1] - b, a[1][0] - b, a[1][1] - b); } inline int2x2 operator*(const int2x2& a, int b) { return int2x2( a[0][0] * b, a[0][1] * b, a[1][0] * b, a[1][1] * b); } inline int2x2 operator/(const int2x2& a, int b) { return int2x2( a[0][0] / b, a[0][1] / b, a[1][0] / b, a[1][1] / b); } inline int2x2 operator+(int a, const int2x2& b) { return int2x2( a + b[0][0], a + b[0][1], a + b[1][0], a + b[1][1]); } inline int2x2 operator-(int a, const int2x2& b) { return int2x2( a - b[0][0], a - b[0][1], a - b[1][0], a - b[1][1]); } inline int2x2 operator*(int a, const int2x2& b) { return int2x2( a * b[0][0], a * b[0][1], a * b[1][0], a * b[1][1]); } inline int2x2 operator/(int a, const int2x2& b) { return int2x2( a / b[0][0], a / b[0][1], a / b[1][0], a / b[1][1]); } inline int2x2& operator+=(int2x2& a, int b) { return (a = a + b); } inline int2x2& operator-=(int2x2& a, int b) { return (a = a - b); } inline int2x2& operator*=(int2x2& a, int b) { return (a = a * b); } inline int2x2& operator/=(int2x2& a, int b) { return (a = a / b); } inline int2x2& operator+=(int2x2& a, const int2x2& b) { return (a = a + b); } inline int2x2& operator-=(int2x2& a, const int2x2& b) { return (a = a - b); } inline int2x2& operator*=(int2x2& a, const int2x2& b) { return (a = a * b); } inline int2x2& operator/=(int2x2& a, const int2x2& b) { return (a = a / b); } inline bool2x2 operator<(const int2x2& a, const int2x2& b) { return bool2x2( a[0][0] < b[0][0], a[0][1] < b[0][1], a[1][0] < b[1][0], a[1][1] < b[1][1]); } inline bool2x2 operator>(const int2x2& a, const int2x2& b) { return bool2x2( a[0][0] > b[0][0], a[0][1] > b[0][1], a[1][0] > b[1][0], a[1][1] > b[1][1]); } inline bool2x2 operator<=(const int2x2& a, const int2x2& b) { return bool2x2( a[0][0] <= b[0][0], a[0][1] <= b[0][1], a[1][0] <= b[1][0], a[1][1] <= b[1][1]); } inline bool2x2 operator>=(const int2x2& a, const int2x2& b) { return bool2x2( a[0][0] >= b[0][0], a[0][1] >= b[0][1], a[1][0] >= b[1][0], a[1][1] >= b[1][1]); } inline bool2x2 operator==(const int2x2& a, const int2x2& b) { return bool2x2( a[0][0] == b[0][0], a[0][1] == b[0][1], a[1][0] == b[1][0], a[1][1] == b[1][1]); } inline bool2x2 operator!=(const int2x2& a, const int2x2& b) { return bool2x2( a[0][0] != b[0][0], a[0][1] != b[0][1], a[1][0] != b[1][0], a[1][1] != b[1][1]); }
20.44
59
0.476027
14481e289291ea2b75dc3c2c7b60a5a6a08768b6
678
ts
TypeScript
jest.ts
pgdesjardins/react-horizontal-scrolling-menu
48ef6733b0f7c790d67bbd31edab62e7f1558edf
[ "MIT" ]
2
2021-06-01T21:59:57.000Z
2021-11-18T18:12:52.000Z
jest.ts
btargac/react-horizontal-scrolling-menu
c62fe0ea47781060cf6ec8c9bb9b43cd8ad25193
[ "MIT" ]
null
null
null
jest.ts
btargac/react-horizontal-scrolling-menu
c62fe0ea47781060cf6ec8c9bb9b43cd8ad25193
[ "MIT" ]
null
null
null
import Enzyme from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; const jsdom = require('jsdom'); const { JSDOM } = jsdom; Enzyme.configure({adapter: new Adapter()}); /* declare global { namespace NodeJS { interface Global { [key: string]: any } } }; */ /* const documentHTML = '<!doctype html><html><body><div id="root"></div></body></html>'; global.document = new JSDOM(documentHTML); global.window.resizeTo = (width: number, height: number): void => { global.window.innerWidth = width || global.window.innerWidth; global.window.innerHeight = height || global.window.innerHeight; global.window.dispatchEvent(new Event('resize')); }; */
23.37931
89
0.678466
4372fe8c73db2fe2d627f92317d40692972acf72
2,451
ts
TypeScript
src/app/app.module.ts
sonntag-philipp/Pen-and-Paper-Web
6e7861f6dea2a45fd8c1c0e53c65cef14bf1285b
[ "MIT" ]
null
null
null
src/app/app.module.ts
sonntag-philipp/Pen-and-Paper-Web
6e7861f6dea2a45fd8c1c0e53c65cef14bf1285b
[ "MIT" ]
null
null
null
src/app/app.module.ts
sonntag-philipp/Pen-and-Paper-Web
6e7861f6dea2a45fd8c1c0e53c65cef14bf1285b
[ "MIT" ]
null
null
null
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import {AppComponent} from './app.component'; import {BrowserAnimationsModule} from "@angular/platform-browser/animations"; import {MatButtonModule, MatCardModule, MatInputModule, MatToolbarModule} from "@angular/material"; import {FlexLayoutModule} from "@angular/flex-layout"; import {IndexComponent} from './index/index.component'; import {AppRoutingModule} from "./app-routing.module"; import {ToolbarComponent} from './toolbar/toolbar.component'; import {ToolbarService} from "./toolbar/toolbar.service"; import {DialogsModule} from "./dialogs/dialogs.module"; import {MessageDialogComponent} from "./dialogs/message-dialog/message-dialog.component"; import {ConfirmationDialogComponent} from "./dialogs/confirmation-dialog/confirmation-dialog.component"; import {AngularFirestoreModule} from "angularfire2/firestore"; import {AngularFireAuthModule} from "angularfire2/auth"; import {AppFirebaseModule} from "./app-firebase.module"; import {CharsComponent} from "./chars/chars.component"; import {CharComponent} from "./chars/char/char.component"; import {CharEditComponent} from "./chars/char-edit/char-edit.component"; import {ErrorPageComponent} from "./shared/components/error-page/error-page.component"; import {InputDialogComponent} from "./dialogs/input-dialog/input-dialog.component"; import {StoriesComponent} from "./stories/stories.component"; import {StoryComponent} from "./stories/story/story.component"; import {StoryEditComponent} from "./stories/story-edit/story-edit.component"; @NgModule({ declarations: [ AppComponent, IndexComponent, ToolbarComponent, ErrorPageComponent, CharsComponent, CharComponent, CharEditComponent, StoriesComponent, StoryComponent, StoryEditComponent ], imports: [ // Other Modules BrowserModule, BrowserAnimationsModule, FlexLayoutModule, // Local Modules AppFirebaseModule, AppRoutingModule, DialogsModule, // Firebase Imports AngularFireAuthModule, AngularFirestoreModule, // Material Design imports MatToolbarModule, MatButtonModule, MatCardModule, MatInputModule ], providers: [ ToolbarService ], entryComponents: [ MessageDialogComponent, ConfirmationDialogComponent, InputDialogComponent ], bootstrap: [AppComponent] }) export class AppModule { }
32.68
104
0.758466
c1479d246877d5f0c53998ca8f82da33ad7d6440
22,946
lua
Lua
bdasm.lua
SolraBizna/bdasm
c8707023a40bd0486b32958503fba775fedb8001
[ "Zlib" ]
null
null
null
bdasm.lua
SolraBizna/bdasm
c8707023a40bd0486b32958503fba775fedb8001
[ "Zlib" ]
null
null
null
bdasm.lua
SolraBizna/bdasm
c8707023a40bd0486b32958503fba775fedb8001
[ "Zlib" ]
null
null
null
#!/usr/bin/env lua5.3 -- This file is concatentated from several smaller files, to allow the -- program's logic to be spread out without complicating its invocation -- and/or distribution processes. load("if not pcall(require, \"lpeg\") then\ io.write[[\ You must install the LPEG package to use this assembler.\ \ With LuaRocks installed:\ \ luarocks install lpeg\ ]]\ os.exit(1)\ end\ \ local declared = {}\ function globals(...)\ for _,v in ipairs{...} do\ declared[v] = true\ end\ end\ local _mt = {}\ function _mt:__newindex(k,v)\ if not declared[k] then\ error(\"Undeclared global: \"..tostring(k), 2)\ else\ rawset(self,k,v)\ end\ end\ _mt.__index = _mt.__newindex\ setmetatable(_G, _mt)\ \ if #arg ~= 2 and #arg ~= 3 then\ io.write[[\ Usage: bdasm input.s output.txt [listfile.txt]\ ]]\ os.exit(1)\ end\ \ globals(\"input_filename\", \"output_filename\", \"listing_filename\")\ \ input_filename = arg[1]\ output_filename = arg[2]\ listing_filename = arg[3]\ ","@src/top.lua")() load("globals(\"grammar\")\ \ local lpeg = require \"lpeg\"\ \ local P = lpeg.P\ local V = lpeg.V\ local C = lpeg.C\ local R = lpeg.R\ local S = lpeg.S\ local Ct = lpeg.Ct\ local Cc = lpeg.Cc\ \ local ESCAPES = {\ [\"\\\\\"] = \"\\\\\",\ a=\"\\x07\",\ n=\"\\n\",\ t=\"\\t\",\ r=\"\\r\",\ }\ \ grammar = P{\ \"loc\";\ loc = V\"label\" * (V\"instruction\" + V\"eol\");\ label = (-1 * Cc\"\") + (C(V\"identifier\") * (P\":\")^-1 + Cc\"\") * (V\"whitespace\"^1+V\"eol\");\ eol = V\"whitespace\"^0 * (P\";\" + -1);\ identifier = (R(\"az\",\"AZ\")+S\"_\") * (R(\"az\",\"AZ\",\"09\")+S\"_\")^0 + P\"-\"^1 + P\"+\"^1;\ instruction = (Cc\"instruction\"*(C(V\"identifier\")/string.upper)*((P\".\"*C(V\"identifier\")/string.upper)+C\"\")*(P\"?\"*Cc(true)+Cc(false))+(Cc\"directive\"*P\".\"*(C(V\"identifier\")/string.upper)*Cc\"\"*Cc(false))) * Ct(V\"whitespace\"^1 * V\"nonterminal_parameter\"^0 * V\"parameter\" + V\"eol\");\ nonterminal_parameter = V\"parameter\" * V\"whitespace\"^0 * P\",\" * V\"whitespace\"^0;\ parameter = V\"param_string\" + V\"param_id\" + V\"param_literal\";\ param_string = V\"squot_string\" + V\"dquot_string\";\ squot_string = Ct(Cc\"string\"*P\"'\"*C((P(1)-P\"'\")^0)*\"'\");\ dquot_string = Ct(Cc\"string\"*P'\"'*(Ct((V\"dquot_string_char\"-P'\"')^0)/table.concat)*P'\"');\ dquot_string_char = V\"dquot_escaped_char\" + C(1);\ dquot_escaped_char = P\"\\\\\" * (C(S\"\\\\antr\") / ESCAPES);\ param_id = Ct(Cc\"identifier\"*C(V\"identifier\"));\ param_literal = Ct(Cc\"integer\"*(V\"num_hex\" + V\"num_bin\" + V\"num_dec\"));\ num_hex = P\"0x\" * C(R(\"09\",\"AF\",\"af\")^1)/function(x) return tonumber(x,16) end;\ num_bin = P\"%\" * C(S\"01\"^1)/function(x) return tonumber(x,2) end;\ num_dec = C(P\"-\"^-1*R(\"09\")^1)/function(x) return tonumber(x,10) end;\ whitespace = S\" \\r\\t\";\ }\ ","@src/grammar.lua")() load("globals(\"source_registers\", \"dest_registers\", \"all_registers\", \"register_names\", \"conditions\", \"reverse_condition_map\")\ \ local common_registers = {\ A=1,\ B=2,\ PC=3,\ MA=4,\ MD=5,\ S=6,\ X=7\ }\ \ source_registers = {\ ADD=0<<3,\ SUB=1<<3,\ LSL=2<<3,\ LSR=3<<3,\ ROL=4<<3,\ ROR=5<<3,\ AB=6<<3,\ AINC=7<<3,\ BINC=8<<3,\ ADEC=9<<3,\ BDEC=10<<3,\ ASEX=11<<3,\ NOT=12<<3,\ AND=13<<3,\ OR=14<<3,\ XOR=15<<3,\ }\ \ dest_registers = {\ Q=0,\ }\ \ for k,v in pairs(common_registers) do\ source_registers[k] = v\ dest_registers[k] = v\ end\ \ all_registers = {}\ register_names = {}\ \ for k,v in pairs(source_registers) do\ register_names[v] = k\ all_registers[k] = v\ end\ \ for k,v in pairs(dest_registers) do\ register_names[v] = k\ all_registers[k] = v\ end\ \ conditions = {\ AL=0,\ NEVER=1,\ NAL=1,\ MI=2,\ NMI=3,\ PL=4,\ NPL=5,\ Z=6,\ NZ=7\ }\ \ reverse_condition_map = {\ [0] = \"\",\ [1] = \".NEVER\",\ [2] = \".MI\",\ [3] = \".NMI\",\ [4] = \".PL\",\ [5] = \".NPL\",\ [6] = \".Z\",\ [7] = \".NZ\",\ }\ ","@src/registers.lua")() load("globals(\"instructions\")\ \ instructions = {\ WIDEMOVE={\"lvalue\", \"bigvalue\", source=[[\ MOVE A, bhi\ MOVE B, blo\ MOVE a, AB\ ]]},\ PUSH={\"value\", source=[[\ MOVE B, S\ MOVE S, BDEC\ MOVE MA, S\ MOVE MD, a\ ]]},\ WIDEPUSH={\"bigvalue\", source=[[\ MOVE B, S\ MOVE S, BDEC\ MOVE MA, S\ WIDEMOVE MD, a\ ]]},\ POP={\"lvalue\", source=[[\ MOVE MA, S\ MOVE B, S\ MOVE S, BINC\ MOVE a, MD\ ]]},\ RET={source=[[\ POP PC\ ]]},\ JL={\"bigvalue\", source=[[\ WIDEPUSH _A\ WIDEMOVE PC, a\ _A:\ ]]},\ J={\"bigvalue\", source=[[\ WIDEMOVE PC, a\ _A:\ ]]},\ LOAD={\"lvalue\", \"value\", source=[[\ MOVE MA, b\ MOVE a, MD\ ]]},\ FARLOAD={\"lvalue\", \"bigvalue\", source=[[\ WIDEMOVE MA, b\ MOVE a, MD\ ]]},\ STORE={\"value\", \"value\", source=[[\ MOVE MA, a\ MOVE MD, b\ ]]},\ FARSTORE={\"bigvalue\", \"value\", source=[[\ WIDEMOVE MA, a\ MOVE MD, b\ ]]},\ WIDESTORE={\"value\", \"bigvalue\", source=[[\ MOVE MA, a\ WIDEMOVE MD, b\ ]]},\ FARWIDESTORE={\"bigvalue\", \"bigvalue\", source=[[\ WIDEMOVE MA, a\ WIDEMOVE MD, b\ ]]},\ MOVE={\"lvalue\", \"value\", compiled={\ {type=\"instruction\",dest=\"a\", source=\"b\"},\ }},\ }\ \ for k,v in pairs(instructions) do v.name = k end\ \ local function remap(x, params)\ if x == \"a\" then return assert(params[1][2])\ elseif x == \"b\" then return assert(params[2][2])\ elseif x == \"alo\" then return assert(params[1][2]..\"lo\")\ elseif x == \"blo\" then return assert(params[2][2]..\"lo\")\ elseif x == \"ahi\" then return assert(params[1][2]..\"hi\")\ elseif x == \"bhi\" then return assert(params[2][2]..\"hi\")\ else return x end\ end\ \ local function maybe_map_label(x, labels)\ if x:sub(1,1) ~= \"_\" then return x end\ local prefix\ if x:sub(-2,-1) == \"lo\" then prefix,x = \"<\",x:sub(1,-3)\ elseif x:sub(-2,-1) == \"hi\" then prefix,x = \">\",x:sub(1,-3)\ else prefix = \"\" end\ assert(labels[x], \"unknown label in instruction source\")\ return prefix..labels[x]\ end\ \ local lpeg = require \"lpeg\"\ local function compile_instruction(insn)\ if insn.compiled then return end\ if insn.compiling then\ error(\"recursive instruction dependency\")\ end\ insn.compiling = true\ assert(insn.source, \"attempting to compile an instruction with no source\")\ local compiled = {}\ local labels = {}\ for l in insn.source:gmatch(\"[^\\n]+\") do\ local label, ltyp, name, condition, update, params = lpeg.match(grammar, l)\ if not label then\ error(\"unparseable source line compiling instruction \"..insn.name)\ elseif label ~= \"\" then\ assert(label:sub(1,1) == \"_\", \"instruction source labels must begin with _\")\ labels[label] = \"+\"..#compiled\ end\ if ltyp ~= nil then\ if ltyp == \"directive\" then\ error(\"directive in source for instruction \"..insn.name)\ elseif condition ~= \"\" or update ~= false then\ error(\"explicit condition flag / update in source for instruction \"..insn.name)\ elseif not instructions[name] then\ error(\"referenced nonexistent instruction \"..name..\" in source for instruction \"..insn.name)\ end\ compile_instruction(instructions[name])\ local subcode = instructions[name].compiled\ for n=1,#subcode do\ local subel = subcode[n]\ assert(subel.type == \"instruction\")\ local neo = {type=\"instruction\"}\ neo.source = remap(subel.source, params)\ neo.dest = remap(subel.dest, params)\ compiled[#compiled+1] = neo\ end\ end\ end\ for n=1,#compiled do\ local el = compiled[n]\ el.source = maybe_map_label(el.source, labels)\ el.dest = maybe_map_label(el.dest, labels)\ end\ insn.compiling = nil\ insn.compiled = compiled\ end\ \ for k,v in pairs(instructions) do compile_instruction(v) end\ \ -- uncomment to debug instruction compilation\ --[=[\ globals(\"unpack\")\ unpack=table.unpack\ local t = {}\ for k,v in pairs(instructions) do t[#t+1] = k end\ table.sort(t)\ for n=1,#t do\ local insn = instructions[t[n]]\ print(insn.name..\":\")\ for n=1,#insn.compiled do\ print(require \"erebor\".build(insn.compiled[n]))\ end\ end\ os.exit(1)\ --[=[]=]\ ","@src/instructions.lua")() load("globals(\"memory\", \"mem_base\", \"mem_size\")\ \ local input,e = io.open(input_filename, \"rb\")\ if not input then\ print(e)\ os.exit(1)\ end\ \ local listing\ if listing_filename then\ listing,e = io.open(listing_filename, \"wb\")\ if not listing then\ print(e)\ os.exit(1)\ end\ end\ \ local lpeg = require \"lpeg\"\ \ local cur_line\ local lineno = 1\ local printed_line = nil\ local error_count = 0\ local function asm_error(format, ...)\ io.write(\"ERROR: \",input_filename,\":\",lineno,\": \",format:format(...),\"\\n\")\ if printed_line ~= lineno and cur_line then\ io.write(\" \",cur_line,\"\\n\")\ printed_line = lineno\ end\ error_count = error_count + 1\ end\ local had_fatal_error = false -- stop parsing if true\ local function fatal_asm_error(...)\ asm_error(...)\ fatal_error = true\ end\ \ memory = {}\ local definitions = {}\ local had_code = false -- .BASE and .SIZE are invalid when had_code is true\ mem_base = 0x8000\ mem_size = 0x8000\ local instruction_start_org\ local org = 0x8000\ local refs = {}\ \ local function resolve(name)\ local got\ local rtype, offset = name:match(\"^([<>])%+([0-9]+)$\")\ if rtype then\ -- offset relative to start of instruction\ got = instruction_start_org + tonumber(offset, 10)\ if rtype == \"<\" then got = got & 255\ elseif rtype == \">\" then got = (got >> 8) & 255\ end\ elseif name:sub(1,1) == \"<\" then\ -- low part\ got = definitions[name:sub(2,-1)]\ if got then got = got & 255 end\ elseif name:sub(1,1) == \">\" then\ -- high part\ got = definitions[name:sub(2,-1)]\ if got then got = (got >> 8) & 255 end\ elseif name:sub(1,1) == \"!\" then\ -- full word\ got = definitions[name:sub(2,-1)]\ else\ -- word fitting in a uint8\ got = definitions[name]\ if got and (got < 0 or got > 255) then\ got = 0\ asm_error(\"definition of %s does not fit in a uint8\", name)\ end\ end\ return got\ end\ \ local function warn_listing_seek()\ print(\"WARNING: Couldn't seek in the listing file. Some references will be missing.\")\ warn_listing_seek = function() end\ end\ \ local function link(ref, got)\ memory[ref.addr] = memory[ref.addr] | got\ if listing and ref.lspos then\ if not listing:seek(\"set\", ref.lspos) then\ warn_listing_seek()\ else\ listing:write((\"%04X\"):format(memory[ref.addr]))\ assert(listing:seek(\"end\"))\ end\ end\ end\ \ local function ref(addr, name)\ local lspos\ if listing then\ lspos = listing:seek()\ if lspos then lspos = lspos + 10\ else warn_listing_seek() end\ end\ refs[#refs+1] = {addr=addr, name=name, lineno=lineno, lspos=lspos}\ end\ \ local function emit_word(w, ex)\ if org < mem_base or org >= mem_base + mem_size then\ asm_error(\".ORG value has escaped from memory\")\ end\ had_code = true\ if memory[org] then\ asm_error(\"attempted to emit code in an already-occupied section of the image\")\ else\ memory[org] = w\ end\ if listing then\ listing:write((\";;0x%04X: %04X%s\\n\"):format(org, w, ex or \"\"))\ end\ org = org + 1\ end\ \ local function emit_move(source, dest, condition, update)\ local word = dest << 9\ local sourcename\ if type(source) == \"number\" then\ word = word | source\ if source >= 256 then sourcename = source&255\ else sourcename = register_names[source] end\ else\ sourcename = source\ local got = resolve(source)\ if not got then\ ref(org, source)\ word = word | 256\ else\ source = got\ word = word | got | 256\ end\ end\ if update then word = word | 0x1000 end\ word = word | (condition << 13)\ local ex = (\" = MOVE%s%s %s, %s\"):format(reverse_condition_map[condition], update and \"?\" or \"\", register_names[dest], sourcename)\ emit_word(word, ex)\ end\ \ local function ck16(x)\ if type(x) ~= \"number\" or x < -32768 or x > 65535 then\ asm_error(\"expected an integer between -32768 and 65535\")\ return false\ else\ return true\ end\ end\ \ local function cku16(x)\ if type(x) ~= \"number\" or x < 0 or x > 65535 then\ asm_error(\"expected an integer between 0 and 65535\")\ return false\ else\ return true\ end\ end\ \ local directives = {}\ directives.BASE = {\"integer\",\ func=function(a)\ if had_code then\ return fatal_asm_error(\".BASE is only valid before code\")\ end\ if not cku16(a) then return end\ mem_base = a\ end}\ directives.SIZE = {\"integer\",\ func=function(a)\ if had_code then\ return fatal_asm_error(\".SIZE is only valid before code\")\ end\ if not cku16(a) then return end\ mem_size = a\ end}\ directives.ORG = {\"integer\",\ func=function(a)\ if not cku16(a) then return end\ org = a\ if org < mem_base or org >= mem_base + mem_size then\ asm_error(\".ORG value must be in the range 0x%04X - 0x%04X\",\ mem_base, mem_base + mem_size - 1)\ end\ end}\ directives.DEFINE = {\"identifier\", \"integer\",\ func=function(id,val)\ if all_registers[id] then\ asm_error(\"\\\"%s\\\" is a register name and cannot be used as a symbol\", id)\ elseif definitions[id] then\ asm_error(\"Duplicate definition for \\\"%s\\\"\", id)\ elseif not ck16(val) then\ return\ else\ definitions[id] = val\ end\ end}\ local byte_exes = {[10]=\" = newline\",[13]=\" = carriage return\",[7]=\" = bell\",[9]=\" = tab\"}\ directives.WORDS = {\ func=function(params)\ if #params == 0 then\ asm_error(\".WORDS expects at least one parameter\")\ return\ end\ for n=1,#params do\ local param = params[n]\ local typ,val = param[1], param[2]\ if typ == \"integer\" then\ if ck16(val) then emit_word(val, (\" = %i\"):format(val)) end\ elseif typ == \"identifier\" then\ asm_error(\"Can't emit linked words yet.\")\ elseif typ == \"string\" then\ for n=1,#val do\ local byte = val:byte(n)\ local ex\ if byte_exes[byte] then ex = byte_exes[byte]\ elseif byte >= 32 and byte <= 126 then\ ex = (\" = '%s'\"):format(string.char(byte))\ else\ ex = (\" = %i\"):format(byte)\ end\ emit_word(byte, ex)\ end\ else\ error(\"Internal error: Unknown parameter type: \"..typ)\ end\ end\ end}\ \ local function remap(name, params)\ if params[name] then return params[name] end\ return name\ end\ for l in input:lines() do\ cur_line = l\ if listing then\ listing:write(l, \"\\n\")\ end\ local label, ltype, name, condition, update, params = lpeg.match(grammar, l)\ if not label then\ asm_error(\"Couldn't parse this line.\")\ elseif label ~= \"\" then\ if all_registers[label] then\ asm_error(\"\\\"%s\\\" is a register name and cannot be used as a symbol\", id)\ elseif definitions[label] and label:sub(1,1) ~= \"-\" then\ asm_error(\"Duplicate definition for \\\"%s\\\"\", label)\ elseif label:sub(1,1) == \"+\" then\ -- \"forward jump\" label, fixup backwards\ local lo = \"<\"..label\ local hi = \">\"..label\ for n=#refs,1,-1 do\ if refs[n].name == lo then\ link(refs[n], org & 255)\ table.remove(refs, n)\ elseif refs[n].name == hi then\ link(refs[n], (org >> 8) & 255)\ table.remove(refs, n)\ end\ end\ else\ -- regular label or \"backward jump\" label\ definitions[label] = org\ end\ end\ if ltype == \"directive\" then\ local directive = directives[name]\ if not directive then\ asm_error(\"Unknown directive: \\\".%s\\\"\", name)\ elseif #directive == 0 then\ -- varargs directive, does its own validation\ directive.func(params)\ else\ if #directive ~= #params then\ asm_error(\"\\\".%s\\\" directive expects %i parameter%s\",\ name, #directive, #directive == 1 and \"\" or \"s\")\ else\ local inparams = {}\ for n=1, #params do\ if params[n][1] ~= directive[n] then\ asm_error(\"\\\".%s\\\" directive parameter %i must be %s, not %s\",\ name, n, directive[n], params[n][1])\ inparams = nil\ elseif inparams then\ inparams[n] = params[n][2]\ end\ end\ if inparams ~= nil then\ directive.func(table.unpack(inparams))\ end\ end\ end\ elseif ltype == \"instruction\" then\ instruction_start_org = org\ local instruction = instructions[name]\ if not instruction then\ asm_error(\"Unknown instruction: \\\"%s\\\"\", name)\ elseif #instruction ~= #params then\ asm_error(\"\\\"%s\\\" instruction expects %i parameter%s\",\ name, #instruction, #instruction == 1 and \"\" or \"s\")\ else\ if condition == \"\" then\ condition = 0 -- default is always\ elseif not conditions[condition] then\ asm_error(\"invalid condition\")\ condition = 0\ else\ condition = conditions[condition]\ end\ local ok = true\ local source_params = {}\ for n=1,#instruction do\ if params[n][1] == \"string\" then\ asm_error(\"instruction parameters may not be strings\")\ ok = false\ else\ if params[n][1] == \"integer\" then\ if not ck16(params[n][2]) then ok = false end\ params[n][2] = params[n][2] & 65535\ end\ local name = string.char(96+n)\ if instruction[n] == \"bigvalue\" then\ if params[n][1] == \"integer\" then\ source_params[name..\"lo\"] = params[n][2]&255\ source_params[name..\"hi\"] = (params[n][2]>>8)&255\ else\ source_params[name..\"lo\"] = \"<\"..params[n][2]\ source_params[name..\"hi\"] = \">\"..params[n][2]\ end\ elseif instruction[n] == \"lvalue\" then\ if params[n][1] ~= \"identifier\" then\ asm_error(\"parameter %i of %s must be a register\",\ n, instruction.name)\ ok = false\ else\ -- TODO: check that it is indeed an lvalue\ end\ source_params[name] = params[n][2]\ elseif instruction[n] == \"value\" then\ source_params[name] = params[n][2]\ else\ error(\"internal error: unknown parameter type: \"..instruction[n])\ end\ end\ end\ if ok then\ for n=1,#instruction.compiled do\ local source, dest\ local el = instruction.compiled[n]\ local we_update = update and n == #instruction.compiled\ dest = remap(el.dest, source_params)\ if dest_registers[dest] then\ dest = dest_registers[dest]\ else\ asm_error(\"not a valid destination register: %s\", dest)\ dest = nil\ end\ source = remap(el.source, source_params)\ if type(source) == \"number\" then\ if source > 255 or source < 0 then\ asm_error(\"source is not a valid uint8\")\ end\ source = source & 255 | 256\ elseif source_registers[source] then\ source = source_registers[source]\ end\ if source and dest then\ emit_move(source, dest, condition, we_update)\ else\ break\ end\ end\ end\ end\ elseif ltype == nil then\ -- (no line, or couldn't parse)\ else\ error(\"Internal error: unknown ltype: \"..ltype)\ end\ lineno = lineno + 1\ if error_count > 50 then\ print(\"Too many errors, giving up...\")\ break\ elseif had_fatal_error then\ print(\"That error is fatal...\")\ break\ end\ end\ input:close()\ \ if error_count > 0 then\ if error_count == 1 then\ print(\"Encountered an error in the assembly process. Aborting.\")\ else\ print(\"Encountered \"..error_count..\" errors in the assembly process. Aborting.\")\ end\ os.exit(1)\ end\ \ cur_line = nil\ \ for n=1,#refs do\ local ref = refs[n]\ lineno = ref.lineno\ local got = resolve(ref.name)\ if not got then\ asm_error(\"undefined reference to \\\"%s\\\"\", ref.name)\ else\ link(ref, got)\ end\ end\ \ if error_count > 0 then\ if error_count == 1 then\ print(\"Encountered an error in the linking process. Aborting.\")\ else\ print(\"Encountered \"..error_count..\" errors in the linking process. Aborting.\")\ end\ os.exit(1)\ end\ \ if listing then listing:close() end\ ","@src/assemble.lua")() load("local output, e = io.open(output_filename, \"wb\")\ if not output then\ print(e)\ os.exit(1)\ end\ \ output:write(\"v2.0 raw\\n\\n\")\ \ local highest_addr = mem_base + mem_size - 1\ while (memory[highest_addr] == 0 or memory[highest_addr] == nil) and highest_addr >= mem_base do\ highest_addr = highest_addr - 1\ end\ \ for n=mem_base, highest_addr do\ output:write((\"%04X\\n\"):format(memory[n]))\ end\ output:close()\ ","@src/output.lua")()
30.034031
308
0.540835
c2ded415ede81371647e758c03fb51dd902866bf
11,174
asm
Assembly
intro/multifx.asm
FolkertVanVerseveld/c64
a244b976cc650a86566b88066c0f7cb3a3915f09
[ "MIT" ]
1
2018-12-26T22:55:37.000Z
2018-12-26T22:55:37.000Z
intro/multifx.asm
FolkertVanVerseveld/c64
a244b976cc650a86566b88066c0f7cb3a3915f09
[ "MIT" ]
null
null
null
intro/multifx.asm
FolkertVanVerseveld/c64
a244b976cc650a86566b88066c0f7cb3a3915f09
[ "MIT" ]
null
null
null
// Assembler: KickAssembler 4.4 // dancing sprites // All made by myself (except irq code) BasicUpstart2(start) .var irq_line_top = $28 .var irq_line_top2 = $3a .var irq_line_bottom = $fc //.var spr_data = $2800 // Update this to your HVSC directory .var music = LoadSid("/home/methos/Music/C64Music/MUSICIANS/0-9/20CC/van_Santen_Edwin/Spijkerhoek.sid") // cool remix: //.var music = LoadSid("/home/methos/Music/C64Music/MUSICIANS/A/Audial_Arts/Balai_Rodney/Spijkerhoek.sid") //set variables and locations .var buf = $2700 .var colram = $d800 .var vic = $4000 .var bitmap = vic + 0 .var screen = vic + $2000 .var spr_data = vic + $2400 .var font = vic + $3000 .var top_textptr = screen .var top_colptr = $d800 .var debug = false * = $0810 "multifx" start: jsr copy_buf_to_colram jsr scrclr jsr scr_init jsr top_init jsr spr_init lda #music.startSong - 1 jsr music.init jsr irq_init // it's showtime! lda #0 sta $d020 sta $d021 jmp * top_init: ldx #0 !l: lda !tbl+, x sta top_colptr, x lda #' ' sta screen, x inx cpx #40 bne !l- rts !tbl: .byte 11, 11, 12, 15 .byte 1, 1, 1, 1, 3, 14, 6 .byte 14, 3, 1, 1, 1, 3, 14, 6 .byte 6, 14, 3, 1, 1, 1, 3, 14 .byte 6, 14, 3, 1, 1, 1, 1 .byte 15, 12, 11, 11, 11 scr_init: //screen (colors12) at $2000 bitmap at $0000 lda #%10000000 sta $d018 // multicolor (bit 4), 40 columns (bit 3) lda #%00011000 sta $d016 // bitmap mode (bit 5), screen on (bit 4), 25 rows (bit 3) lda #%00111011 sta $d011 //Bits #0-#1: VIC bank. Values: // // %00, 0: Bank #3, $C000-$FFFF, 49152-65535. // // %01, 1: Bank #2, $8000-$BFFF, 32768-49151. // // %10, 2: Bank #1, $4000-$7FFF, 16384-32767. // // %11, 3: Bank #0, $0000-$3FFF, 0-16383. // sei lda #%00000010 sta $dd00 cli rts spr_init: // setup sprite at $0340 (== 13 * 64) lda #(spr_data - vic + 64 * 0) / 64 sta screen + $03f8 lda #(spr_data - vic + 64 * 1) / 64 sta screen + $03f9 lda #(spr_data - vic + 64 * 2) / 64 sta screen + $03fa lda #(spr_data - vic + 64 * 3) / 64 sta screen + $03fb lda #(spr_data - vic + 64 * 3) / 64 sta screen + $03fc // copy sprites ldx #0 !l: lda m0spr, x sta spr_data + 64 * 0, x lda m1spr, x sta spr_data + 64 * 1, x lda m2spr, x sta spr_data + 64 * 2, x lda m3spr, x sta spr_data + 64 * 3, x // sprite 4 is identical to sprite 3 inx cpx #64 bne !l- // show sprites lda #$1f sta $d015 lda #6 sta $d027 sta $d028 sta $d029 lda #1 sta $d02a sta $d02b rts irq_bottom: asl $d019 nop nop nop nop ldx #0 !l: lda !tbl+, x sta $d020 jsr !d+ jsr !d+ jsr !d+ jsr !d+ nop inx cpx #6 bne !l- lda #0 sta $d020 .if (debug) { inc $d020 } jsr scroll jsr dance jsr music.play lda #<irq_top sta $0314 lda #>irq_top sta $0315 lda #irq_line_top sta $d012 .if (debug) { dec $d020 } pla tay pla tax pla rti !tbl: .byte 1, 3, 1, 3, 14, 3, 14, 6 irq_top: asl $d019 nop nop nop nop ldx #0 !l: lda !tbl+, x sta $d020 jsr !d+ jsr !d+ jsr !d+ jsr !d+ nop inx cpx #6 bne !l- lda #0 sta $d020 .if (debug) { inc $d020 } // apply horizontal position lda #%11000000 ora scroll_xpos sta $d016 // text mode (bit5 = 0), screen on (bit4 = 1), 25 rows (bit3 = 1) lda #%00011011 sta $d011 // screen at $400, font bitmap at $3000 lda #%10001100 sta $d018 lda #<irq_top2 sta $0314 lda #>irq_top2 sta $0315 lda #irq_line_top2 sta $d012 .if (debug) { dec $d020 } pla tay pla tax pla rti !d: rts !tbl: .byte 6, 14, 3, 14, 3, 1, 3, 1 irq_top2: asl $d019 .if (debug) { inc $d020 } //screen (colors12) at $2000 bitmap at $0000 lda #%10000000 sta $d018 // multicolor (bit 4), 40 columns (bit 3) lda #%00011000 sta $d016 // bitmap mode (bit 5), screen on (bit 4), 25 rows (bit 3) lda #%00111011 sta $d011 lda #<irq_bottom sta $0314 lda #>irq_bottom sta $0315 lda #irq_line_bottom sta $d012 .if (debug) { dec $d020 } pla tay pla tax pla rti copy_buf_to_colram: ldx #0 !l: lda buf + 0 * 256, x sta colram + 0 * 256, x lda buf + 1 * 256, x sta colram + 1 * 256, x lda buf + 2 * 256, x sta colram + 2 * 256, x lda buf + 3 * 256, x sta colram + 3 * 256, x dex bne !l- rts scroll: // verplaats horizontaal lda scroll_xpos sec sbc scroll_speed and #$07 sta scroll_xpos bcc !move+ jmp !done+ !move: // verplaats alles één naar links ldx #$00 !l: lda top_textptr + 1, x sta top_textptr, x inx cpx #40 bne !l- // haal eentje op uit de rij !textptr: lda scroll_text cmp #$ff bne !nowrap+ jsr top_restore !nowrap: sta top_textptr + 39 // werk text ptr bij inc !textptr- + 1 bne !done+ inc !textptr- + 2 !done: rts top_restore: // herstel ptr lda #<scroll_text sta !textptr- + 1 sta !ptr+ + 1 lda #>scroll_text sta !textptr- + 2 sta !ptr+ + 2 !ptr: lda scroll_text rts dance: ldx m0p lda sinx, x sta $d000 lda siny + $30, x sta $d001 inx inx stx m0p ldx m1p lda sinx + $8, x sta $d002 lda siny + $38, x sta $d003 inx inx stx m1p ldx m2p lda sinx + $10, x sta $d004 lda siny + $40, x sta $d005 inx inx stx m2p // side sprites ldx m3p lda #40 sta $d006 lda siny2 + $40, x sta $d007 inx inx inx inx inx stx m3p ldx m4p lda #$10 sta $d010 lda #44 sta $d008 lda siny2 + $40 + $80, x sta $d009 inx inx inx inx inx stx m4p rts scrclr: ldx #0 lda #' ' !l: sta $0400,x sta $0500,x sta $0600,x sta $06e8,x inx bne !l- rts irq_init: // zet irq done sei lda #<irq_bottom sta $0314 lda #>irq_bottom sta $0315 // zorg dat de irq gebruikt wordt asl $d019 // geen idee wat dit precies doet // het zet alle interrupts eerst uit en dan // de volgende aan: timer a, timer b, flag pin, serial shift lda #$7b sta $dc0d // zet raster interrupt aan lda #$81 sta $d01a // bit-7 van de te schrijven waarde is bit-8 van de interruptregel (hier 0) // tekst mode (bit-5 uit) // scherm aan (bit-4 aan) // 25 rijen (bit-3 aan) // y scroll = 3 (bits 0-2) lda $d011 and #%01111111 sta $d011 // de onderste 8-bits van de interruptregel. // dus: regel $80 (128) lda #irq_line_top sta $d012 // vanaf nu kunnen de interrupts gevuurd worden cli rts m0p: .byte 0 m1p: .byte 0 m2p: .byte 0 m3p: .byte 0 m4p: .byte 0 .align $100 m0spr: .byte %01111110, %00000000, %01111110 .byte %01111110, %00000000, %01111110 .byte %01111110, %00000000, %01111110 .byte %01111110, %00000000, %01111110 .byte %01111110, %00000000, %01111110 .byte %01111110, %00000000, %01111110 .byte %01111110, %00000000, %01111110 .byte %01111110, %00000000, %01111110 .byte %01111110, %00000000, %01111110 .byte %01111110, %00000000, %01111110 .byte %01111110, %00000000, %01111110 .byte %01111111, %00000000, %11111110 .byte %01111111, %00000000, %11111110 .byte %01111111, %10000001, %11111110 .byte %01111111, %11111111, %11111110 .byte %01111111, %11111111, %11111110 .byte %01111111, %11111111, %11111110 .byte %00111111, %11111111, %11111100 .byte %00011111, %11111111, %11111000 .byte %00001111, %11111111, %11110000 .byte %00000011, %11111111, %11000000 .byte 0 m1spr: .byte %01111110, %00000000, %01111110 .byte %01111111, %00000000, %01111110 .byte %01111111, %10000000, %01111110 .byte %01111111, %11000000, %01111110 .byte %01111111, %11100000, %01111110 .byte %01111111, %11110000, %01111110 .byte %01111111, %11111000, %01111110 .byte %01111111, %11111100, %01111110 .byte %01111110, %11111110, %01111110 .byte %01111110, %01111111, %01111110 .byte %01111110, %00111111, %11111110 .byte %01111110, %00011111, %11111110 .byte %01111110, %00001111, %11111110 .byte %01111110, %00000111, %11111110 .byte %01111110, %00000011, %11111110 .byte %01111110, %00000001, %11111110 .byte %01111110, %00000000, %11111110 .byte %01111110, %00000000, %01111110 .byte %01111110, %00000000, %01111110 .byte %01111110, %00000000, %01111110 .byte %01111110, %00000000, %01111110 .byte 0 m2spr: .byte %00000000, %01111111, %00000000 .byte %00000001, %11111111, %11000000 .byte %00000011, %11111111, %11100000 .byte %00000111, %11111111, %11110000 .byte %00001111, %11110001, %11110000 .byte %00001111, %11000000, %01100000 .byte %00011111, %10000000, %00000000 .byte %00011111, %10000000, %00000000 .byte %00111111, %00000000, %00000000 .byte %00111111, %00000000, %00000000 .byte %00111111, %00000000, %00000000 .byte %00111111, %00000000, %00000000 .byte %00111111, %00000000, %00000000 .byte %00011111, %10000000, %00000000 .byte %00011111, %10000000, %00000000 .byte %00001111, %11000000, %01100000 .byte %00001111, %11110001, %11110000 .byte %00000111, %11111111, %11110000 .byte %00000011, %11111111, %11100000 .byte %00000001, %11111111, %11000000 .byte %00000000, %01111111, %00000000 .byte 0 m3spr: .byte %00000001, %11111100, %00000000 .byte %00000111, %11111111, %00000000 .byte %00001111, %11111111, %10000000 .byte %00011111, %11111111, %11000000 .byte %00111111, %11000111, %11000000 .byte %00111111, %00000001, %10000000 .byte %01111110, %00000000, %11111111 .byte %01111110, %00000000, %11111110 .byte %11111100, %00000000, %11111100 .byte %11111100, %00000000, %11111000 .byte %11111100, %00000000, %00000000 .byte %11111100, %00000000, %11111000 .byte %11111100, %00000000, %11111100 .byte %01111110, %00000000, %11111110 .byte %01111110, %00000000, %11111111 .byte %00111111, %00000001, %10000000 .byte %00111111, %11000111, %11000000 .byte %00011111, %11111111, %11000000 .byte %00001111, %11111111, %10000000 .byte %00000111, %11111111, %00000000 .byte %00000001, %11111100, %00000000 .byte 0 scroll_xpos: .byte 0 scroll_speed: .byte 2 scroll_char: .byte 0 scroll_text: //.text "hallo daar! test 1 2 3 dit is een test.... lekker klooien bij de hcc... " .text "hello under construction 2017! this is methos' little compofiller. " .text "this is completely coded at the party. " .text "as always, my hardest problem on the c64 is to get started at all! " .text "this demo would not be possible without the assistance of fieserwolf. " .text "code by methos, music by evs. " .text "greetings fly out to abyss connection, censor design, duncan, fairlight, fred, genesis project, miri-kat, monoceros, prosonix, scs-trc, stephan and all other groups and sceners! " .text "have fun and see ya in 2018! ....... ... .. . " .byte $ff * = music.location "music" .fill music.size, music.getData(i) .print "music_init = $" + toHexString(music.init) .print "music_play = $" + toHexString(music.play) // sprite movement tables .align $100 sinx: // waveform h, min 70, max 255 .import binary "sin2.bin" .import binary "sin2.bin" siny: // waveform h, min 70, max 170 .import binary "sin3.bin" .import binary "sin3.bin" siny2: .fill $100, round($90 + $40 * sin(toRadians(i * 360 / $100))) .fill $100, round($90 + $40 * sin(toRadians(i * 360 / $100))) * = font "font" .import binary "../assets/aeg_collection_05.64c", 2 * = bitmap "bitmap" .import binary "../assets/c64.koa", 2, 8000 * = screen "screen" .import binary "../assets/c64.koa", 2 + 8000, 40 * 25 * = buf "buf" .import binary "../assets/c64.koa", 2 + 8000 + 40 * 25, 40 * 25
18.228385
187
0.652855
a188dbaf171ef187ca8f89b43e4141ebef91bbe0
785
ts
TypeScript
src/ui-kit/form-controls/date-time/date-time.spec.ts
OctoConsulting/sam-ui-elements
5880b12b956b403dce5ca5be5bc30de01e515fcc
[ "MIT" ]
null
null
null
src/ui-kit/form-controls/date-time/date-time.spec.ts
OctoConsulting/sam-ui-elements
5880b12b956b403dce5ca5be5bc30de01e515fcc
[ "MIT" ]
null
null
null
src/ui-kit/form-controls/date-time/date-time.spec.ts
OctoConsulting/sam-ui-elements
5880b12b956b403dce5ca5be5bc30de01e515fcc
[ "MIT" ]
null
null
null
import { TestBed } from '@angular/core/testing'; // Load the implementations that should be tested import { SamDateTimeComponent } from './date-time.component'; import { SamUIKitModule } from '../../index'; describe('The Sam Date Time component', () => { let component: SamDateTimeComponent; let fixture: any; // provide our implementations or mocks to the dependency injector beforeEach(() => { TestBed.configureTestingModule({ imports: [SamUIKitModule], providers: [SamDateTimeComponent], }); fixture = TestBed.createComponent(SamDateTimeComponent); component = fixture.componentInstance; component.value = "2016-12-31T12:01"; component.name = 'test'; }); it('Should compile', function () { expect(true).toBe(true); }); });
28.035714
68
0.68535
2cb1550bff9a1cf74120b2eee5eb7a4d1fdb522d
8,536
py
Python
improvedGAN/.ipynb_checkpoints/improvedGAN-checkpoint.py
Ontheway361/ak47GAN
7a1b4b3c2159ab0e2662f3d0a2cedccb30e62f3c
[ "MIT" ]
null
null
null
improvedGAN/.ipynb_checkpoints/improvedGAN-checkpoint.py
Ontheway361/ak47GAN
7a1b4b3c2159ab0e2662f3d0a2cedccb30e62f3c
[ "MIT" ]
null
null
null
improvedGAN/.ipynb_checkpoints/improvedGAN-checkpoint.py
Ontheway361/ak47GAN
7a1b4b3c2159ab0e2662f3d0a2cedccb30e62f3c
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import pdb import torch import argparse import numpy as np import tensorboardX import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable from functional import log_sum_exp from torch.utils.data import DataLoader,TensorDataset from dataset import * from model import Generator, Discriminator from IPython import embed class ImprovedGAN(object): def __init__(self, G, D, labeled, unlabeled, test, args): if os.path.exists(args.savedir): print('Loading model from ' + args.savedir) self.G = torch.load(os.path.join(args.savedir, 'G.pkl')) self.D = torch.load(os.path.join(args.savedir, 'D.pkl')) else: os.mkdir(args.savedir) self.G = G self.D = D torch.save(self.G, os.path.join(args.savedir, 'G.pkl')) torch.save(self.D, os.path.join(args.savedir, 'D.pkl')) self.writer = tensorboardX.SummaryWriter(log_dir=args.logdir) if args.cuda: self.G.cuda() self.D.cuda() self.labeled = labeled self.unlabeled = unlabeled self.test = test self.Doptim = optim.Adam(self.D.parameters(), lr=args.lr, betas= (args.momentum, 0.999)) self.Goptim = optim.Adam(self.G.parameters(), lr=args.lr, betas = (args.momentum,0.999)) self.args = args def trainD(self, x_label, y, x_unlabel): x_label, x_unlabel, y = Variable(x_label), Variable(x_unlabel), Variable(y, requires_grad = False) if self.args.cuda: x_label, x_unlabel, y = x_label.cuda(), x_unlabel.cuda(), y.cuda() output_label = self.D(x_label, cuda=self.args.cuda) output_unlabel = self.D(x_unlabel, cuda=self.args.cuda) output_fake = self.D(self.G(x_unlabel.size()[0], cuda = self.args.cuda).view(x_unlabel.size()).detach(), cuda=self.args.cuda) logz_label, logz_unlabel, logz_fake = log_sum_exp(output_label), log_sum_exp(output_unlabel), log_sum_exp(output_fake) # log ∑e^x_i prob_label = torch.gather(output_label, 1, y.unsqueeze(1)) # log e^x_label = x_label loss_supervised = -torch.mean(prob_label) + torch.mean(logz_label) loss_unsupervised = 0.5 * (-torch.mean(logz_unlabel) + torch.mean(F.softplus(logz_unlabel)) + # real_data: log Z/(1+Z) torch.mean(F.softplus(logz_fake)) ) # fake_data: log 1/(1+Z) loss = loss_supervised + self.args.unlabel_weight * loss_unsupervised acc = torch.mean((output_label.max(1)[1] == y).float()) self.Doptim.zero_grad() loss.backward() self.Doptim.step() return loss_supervised.data.cpu().numpy(), loss_unsupervised.data.cpu().numpy(), acc def trainG(self, x_unlabel): fake = self.G(x_unlabel.size()[0], cuda = self.args.cuda).view(x_unlabel.size()) mom_gen, output_fake = self.D(fake, feature=True, cuda=self.args.cuda) mom_unlabel, _ = self.D(Variable(x_unlabel), feature=True, cuda=self.args.cuda) mom_gen = torch.mean(mom_gen, dim = 0) mom_unlabel = torch.mean(mom_unlabel, dim = 0) loss_fm = torch.mean((mom_gen - mom_unlabel) ** 2) loss = loss_fm self.Goptim.zero_grad() self.Doptim.zero_grad() loss.backward() self.Goptim.step() return loss.data.cpu().numpy() def train(self): assert self.unlabeled.__len__() > self.labeled.__len__() assert type(self.labeled) == TensorDataset times = int(np.ceil(self.unlabeled.__len__() * 1. / self.labeled.__len__())) t1 = self.labeled.tensors[0].clone() t2 = self.labeled.tensors[1].clone() tile_labeled = TensorDataset(t1.repeat(times,1,1,1),t2.repeat(times)) gn = 0 for epoch in range(self.args.epochs): self.G.train() self.D.train() unlabel_loader1 = DataLoader(self.unlabeled, batch_size = self.args.batch_size, shuffle=True, drop_last=True, num_workers = 4) unlabel_loader2 = DataLoader(self.unlabeled, batch_size = self.args.batch_size, shuffle=True, drop_last=True, num_workers = 4).__iter__() label_loader = DataLoader(tile_labeled, batch_size = self.args.batch_size, shuffle=True, drop_last=True, num_workers = 4).__iter__() loss_supervised = loss_unsupervised = loss_gen = accuracy = 0. batch_num = 0 for (unlabel1, _label1) in unlabel_loader1: batch_num += 1 unlabel2, _label2 = unlabel_loader2.next() x, y = label_loader.next() if args.cuda: x, y, unlabel1, unlabel2 = x.cuda(), y.cuda(), unlabel1.cuda(), unlabel2.cuda() ll, lu, acc = self.trainD(x, y, unlabel1) loss_supervised += ll loss_unsupervised += lu accuracy += acc lg = self.trainG(unlabel2) if epoch > 1 and lg > 1: lg = self.trainG(unlabel2) loss_gen += lg if (batch_num + 1) % self.args.log_interval == 0: print('Training: %d / %d' % (batch_num + 1, len(unlabel_loader1))) gn += 1 with torch.no_grad(): self.writer.add_scalars('loss', {'loss_supervised':ll, 'loss_unsupervised':lu, 'loss_gen':lg}, gn) self.writer.add_histogram('real_feature', self.D(Variable(x), cuda=self.args.cuda, feature = True)[0], gn) self.writer.add_histogram('fake_feature', self.D(self.G(self.args.batch_size, cuda = self.args.cuda), cuda=self.args.cuda, feature = True)[0], gn) self.writer.add_histogram('fc3_bias', self.G.fc3.bias, gn) self.writer.add_histogram('D_feature_weight', self.D.layers[-1].weight, gn) self.D.train() self.G.train() loss_supervised /= batch_num loss_unsupervised /= batch_num loss_gen /= batch_num accuracy /= batch_num print("Iteration %d, loss_supervised = %.4f, loss_unsupervised = %.4f, loss_gen = %.4f train acc = %.4f" % \ (epoch, loss_supervised, loss_unsupervised, loss_gen, accuracy)) sys.stdout.flush() if (epoch + 1) % self.args.eval_interval == 0: print("Eval: correct %d / %d" % (self.eval(), self.test.__len__())) torch.save(self.G, os.path.join(args.savedir, 'G.pkl')) torch.save(self.D, os.path.join(args.savedir, 'D.pkl')) def predict(self, x): with torch.no_grad(): ret = torch.max(self.D(Variable(x), cuda=self.args.cuda), 1)[1].data return ret def eval(self): self.G.eval() self.D.eval() d, l = [], [] for (datum, label) in self.test: d.append(datum) l.append(label) x, y = torch.stack(d), torch.LongTensor(l) if self.args.cuda: x, y = x.cuda(), y.cuda() pred = self.predict(x) return torch.sum(pred == y) def draw(self, batch_size): self.G.eval() return self.G(batch_size, cuda=self.args.cuda) def config(): parser = argparse.ArgumentParser(description='PyTorch Improved GAN') parser.add_argument('--batch-size', type=int, default=100) parser.add_argument('--epochs', type=int, default=10) parser.add_argument('--lr', type=float,default=0.003) parser.add_argument('--momentum', type=float,default=0.5) parser.add_argument('--cuda', type=bool, default=True) parser.add_argument('--seed', type=int, default=1) parser.add_argument('--log-interval', type=int, default=100) parser.add_argument('--eval-interval', type=int, default=1) parser.add_argument('--unlabel-weight', type=float, default=1) parser.add_argument('--logdir', type=str, default='./logfile') parser.add_argument('--savedir', type=str, default='./models') args = parser.parse_args() return args if __name__ == '__main__': args = config() args.cuda = args.cuda and torch.cuda.is_available() np.random.seed(args.seed) gan = ImprovedGAN(Generator(100), Discriminator(), MnistLabel(10), MnistUnlabel(), MnistTest(), args) gan.train()
46.644809
170
0.598993
ff51bccf79b0d828e00a0615eabf3b3e94f43bcf
2,691
py
Python
src/doom/game.py
phillikus/doom-ai
ee0d49ae46321960adacc054d041377622877b10
[ "MIT" ]
2
2019-02-15T05:53:24.000Z
2020-08-27T09:25:08.000Z
src/doom/game.py
philipp007/doom-ai
ee0d49ae46321960adacc054d041377622877b10
[ "MIT" ]
null
null
null
src/doom/game.py
philipp007/doom-ai
ee0d49ae46321960adacc054d041377622877b10
[ "MIT" ]
1
2020-07-15T12:21:27.000Z
2020-07-15T12:21:27.000Z
import os import torch import torch.multiprocessing as _mp from models.a2c.A2C import A2C from models.a2c.test import test as test_a2c from models.a2c.train import train as train_a2c from models.a3c.A3C import A3C from models.a3c import optimizers from models.a3c.test import test as test_a3c from models.a3c.train import train as train_a3c from models.dqn.DQN import DQN from models.dqn.NStepProgress import NStepProgress from models.dqn.SoftmaxBody import SoftmaxBody from models.dqn.AI import AI from models.dqn.ReplayMemory import ReplayMemory from models.dqn.train import train as train_dqn from models.dqn.train import eligibility_trace from doom.doom_trainer import DoomTrainer mp = _mp.get_context('spawn') def play(parameters): dtype = torch.cuda.FloatTensor torch.manual_seed(parameters.seed) torch.set_default_tensor_type('torch.cuda.FloatTensor') if parameters.model == 'human': play_human(parameters) elif parameters.model == 'a3c': play_a3c(parameters) elif parameters.model == 'a2c': play_a2c(parameters) elif parameters.model == 'dqn': play_dqn(parameters) def play_human(params): trainer = DoomTrainer(params) trainer.start_game() trainer.play_human() def play_a2c(params): trainer = DoomTrainer(params) trainer.start_game() model = A2C(1, params.num_actions).cuda() optimizer = torch.optim.Adam(model.parameters(), lr=params.lr) counter = 0 while True: if counter % 10 == 0: print("Iteration: ", counter) train_a2c(params, trainer, model, optimizer) test_a2c(params, trainer, model) counter += 1 def play_a3c(params): trainer = DoomTrainer(params) os.environ['OMP_NUM_THREADS'] = '1' shared_model = A3C(1, trainer.num_actions()).cuda() shared_model.share_memory() optimizer = optimizers.SharedAdam(shared_model.parameters(), lr=params.lr) optimizer.share_memory() processes = [] process = mp.Process(target=test_a3c, args=(params.num_processes, params, shared_model)) process.start() for rank in range(0, params.num_processes): process = mp.Process(target=train_a3c, args=(rank, params, shared_model, optimizer)) process.start() processes.append(process) for p in processes: p.join() def play_dqn(params): trainer = DoomTrainer(params) trainer.start_game() model = DQN(trainer.num_actions()) softmax_body = SoftmaxBody(T=1) ai = AI(brain=model, body=softmax_body) n_steps = NStepProgress(trainer, ai, n_step=10) memory = ReplayMemory(n_steps=n_steps, capacity=10000) train_dqn(model, memory, n_steps)
27.742268
92
0.712746
1a3c0e73d62ab9e8593abd0d24ea126a0211acb3
3,911
py
Python
Code/Password generator.py
RIR360/Python-Password-Generator
3ce6f201c06e6747b86e966cc7ed829f3b68dc68
[ "MIT" ]
2
2020-11-12T07:10:41.000Z
2021-03-12T10:59:05.000Z
Code/Password generator.py
RIR360/Python-Password-Generator
3ce6f201c06e6747b86e966cc7ed829f3b68dc68
[ "MIT" ]
null
null
null
Code/Password generator.py
RIR360/Python-Password-Generator
3ce6f201c06e6747b86e966cc7ed829f3b68dc68
[ "MIT" ]
1
2020-11-12T11:58:15.000Z
2020-11-12T11:58:15.000Z
import tkinter as app from tkinter import messagebox from tkinter import Scrollbar import random #definitions family = "sans serif" primary_c = "#2065d4" second_c = "#e8e8e8" inherit = "white" algorithm_count = 5 keywords = [] passwords = [] window = app.Tk() window.title("Password Generator") window.config(bg=inherit) #elements scrollbar = Scrollbar(window) scrollbar.pack( side = app.RIGHT, fill = app.Y ) main_header = app.Label(window, text="PASSWORD GENERATOR",fg=primary_c, bg=inherit, font=(family, 24), pady=10, padx=20) sub_info = app.Label(window, text="This program generates passwords using the keywords you enter. Currently, the program is using {} algorithm(s) to generate passwords.".format(algorithm_count), fg="grey", bg=inherit, font=(family, 12), wraplength=440, justify=app.LEFT, pady=10, padx=10) input_box = app.Entry(window,font=(family, 16), width=30, borderwidth=10, fg=primary_c, bg=second_c, relief=app.FLAT) submit = app.Button(window, text="Generate", font=(family, 12), width=35, borderwidth=5,relief=app.RAISED, bg=primary_c,activebackground=primary_c, fg=inherit, activeforeground=inherit) pass_header = app.Label(window, text="Passwords", fg=primary_c, bg=inherit, pady=10, font=(family, 16)) pass_list = app.Listbox(window, yscrollcommand = scrollbar.set, bg=primary_c, fg=inherit, font=(family, 12), width=42, bd=5) def main(): submit.config(command = start_app) #packing main_header.pack() sub_info.pack() input_box.pack() add_space(window, 1) submit.pack() pass_header.pack() pass_list.pack() add_space(window, 1) scrollbar.config(command = pass_list.yview) messagebox.showinfo("Credit", "This was programmed by Rejwan Islam Rizvy #RIR360") window.mainloop() #functions def add_space(master, amount): white_space = app.Label(master, text=" ", height=amount, bg=inherit) white_space.pack() def start_app(): input = input_box.get() if not input: messagebox.showwarning("No Input", "Enter some keywards first") return 1 keywords = input.split() pass_list.delete(0, app.END) #generating passwords algo_1(keywords, pass_list) algo_2(keywords, pass_list) algo_3(keywords, pass_list) algo_4(keywords, pass_list) algo_5(keywords, pass_list) #algorithms def algo_1(words, list): password = str(random.randint(0,9))*random.randint(0, 5) + str("".join(words)) + str(random.randint(0,9))*random.randint(0, 5) list.insert(app.END, password) def algo_2(words, list): password = "" for word in words: for char in word: if random.randint(0, 1): password += char.upper() else: password += char.lower() list.insert(app.END, password) def algo_3(words, list): password = "" for word in words: if random.randint(0, 1): password += word.upper() else: password += word.lower() password += str(random.randint(0,9))*random.randint(1, 5) list.insert(app.END, password) def algo_4(words, list): password = "" password += str(chr(random.randint(33,47)))*random.randint(1, 5) for word in words: if random.randint(0, 1): password += word.capitalize() else: password += word.lower() password += str(chr(random.randint(33,47)))*random.randint(1, 5) list.insert(app.END, password) def algo_5(words, list): password = "" password += str(chr(random.randint(33,47)))*random.randint(1, 5) for word in words: if random.randint(0, 1): password += word.capitalize() else: password += word.lower() password += str(random.randint(0,9))*random.randint(1, 5) list.insert(app.END, password) main()
26.248322
288
0.644336
0d3d71af42f9ed5c988dd006f70d5d623752bee5
2,348
cs
C#
Assets/com.fluid.stats/Runtime/Definitions/Compiled/StatDefinitionsCompiled.cs
ashblue/fluid-stats
6447915ec50705ea9710ab610dce7137c1d7e8c7
[ "MIT" ]
28
2021-04-11T02:19:46.000Z
2022-02-12T05:09:59.000Z
Assets/com.fluid.stats/Runtime/Definitions/Compiled/StatDefinitionsCompiled.cs
ashblue/fluid-stats
6447915ec50705ea9710ab610dce7137c1d7e8c7
[ "MIT" ]
7
2021-04-11T02:03:53.000Z
2022-02-02T02:20:29.000Z
Assets/com.fluid.stats/Runtime/Definitions/Compiled/StatDefinitionsCompiled.cs
ashblue/fluid-stats
6447915ec50705ea9710ab610dce7137c1d7e8c7
[ "MIT" ]
3
2021-04-11T11:10:06.000Z
2021-06-19T18:54:21.000Z
using System.Collections.Generic; namespace CleverCrow.Fluid.StatsSystem { /// <summary> /// A collection for caching stat defintion collections at runtime /// </summary> public class StatDefinitionsCompiled { private Dictionary<StatDefinitionCollection, List<StatDefinition>> _compiled = new Dictionary<StatDefinitionCollection, List<StatDefinition>>(); public List<StatDefinition> Get (StatDefinitionCollection id) { if (id == null) return null; List<StatDefinition> definitions; if (_compiled.TryGetValue(id, out definitions)) { return definitions; } definitions = id.GetDefinitions(); // Append default definitions that haven't already been added var defaults = GetDefaults(); if (defaults != null) { foreach (var statDefinition in defaults) { if (definitions.Contains(statDefinition)) continue; definitions.Add(statDefinition); } } _compiled[id] = definitions; return definitions; } public List<StatDefinition> GetDefaults () { var id = StatsSettings.Current.DefaultStats; if (id == null) return null; List<StatDefinition> definitions; if (_compiled.TryGetValue(id, out definitions)) { return definitions; } definitions = id.GetDefinitions(); _compiled[id] = definitions; return definitions; } public static List<StatDefinition> GetDefinitions (StatDefinitionCollection id) { if (id == null) return null; var definitions = id.GetDefinitions(); var defaults = GetDefinitionDefaults(); if (defaults == null) return definitions; foreach (var statDefinition in defaults) { if (definitions.Contains(statDefinition)) continue; definitions.Add(statDefinition); } return definitions; } public static List<StatDefinition> GetDefinitionDefaults () { var id = StatsSettings.Current.DefaultStats; if (id == null) return null; return id.GetDefinitions(); } } }
32.164384
152
0.584327
1b03a1e9a22cfa1df33d9ce837aad88c6e091b61
223
swift
Swift
CombineOperatorGuideSample.playground/Pages/erase2.xcplaygroundpage/Contents.swift
usami-k/CombineOperatorGuideSample
7a97c1b3443ba77c22807a216499b5cac193620c
[ "Apache-2.0" ]
null
null
null
CombineOperatorGuideSample.playground/Pages/erase2.xcplaygroundpage/Contents.swift
usami-k/CombineOperatorGuideSample
7a97c1b3443ba77c22807a216499b5cac193620c
[ "Apache-2.0" ]
null
null
null
CombineOperatorGuideSample.playground/Pages/erase2.xcplaygroundpage/Contents.swift
usami-k/CombineOperatorGuideSample
7a97c1b3443ba77c22807a216499b5cac193620c
[ "Apache-2.0" ]
null
null
null
import Combine let publisher0 = PassthroughSubject<Int, Never>() let publisher1 = publisher0 .filter { $0 > 0 } .map { $0 * 2 } let publisher2 = publisher1 .eraseToAnyPublisher() print(type(of: publisher2))
17.153846
49
0.67713
54b6c91ccb501a2ed232446a17f97adb6ce7cd71
355
c
C
C/SwapAdjacentinLRString.c
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
1
2018-01-22T12:06:28.000Z
2018-01-22T12:06:28.000Z
C/SwapAdjacentinLRString.c
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
C/SwapAdjacentinLRString.c
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
#include <stdbool.h> bool canTransform(char *start, char *end) { int l = 0, r = 0; for (int i = 0; start[i]; ++i) { if (start[i] != 'X') start[i] == 'R' ? ++r : ++l; if (l != 0 && r > 0) return false; if (end[i] != 'X') end[i] == 'R' ? --r : --l; if (l > 0 || r < 0 || (l < 0 && r > 0)) return false; } return l == 0 && r == 0; }
19.722222
41
0.419718
a4a26b7f952da13e011012ffe7776aa068b81359
4,613
php
PHP
resources/views/branches/index.blade.php
pug3eye/loyalty
b896000f577ae1385184acd74e0f6b73f0b5ad87
[ "MIT" ]
null
null
null
resources/views/branches/index.blade.php
pug3eye/loyalty
b896000f577ae1385184acd74e0f6b73f0b5ad87
[ "MIT" ]
null
null
null
resources/views/branches/index.blade.php
pug3eye/loyalty
b896000f577ae1385184acd74e0f6b73f0b5ad87
[ "MIT" ]
null
null
null
@extends('layouts.template') @section('title', 'Branch') @section('branch_menu', 'class="treeview active"') @section('branch_list', 'class="active"') @section('css') <style> .displayed { displayed: block; margin-left: auto; margin-right: auto; max-height: 75%; max-width: 75%; } </style> @endsection @section('content') <section class="content-header"> <h1>BRANCHES LIST</h1> </section> <section class="content"> <div class="row"> <div class="col-sm-12"> <!-- start box. --> <div class="box"> <div class="box-header"> </div> <!-- content inside here. --> <div class="box-body"> <!-- data table. --> <table class="table table-hover"> <thead> <th>Branch Name</th> <th>Branch E-mail</th> <th>Branch Address</th> <th style="width:5%; text-align:center;">View</th> <th style="width:5%; text-align:center;">Edit</th> <th style="width:5%; text-align:center;">Delete</th> </thead> <tbody> @foreach ($branches as $branch) <tr> <td>{{ $branch->name }}</td> <td>{{ $branch->shop->email }}</td> <td>{{ $branch->shop->address }}</td> <td style="text-align:center;"><span style="cursor:pointer;" class="glyphicon glyphicon-eye-open" onclick="showDetail({{ $branch->sub_id }}, '{{ $branch->name }}')"></span></td> <td style="text-align:center;"><a href="{{ url('/branch/'.$branch->sub_id.'/edit') }}"><span class="glyphicon glyphicon-pencil"></span></a></td> <td style="text-align:center;"><span class="glyphicon glyphicon-trash" style="color:red; cursor:pointer;" onclick="deleteConfirm({{ $branch->sub_id }}, '{{ $branch->name }}')"></span></td> </tr> @endforeach </tbody> </table> <!-- end table. --> </div> <div style="border-style:none;" class="box-footer" > </div> </div> <!-- end box. --> </div> </div> <!-- modal for show data --> <div class="modal fade" id="view_modal" tabindex="-1" role="dialog" aria-labelledby="view_modal_label"> <div class="modal-dialog" role="document"> <div class="modal-content"> <!-- head of modal --> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h3 class="modal-title branch_name" id="view_modal_label">Branch Name</h3> </div> <!-- end head --> <!-- content inside here --> <div class="modal-body show_branch"> ..... </div> <!-- end content --> <!-- footer of modal --> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> <!-- end footer --> </div> </div> </div> <!-- end modal --> </section> @endsection @section('js') <script> // sweet alert confirm when delete icon is click. function deleteConfirm(id, name) { swal({ title: "Delete Confirm", text: "Are you sure you want to delete branch \"" + name + "\"", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Delete", closeOnConfirm: false }, function() { swal("Deleted !", "Wait for refresh in a few second", "success"); $.post("{{ url('branch') }}/" + id, function(result){ if ( !result.localeCompare('guest') ) { window.location.assign("{{ url('login') }}"); } else { window.location.reload(); } }); }); } </script> <script> function showDetail(id, name) { $.get("{{ url('branch') }}/" + id, function(result) { $( ".show_branch" ).html(result); $( ".branch_name").html(name); $('#view_modal').modal('show'); }); } </script> @if (Session::has('flash_message')) <script> $(document).ready(function() { swal({ title: "Success !", text: "Edit branch complete.", type: "success", timer: 1500, showConfirmButton: false }); }); </script> @endif @if (Session::has('error_message')) <script> $(document).ready(function() { swal({ title: "Oops... ", text: "Some errors have occur. Please try again ! ", type: "error", confirmButtonText: "Close" }); }); </script> @endif @endsection
29.012579
206
0.529807
58f67b15de97b0d5192fe632108060c8f12a3461
560
css
CSS
css/styles-master.css
donnymays/my-first-webpage
f27a0b1ae59a91103d314ab6319e1c7b4344a1d6
[ "MIT" ]
null
null
null
css/styles-master.css
donnymays/my-first-webpage
f27a0b1ae59a91103d314ab6319e1c7b4344a1d6
[ "MIT" ]
null
null
null
css/styles-master.css
donnymays/my-first-webpage
f27a0b1ae59a91103d314ab6319e1c7b4344a1d6
[ "MIT" ]
null
null
null
body { background-color: #dee3e2; text-align: center; } h1 { color: #116979; font-size: 5.625rem; margin: 50px auto 0 auto; font-family: 'Sacramento', cursive; } h2 { color: #DE7119; font-size: 2.5rem; font-weight: normal; font-family: 'Montserrat', sans-serif; } h3 { color: #116979; font-family: 'Montserrat', sans-serif; } p { font-family: 'Montserrat', sans-serif; color: #116979; line-height: 2; } ul, ol { font-family: 'Montserrat', sans-serif; color: #DE7119; line-height: 2; list-style-position: inside; }
14.358974
40
0.6375
fc44d3b03d4e58f1f241ceee01d72c7e6185dad5
4,353
sql
SQL
bokuno_database.sql
MengDeC4o/MedicalSystem
e534c00dd5be9105dfc312cbdcb8a077d0a947a9
[ "MIT" ]
1
2021-11-11T08:00:44.000Z
2021-11-11T08:00:44.000Z
bokuno_database.sql
MengDeC4o/MedicalSystem
e534c00dd5be9105dfc312cbdcb8a077d0a947a9
[ "MIT" ]
null
null
null
bokuno_database.sql
MengDeC4o/MedicalSystem
e534c00dd5be9105dfc312cbdcb8a077d0a947a9
[ "MIT" ]
1
2021-11-12T06:05:18.000Z
2021-11-12T06:05:18.000Z
/* SQLyog v10.2 MySQL - 5.6.24-log : Database - db_appapidemo ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`bokuno_database` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; USE `bokuno_database`; DROP TABLE IF EXISTS `t_patient`; CREATE TABLE `t_patient` ( `patient_id` int(11) NOT NULL AUTO_INCREMENT, `patient_name` varchar(110) , `patient_age` int(11) , `patient_iden_id` varchar(110) , `last_hospitalizationTime` varchar(110) , `patient_sex` varchar(110) , `disease` text, `patient_account_id` varchar(110) , `patient_account_password` varchar(110) DEFAULT '88888888', PRIMARY KEY (`patient_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4; insert into `t_patient`(`patient_id`,`patient_name`,`patient_age`,`patient_iden_id`,`last_hospitalizationTime`,`patient_sex`,`disease`,`patient_account_id`,`patient_account_password`) values (NULL,'小明',10,'114514','2020.1','男','瘸腿','小明',1111),(NULL,'小刚',11,'1145141','2020.12','男','断手','xiaogang',1111); /*Table structure for table `t_album` */ DROP TABLE IF EXISTS `t_drug`; CREATE TABLE `t_drug` ( `drug_id` int(11) NOT NULL AUTO_INCREMENT, `drug_name` varchar(110) NOT NULL, `drug_producer` varchar(110) , `drug_produceDate` varchar(110), `drug_expdate` varchar(110), `stock` int(11) NOT NULL DEFAULT 1, `drug_abstract` text, `drug_description` text, `comm` varchar(110), /*comment*/ PRIMARY KEY (`drug_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4; insert into `t_drug`(`drug_id`,`drug_name`,`drug_producer`,`drug_produceDate`,`drug_expdate`,`stock`,`drug_abstract`,`drug_description`, `comm`) values (NULL, "头孢", "中国人", "昨天", "明天", 2, "头孢克圬胶囊","炎症", "无"); DROP TABLE IF EXISTS `t_room`; CREATE TABLE `t_room` ( `room_id` int(11) NOT NULL AUTO_INCREMENT, `room_function` varchar(110) NOT NULL, PRIMARY KEY (`room_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4; insert into `t_room`(`room_id`,`room_function`)values(NULL,"外科手术"),(NULL,"外科门诊"),(NULL,"内科门诊"),(NULL,"B超室"); DROP TABLE IF EXISTS `t_doctor`; CREATE TABLE `t_doctor` ( `doctor_id` int(11) NOT NULL AUTO_INCREMENT, `doctor_name` varchar(110), `doctor_age` int(11) , `doctor_major` varchar(110), `doctor_department` varchar(110), `doctor_level` varchar(110), `doctor_description` text, `doctor_experience` int(11), `doctor_account_id` varchar(110), `doctor_account_password` varchar(110), PRIMARY KEY (`doctor_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4; insert into `t_doctor`(`doctor_id`,`doctor_name`,`doctor_age`,`doctor_major`,`doctor_department`,`doctor_level`,`doctor_description`,`doctor_experience`,`doctor_account_id`,`doctor_account_password`) values(NULL,"医生贾",33,"外科手术","外科","见习","应届毕业生","0.5","AA1213","123456"),(NULL,"医生乙",34,"内科手术","内科","普通","态度良好","2","AB1444","123456HMS"); DROP TABLE IF EXISTS `t_nurse`; CREATE TABLE `t_nurse` ( `nurse_id` int(11) NOT NULL AUTO_INCREMENT, `nurse_name` varchar(110), `nurse_age` int(11) , `nurse_major` varchar(110), `nurse_department` varchar(110), `nurse_level` varchar(110), `nurse_description` text, `nurse_experience` int(11), `nurse_account_id` varchar(110), `nurse_account_password` varchar(110), PRIMARY KEY (`nurse_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4; insert into `t_nurse`(`nurse_id`,`nurse_name`,`nurse_age`,`nurse_major`,`nurse_department`,`nurse_level`,`nurse_description`,`nurse_experience`,`nurse_account_id`,`nurse_account_password`) values(NULL,"护士丁",17,"外科护理","外科","见习","应届毕业生","0.2","BB12","544322"),(NULL,"护士卡卡",44,"内科护理","内科","专业","口齿不清","4","CA1111","456HMS"); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
40.682243
337
0.690788
1f4ab735880c45a1577730ec6ca1d4beebd83516
10,516
cs
C#
sources/Interop/Windows/um/winnt/SYSTEM_CPU_SET_INFORMATION.cs
mfkl/terrafx.interop.windows
6c19a547b972ff6dcbb5456b0e5ac3e38b1c59ca
[ "MIT" ]
null
null
null
sources/Interop/Windows/um/winnt/SYSTEM_CPU_SET_INFORMATION.cs
mfkl/terrafx.interop.windows
6c19a547b972ff6dcbb5456b0e5ac3e38b1c59ca
[ "MIT" ]
null
null
null
sources/Interop/Windows/um/winnt/SYSTEM_CPU_SET_INFORMATION.cs
mfkl/terrafx.interop.windows
6c19a547b972ff6dcbb5456b0e5ac3e38b1c59ca
[ "MIT" ]
null
null
null
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/winnt.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { public partial struct SYSTEM_CPU_SET_INFORMATION { [NativeTypeName("DWORD")] public uint Size; public CPU_SET_INFORMATION_TYPE Type; [NativeTypeName("_SYSTEM_CPU_SET_INFORMATION::(anonymous union at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/um/winnt.h:12628:5)")] public _Anonymous_e__Union Anonymous; public ref _Anonymous_e__Union._CpuSet_e__Struct CpuSet { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref MemoryMarshal.GetReference(MemoryMarshal.CreateSpan(ref Anonymous.CpuSet, 1)); } } [StructLayout(LayoutKind.Explicit)] public partial struct _Anonymous_e__Union { [FieldOffset(0)] [NativeTypeName("struct (anonymous struct at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/um/winnt.h:12629:9)")] public _CpuSet_e__Struct CpuSet; public partial struct _CpuSet_e__Struct { [NativeTypeName("DWORD")] public uint Id; [NativeTypeName("WORD")] public ushort Group; [NativeTypeName("BYTE")] public byte LogicalProcessorIndex; [NativeTypeName("BYTE")] public byte CoreIndex; [NativeTypeName("BYTE")] public byte LastLevelCacheIndex; [NativeTypeName("BYTE")] public byte NumaNodeIndex; [NativeTypeName("BYTE")] public byte EfficiencyClass; [NativeTypeName("_SYSTEM_CPU_SET_INFORMATION::(anonymous union at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/um/winnt.h:12637:13)")] public _Anonymous1_e__Union Anonymous1; public ref byte AllFlags { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref MemoryMarshal.GetReference(MemoryMarshal.CreateSpan(ref Anonymous1.AllFlags, 1)); } } public byte Parked { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous1.Anonymous.Parked; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous1.Anonymous.Parked = value; } } public byte Allocated { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous1.Anonymous.Allocated; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous1.Anonymous.Allocated = value; } } public byte AllocatedToTargetProcess { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous1.Anonymous.AllocatedToTargetProcess; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous1.Anonymous.AllocatedToTargetProcess = value; } } public byte RealTime { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous1.Anonymous.RealTime; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous1.Anonymous.RealTime = value; } } public byte ReservedFlags { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous1.Anonymous.ReservedFlags; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous1.Anonymous.ReservedFlags = value; } } [NativeTypeName("_SYSTEM_CPU_SET_INFORMATION::(anonymous union at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/um/winnt.h:12654:13)")] public _Anonymous2_e__Union Anonymous2; public ref uint Reserved { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref MemoryMarshal.GetReference(MemoryMarshal.CreateSpan(ref Anonymous2.Reserved, 1)); } } public ref byte SchedulingClass { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref MemoryMarshal.GetReference(MemoryMarshal.CreateSpan(ref Anonymous2.SchedulingClass, 1)); } } [NativeTypeName("DWORD64")] public ulong AllocationTag; [StructLayout(LayoutKind.Explicit)] public partial struct _Anonymous1_e__Union { [FieldOffset(0)] [NativeTypeName("BYTE")] public byte AllFlags; [FieldOffset(0)] [NativeTypeName("_SYSTEM_CPU_SET_INFORMATION::(anonymous struct at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/um/winnt.h:12645:17)")] public _Anonymous_e__Struct Anonymous; public partial struct _Anonymous_e__Struct { public byte _bitfield; [NativeTypeName("BYTE : 1")] public byte Parked { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (byte)(_bitfield & 0x1u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (byte)((_bitfield & ~0x1u) | (value & 0x1u)); } } [NativeTypeName("BYTE : 1")] public byte Allocated { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (byte)((_bitfield >> 1) & 0x1u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (byte)((_bitfield & ~(0x1u << 1)) | ((value & 0x1u) << 1)); } } [NativeTypeName("BYTE : 1")] public byte AllocatedToTargetProcess { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (byte)((_bitfield >> 2) & 0x1u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (byte)((_bitfield & ~(0x1u << 2)) | ((value & 0x1u) << 2)); } } [NativeTypeName("BYTE : 1")] public byte RealTime { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (byte)((_bitfield >> 3) & 0x1u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (byte)((_bitfield & ~(0x1u << 3)) | ((value & 0x1u) << 3)); } } [NativeTypeName("BYTE : 4")] public byte ReservedFlags { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (byte)((_bitfield >> 4) & 0xFu); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (byte)((_bitfield & ~(0xFu << 4)) | ((value & 0xFu) << 4)); } } } } [StructLayout(LayoutKind.Explicit)] public partial struct _Anonymous2_e__Union { [FieldOffset(0)] [NativeTypeName("DWORD")] public uint Reserved; [FieldOffset(0)] [NativeTypeName("BYTE")] public byte SchedulingClass; } } } } }
37.159011
170
0.431057
540425ea201d5015ee81188751670ca258d1b08f
100
css
CSS
resources/css/app.css
ofemmy/eventbryte
e71adfa27dece63e15a02b16e1b5494ce6848893
[ "MIT" ]
null
null
null
resources/css/app.css
ofemmy/eventbryte
e71adfa27dece63e15a02b16e1b5494ce6848893
[ "MIT" ]
null
null
null
resources/css/app.css
ofemmy/eventbryte
e71adfa27dece63e15a02b16e1b5494ce6848893
[ "MIT" ]
null
null
null
.public-DraftStyleDefault-block { margin: 0px; } .react-datepicker-wrapper { width: 100%; }
14.285714
33
0.67
a7bbfcab764fb85bd2d5081e877671fb8f0f6ced
568
css
CSS
server/mod/hvp/embed.css
mohitjangra6017/tx_data
8adcb777a0b5e18d2ac66ec6dffda11572a91fc8
[ "PostgreSQL" ]
null
null
null
server/mod/hvp/embed.css
mohitjangra6017/tx_data
8adcb777a0b5e18d2ac66ec6dffda11572a91fc8
[ "PostgreSQL" ]
null
null
null
server/mod/hvp/embed.css
mohitjangra6017/tx_data
8adcb777a0b5e18d2ac66ec6dffda11572a91fc8
[ "PostgreSQL" ]
null
null
null
body.h5p-embed { font-family: Sans-Serif; width: 100%; height: 100%; margin: 0; padding: 0; } body.h5p-embed.h5p-resizing { overflow: hidden; } body.h5p-embed .h5p-container { overflow: hidden; } body.h5p-embed .h5p-content { font-size: 16px; line-height: 1.5em; width: 100%; height: auto; } body.h5p-embed .h5p-fullscreen .h5p-content, body.h5p-embed .h5p-semi-fullscreen .h5p-content { height: 100%; } body.h5p-embed .clearer, body.h5p-embed #maincontent, body.h5p-embed #user-notifications { display: none; }
17.212121
50
0.649648
663c98d5d490d31eedc1cb7a82a2dd348974d23d
520
py
Python
chainercv/utils/image/write_image.py
souravsingh/chainercv
8f76510472bc95018c183e72f37bc6c34a89969c
[ "MIT" ]
1
2018-12-05T04:30:10.000Z
2018-12-05T04:30:10.000Z
chainercv/utils/image/write_image.py
souravsingh/chainercv
8f76510472bc95018c183e72f37bc6c34a89969c
[ "MIT" ]
null
null
null
chainercv/utils/image/write_image.py
souravsingh/chainercv
8f76510472bc95018c183e72f37bc6c34a89969c
[ "MIT" ]
2
2019-12-16T02:20:26.000Z
2022-01-17T02:00:49.000Z
import numpy as np from PIL import Image def write_image(img, path): """Save an image to a file. This function saves an image to given file. The image is in CHW format and the range of its value is :math:`[0, 255]`. Args: image (~numpy.ndarray): An image to be saved. path (string): The path of an image file. """ if img.shape[0] == 1: img = img[0] else: img = img.transpose((1, 2, 0)) img = Image.fromarray(img.astype(np.uint8)) img.save(path)
21.666667
78
0.598077
37565a7f1d222de3a8e9d4a6774be6611b720360
280
dart
Dart
lib/core/providers/home_settings_provider.dart
mataide/acs-nft-viewer
ba019986534e98d0ffc88b03ba4e09f4a60ede93
[ "Apache-2.0" ]
1
2022-02-16T04:02:03.000Z
2022-02-16T04:02:03.000Z
lib/core/providers/home_settings_provider.dart
mataide/acs-nft-viewer
ba019986534e98d0ffc88b03ba4e09f4a60ede93
[ "Apache-2.0" ]
null
null
null
lib/core/providers/home_settings_provider.dart
mataide/acs-nft-viewer
ba019986534e98d0ffc88b03ba4e09f4a60ede93
[ "Apache-2.0" ]
null
null
null
import 'package:faktura_nft_viewer/controllers/home/home_settings_controller.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; final homeSettingsProvider = StateNotifierProvider<HomeSettingsController, HomeSettingsState>( (ref) => HomeSettingsController(), );
46.666667
94
0.832143
1e6dabada7325790cf68629ba0c4a60e7ba82794
15,646
css
CSS
public/css/styles.min.css
pernalin/pernalin.github.io
5923616e40e389f11d4291c7f619dc7a624f93af
[ "MIT" ]
null
null
null
public/css/styles.min.css
pernalin/pernalin.github.io
5923616e40e389f11d4291c7f619dc7a624f93af
[ "MIT" ]
null
null
null
public/css/styles.min.css
pernalin/pernalin.github.io
5923616e40e389f11d4291c7f619dc7a624f93af
[ "MIT" ]
null
null
null
@font-face{font-family:'Modern-UI-Icons---Social';src:url('/public/fonts/Modern-UI-Icons---Social.eot');src:url('/public/fonts/Modern-UI-Icons---Social.eot?#iefix') format('embedded-opentype'),url('/public/fonts/Modern-UI-Icons---Social.woff') format('woff'),url('/public/fonts/Modern-UI-Icons---Social.ttf') format('truetype'),url('/public//Modern-UI-Icons---Social.svg#Modern-UI-Icons---Social') format('svg');font-weight:normal;font-style:normal}[data-icon]:before{font-family:'Modern-UI-Icons---Social';content:attr(data-icon);speak:none;font-weight:normal;font-variant:normal;text-transform:none;line-height:76px;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.icon-social-aim,.icon-social-aim-variant,.icon-social-amazon-appstore,.icon-social-amazon,.icon-social-android,.icon-social-apple,.icon-social-apple-mobileme,.icon-social-apple-appstore,.icon-social-appnet,.icon-social-artcom,.icon-social-arto,.icon-social-aws,.icon-social-baidu,.icon-social-basecamp,.icon-social-bebo,.icon-social-behance,.icon-social-blogger,.icon-social-cloudapp,.icon-social-coding4fun,.icon-social-deviantart,.icon-social-digg,.icon-social-digg-variant,.icon-social-disqus,.icon-social-dribbble,.icon-social-dropbox-download,.icon-social-dropbox,.icon-social-dropbox-upload,.icon-social-drupal,.icon-social-dnd,.icon-social-engadget,.icon-social-etsy,.icon-social-evernote,.icon-social-facebook-heartbreak,.icon-social-facebook-heart,.icon-social-facebook,.icon-social-facebook-variant,.icon-social-foursquare,.icon-social-gdgt,.icon-social-github-octocat-solid,.icon-social-github,.icon-social-google,.icon-social-google-plus,.icon-social-grooveshark,.icon-social-indiegogo,.icon-social-jira,.icon-social-kickstarter,.icon-social-lastfm,.icon-social-linkedin,.icon-social-linkedin-variant,.icon-social-microsoft,.icon-social-mono,.icon-social-openid,.icon-social-picasa,.icon-social-pinterest,.icon-social-playstation,.icon-social-rdio,.icon-social-reddit,.icon-social-sharethis,.icon-social-share-open,.icon-social-share,.icon-social-skype,.icon-social-slashdot,.icon-social-soundcloud,.icon-social-spotify,.icon-social-stackoverflow,.icon-social-theverge,.icon-social-twitter,.icon-social-twitter-retweet,.icon-social-tumblr,.icon-social-uservoice,.icon-social-vimeo,.icon-social-wikipedia,.icon-social-windows,.icon-social-wordpress,.icon-social-wordpress-variant,.icon-social-xbox,.icon-social-yahoo,.icon-social-ycombinator,.icon-social-yelp,.icon-social-youtube,.icon-social-youtube-play,.icon-social-zappos{font-family:'Modern-UI-Icons---Social';speak:none;font-size:50px;font-style:normal;font-weight:normal;font-variant:normal;text-transform:none;line-height:1;-webkit-font-smoothing:antialiased}.icon-social-aim:before{content:"\e000"}.icon-social-aim-variant:before{content:"\e001"}.icon-social-amazon-appstore:before{content:"\e002"}.icon-social-amazon:before{content:"\e003"}.icon-social-android:before{content:"\e004"}.icon-social-apple:before{content:"\e005"}.icon-social-apple-mobileme:before{content:"\e006"}.icon-social-apple-appstore:before{content:"\e007"}.icon-social-appnet:before{content:"\e008"}.icon-social-artcom:before{content:"\e009"}.icon-social-arto:before{content:"\e00a"}.icon-social-aws:before{content:"\e00b"}.icon-social-baidu:before{content:"\e00c"}.icon-social-basecamp:before{content:"\e00d"}.icon-social-bebo:before{content:"\e00e"}.icon-social-behance:before{content:"\e00f"}.icon-social-blogger:before{content:"\e010"}.icon-social-cloudapp:before{content:"\e011"}.icon-social-coding4fun:before{content:"\e013"}.icon-social-deviantart:before{content:"\e014"}.icon-social-digg:before{content:"\e015"}.icon-social-digg-variant:before{content:"\e016"}.icon-social-disqus:before{content:"\e017"}.icon-social-dribbble:before{content:"\e018"}.icon-social-dropbox-download:before{content:"\e019"}.icon-social-dropbox:before{content:"\e01a"}.icon-social-dropbox-upload:before{content:"\e01b"}.icon-social-drupal:before{content:"\e01c"}.icon-social-dnd:before{content:"\e01d"}.icon-social-engadget:before{content:"\e01e"}.icon-social-etsy:before{content:"\e01f"}.icon-social-evernote:before{content:"\e020"}.icon-social-facebook-heartbreak:before{content:"\e021"}.icon-social-facebook-heart:before{content:"\e022"}.icon-social-facebook:before{content:"\e023"}.icon-social-facebook-variant:before{content:"\e024"}.icon-social-foursquare:before{content:"\e025"}.icon-social-gdgt:before{content:"\e027"}.icon-social-github-octocat-solid:before{content:"\e028"}.icon-social-github:before{content:"\e029"}.icon-social-google:before{content:"\e02a"}.icon-social-google-plus:before{content:"\e02b"}.icon-social-grooveshark:before{content:"\e02c"}.icon-social-indiegogo:before{content:"\e02d"}.icon-social-jira:before{content:"\e02e"}.icon-social-kickstarter:before{content:"\e02f"}.icon-social-lastfm:before{content:"\e030"}.icon-social-linkedin:before{content:"\e031"}.icon-social-linkedin-variant:before{content:"\e032"}.icon-social-microsoft:before{content:"\e033"}.icon-social-mono:before{content:"\e034"}.icon-social-openid:before{content:"\e035"}.icon-social-picasa:before{content:"\e036"}.icon-social-pinterest:before{content:"\e037"}.icon-social-playstation:before{content:"\e038"}.icon-social-rdio:before{content:"\e039"}.icon-social-reddit:before{content:"\e03a"}.icon-social-sharethis:before{content:"\e03b"}.icon-social-share-open:before{content:"\e03c"}.icon-social-share:before{content:"\e03e"}.icon-social-skype:before{content:"\e03f"}.icon-social-slashdot:before{content:"\e040"}.icon-social-soundcloud:before{content:"\e041"}.icon-social-spotify:before{content:"\e042"}.icon-social-stackoverflow:before{content:"\e043"}.icon-social-theverge:before{content:"\e044"}.icon-social-twitter:before{content:"\e045"}.icon-social-twitter-retweet:before{content:"\e026"}.icon-social-tumblr:before{content:"\e046"}.icon-social-uservoice:before{content:"\e047"}.icon-social-vimeo:before{content:"\e048"}.icon-social-wikipedia:before{content:"\e049"}.icon-social-windows:before{content:"\e04a"}.icon-social-wordpress:before{content:"\e04b"}.icon-social-wordpress-variant:before{content:"\e012"}.icon-social-xbox:before{content:"\e04c"}.icon-social-yahoo:before{content:"\e04d"}.icon-social-ycombinator:before{content:"\e04e"}.icon-social-yelp:before{content:"\e04f"}.icon-social-youtube:before{content:"\e050"}.icon-social-youtube-play:before{content:"\e03d"}.icon-social-zappos:before{content:"\e051"}.feedback-input{background-color:#fbfbfb;border:1px solid #ccc;box-sizing:border-box;color:#3c3c3c;font-size:18px;font-weight:500;line-height:22px;padding:8px 8px 9px 8px;width:100%;-webkit-appearance:none;-webkit-border-radius:0}.feedback-input:focus{background:#fff;border:1px solid #3498db;color:#3498db}.input-prepend{font-size:0;margin-bottom:20px;white-space:nowrap}.input-addon{background-color:#eee;border:1px solid #ccc;border-radius:4px 0 0 4px;display:inline-block;font-size:18px;line-height:22px;margin-right:-1px;padding:8px 5px;text-align:center;text-shadow:0 1px 0 #fff}.v-align{vertical-align:top}textarea{height:150px;line-height:22px;resize:vertical;width:100%;-webkit-appearance:none;-webkit-border-radius:0}input:hover,textarea:hover,input:focus,textarea:focus{background-color:white}#button-blue{border:#fbfbfb solid 4px;cursor:pointer;background-color:#6a9fb5;color:white;font-size:22px;padding:12px;-webkit-transition:all .3s;-moz-transition:all .3s;transition:all .3s;font-weight:500;float:right;margin-right:-44px}#button-blue:hover{background-color:#3498db;color:#bbb}.submit:hover{color:#3498db}.submit:hover .ease{width:100%;background-color:white}@media only screen and (max-width:580px){#form-div{left:3%;margin-right:3%;width:88%;margin-left:0;padding-left:3%;padding-right:3%}}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html,body{margin:0;padding:0}html{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:16px;line-height:1.5}@media(min-width:38em){html{font-size:20px}}body{color:#515151;background-color:#fff;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}a{color:#268bd2;text-decoration:none}a strong{color:inherit}a:hover,a:focus{text-decoration:underline}h1,h2,h3,h4,h5,h6{margin-bottom:.5rem;font-weight:bold;line-height:1.25;color:#313131;text-rendering:optimizeLegibility}h1{font-size:2rem}h2{margin-top:1rem;font-size:1.5rem}h3{margin-top:1.5rem;font-size:1.25rem}h4,h5,h6{margin-top:1rem;font-size:1rem}p{margin-top:0;margin-bottom:1rem}strong{color:#303030}ul,ol,dl{margin-top:0;margin-bottom:1rem}dt{font-weight:bold}dd{margin-bottom:.5rem}hr{position:relative;margin:1.5rem 0;border:0;border-top:1px solid #eee;border-bottom:1px solid #fff}abbr{font-size:85%;font-weight:bold;color:#555;text-transform:uppercase}abbr[title]{cursor:help;border-bottom:1px dotted #e5e5e5}code,pre{font-family:Menlo,Monaco,"Courier New",monospace}code{padding:.25em .5em;font-size:85%;color:#bf616a;background-color:#f9f9f9;border-radius:3px}pre{display:block;margin-top:0;margin-bottom:1rem;padding:1rem;font-size:.8rem;line-height:1.4;white-space:pre;white-space:pre-wrap;word-break:break-all;word-wrap:break-word;background-color:#f9f9f9}pre code{padding:0;font-size:100%;color:inherit;background-color:transparent}.highlight{margin-bottom:1rem;border-radius:4px}.highlight pre{margin-bottom:0}.gist .gist-file{font-family:Menlo,Monaco,"Courier New",monospace !important}.gist .markdown-body{padding:15px}.gist pre{padding:0;background-color:transparent}.gist .gist-file .gist-data{font-size:.8rem !important;line-height:1.4}.gist code{padding:0;color:inherit;background-color:transparent;border-radius:0}blockquote{padding:.5rem 1rem;margin:.8rem 0;color:#7a7a7a;border-left:.25rem solid #e5e5e5}blockquote p:last-child{margin-bottom:0}@media(min-width:30em){blockquote{padding-right:5rem;padding-left:1.25rem}}img{display:block;max-width:100%;margin:0 0 1rem;border-radius:5px}table{margin-bottom:1rem;width:100%;border:1px solid #e5e5e5;border-collapse:collapse}td,th{padding:.25rem .5rem;border:1px solid #e5e5e5}tbody tr:nth-child(odd) td,tbody tr:nth-child(odd) th{background-color:#f9f9f9}.lead{font-size:1.25rem;font-weight:300}.message{margin-bottom:1rem;padding:1rem;color:#717171;background-color:#f9f9f9}.container{max-width:38rem;padding-left:1rem;padding-right:1rem;margin-left:auto;margin-right:auto}.masthead{padding-top:1rem;padding-bottom:1rem;margin-bottom:3rem}.masthead-title{margin-top:0;margin-bottom:0;color:#505050}.masthead-title a{color:#505050}.masthead-title small{font-size:75%;font-weight:400;color:silver;letter-spacing:0}.page,.post{margin-bottom:4em}.page-title,.post-title,.post-title a{color:#303030}.page-title,.post-title{margin-top:0}.post-date{display:block;margin-top:-.5rem;margin-bottom:1rem;color:#9a9a9a}.related{padding-top:2rem;padding-bottom:2rem;border-top:1px solid #eee}.related-posts{padding-left:0;list-style:none}.related-posts h3{margin-top:0}.related-posts li small{font-size:75%;color:#999}.related-posts li a:hover{color:#268bd2;text-decoration:none}.related-posts li a:hover small{color:inherit}.pagination{overflow:hidden;margin-left:-1rem;margin-right:-1rem;font-family:"PT Sans",Helvetica,Arial,sans-serif;color:#ccc;text-align:center}.pagination-item{display:block;padding:1rem;border:1px solid #eee}.pagination-item:first-child{margin-bottom:-1px}a.pagination-item:hover{background-color:#f5f5f5}@media(min-width:30em){.pagination{margin:3rem 0}.pagination-item{float:left;width:50%}.pagination-item:first-child{margin-bottom:0;border-top-left-radius:4px;border-bottom-left-radius:4px}.pagination-item:last-child{margin-left:-1px;border-top-right-radius:4px;border-bottom-right-radius:4px}}html{font-family:"PT Sans",Helvetica,Arial,sans-serif}@media(min-width:48em){html{font-size:16px}}@media(min-width:58em){html{font-size:20px}}.sidebar{text-align:center;padding:2rem 1rem;color:rgba(255,255,255,.5);background-color:#202020}@media(min-width:48em){.sidebar{position:fixed;top:0;left:0;bottom:0;width:18rem;text-align:left}}.sidebar a{color:#fff;padding:5px 0}.sidebar-about h1{color:#fff;margin-top:0;font-family:"Abril Fatface",serif;font-size:3.25rem}.sidebar-nav{margin-bottom:1rem}.sidebar-nav-item{display:block;line-height:1.75}a.sidebar-nav-item:hover,a.sidebar-nav-item:focus{text-decoration:underline}.sidebar-nav-item.active{font-weight:bold}@media(min-width:48em){.sidebar-sticky{position:absolute;right:1rem;bottom:1rem;left:1rem}}.content{padding-top:4rem;padding-bottom:4rem}@media(min-width:48em){.content{max-width:38rem;margin-left:20rem;margin-right:2rem}}@media(min-width:64em){.content{margin-left:22rem;margin-right:4rem}}@media(min-width:48em){.layout-reverse .sidebar{left:auto;right:0}.layout-reverse .content{margin-left:2rem;margin-right:20rem}}@media(min-width:64em){.layout-reverse .content{margin-left:4rem;margin-right:22rem}}.theme-base-08 .sidebar{background-color:#ac4142}.theme-base-08 .content a,.theme-base-08 .related-posts li a:hover{color:#ac4142}.theme-base-09 .sidebar{background-color:#d28445}.theme-base-09 .content a,.theme-base-09 .related-posts li a:hover{color:#d28445}.theme-base-0a .sidebar{background-color:#f4bf75}.theme-base-0a .content a,.theme-base-0a .related-posts li a:hover{color:#f4bf75}.theme-base-0b .sidebar{background-color:#90a959}.theme-base-0b .content a,.theme-base-0b .related-posts li a:hover{color:#90a959}.theme-base-0c .sidebar{background-color:#75b5aa}.theme-base-0c .content a,.theme-base-0c .related-posts li a:hover{color:#75b5aa}.theme-base-0d .sidebar{background-color:#6a9fb5}.theme-base-0d .content a,.theme-base-0d .related-posts li a:hover{color:#6a9fb5}.theme-base-0e .sidebar{background-color:#aa759f}.theme-base-0e .content a,.theme-base-0e .related-posts li a:hover{color:#aa759f}.theme-base-0f .sidebar{background-color:#8f5536}.theme-base-0f .content a,.theme-base-0f .related-posts li a:hover{color:#8f5536}.highlight .hll{background-color:#ffc}.highlight .c{color:#999}.highlight .err{color:#a00;background-color:#faa}.highlight .k{color:#069}.highlight .o{color:#555}.highlight .cm{color:#09f;font-style:italic}.highlight .cp{color:#099}.highlight .c1{color:#999}.highlight .cs{color:#999}.highlight .gd{background-color:#fcc;border:1px solid #c00}.highlight .ge{font-style:italic}.highlight .gr{color:red}.highlight .gh{color:#030}.highlight .gi{background-color:#cfc;border:1px solid #0c0}.highlight .go{color:#aaa}.highlight .gp{color:#009}.highlight .gu{color:#030}.highlight .gt{color:#9c6}.highlight .kc{color:#069}.highlight .kd{color:#069}.highlight .kn{color:#069}.highlight .kp{color:#069}.highlight .kr{color:#069}.highlight .kt{color:#078}.highlight .m{color:#f60}.highlight .s{color:#d44950}.highlight .na{color:#4f9fcf}.highlight .nb{color:#366}.highlight .nc{color:#0a8}.highlight .no{color:#360}.highlight .nd{color:#99f}.highlight .ni{color:#999}.highlight .ne{color:#c00}.highlight .nf{color:#c0f}.highlight .nl{color:#99f}.highlight .nn{color:#0cf}.highlight .nt{color:#2f6f9f}.highlight .nv{color:#033}.highlight .ow{color:#000}.highlight .w{color:#bbb}.highlight .mf{color:#f60}.highlight .mh{color:#f60}.highlight .mi{color:#f60}.highlight .mo{color:#f60}.highlight .sb{color:#c30}.highlight .sc{color:#c30}.highlight .sd{color:#c30;font-style:italic}.highlight .s2{color:#c30}.highlight .se{color:#c30}.highlight .sh{color:#c30}.highlight .si{color:#a00}.highlight .sx{color:#c30}.highlight .sr{color:#3aa}.highlight .s1{color:#c30}.highlight .ss{color:#fc3}.highlight .bp{color:#366}.highlight .vc{color:#033}.highlight .vg{color:#033}.highlight .vi{color:#033}.highlight .il{color:#f60}.css .o,.css .o+.nt,.css .nt+.nt{color:#999}
15,646
15,646
0.78397
3876ff8a17f98109597ff055c384182fa214aec8
2,001
php
PHP
routes/super/inventory.php
dev-project-info/e-grocery
7239ad3ea8fbeb28e570196039840c328405e8d2
[ "MIT" ]
null
null
null
routes/super/inventory.php
dev-project-info/e-grocery
7239ad3ea8fbeb28e570196039840c328405e8d2
[ "MIT" ]
null
null
null
routes/super/inventory.php
dev-project-info/e-grocery
7239ad3ea8fbeb28e570196039840c328405e8d2
[ "MIT" ]
null
null
null
<?php Route::get('inventory','InventoryController@inventoryIndex') ->name('inventory'); Route::get('create_inventory','InventoryController@createInventory') ->name('inventory_create'); Route::post('store_inventory','InventoryController@storeInventory') ->name('inventory_store'); Route::get('inventory_show{id}','InventoryController@showInventory') ->name('inventory_show'); Route::get('inventory_edit/{id}','InventoryController@editInventory') ->name('inventory_edit'); Route::put('inventory_update/{id}','InventoryController@updateInventory') ->name('inventory_update'); // ----------Bying Part---------- Route::get('buying_reports','InventoryController@buyingReports') ->name('buying_reports'); Route::post('buying_single_date','InventoryController@buyingSingleDate') ->name('buying_single_date'); Route::post('buying_date_wise','InventoryController@buyingDateWise') ->name('buying_date_wise'); Route::get('today_buying_report','InventoryController@todayBuyingReport') ->name('today_buying_report'); Route::get('weekly_buying_report','InventoryController@weeklyBuyingReport') ->name('weekly_buying_report'); Route::get('monthly_buying_report','InventoryController@monthlyBuyingReport') ->name('monthly_buying_report'); // ----------Selling Part ---------- Route::get('selling_reports','InventoryController@sellingReports') ->name('selling_reports'); Route::post('selling_single_date','InventoryController@sellingSingleDate') ->name('selling_single_date'); Route::post('selling_date_wise','InventoryController@sellingDateWise') ->name('selling_date_wise'); Route::get('today_selling_report','InventoryController@todaySellingReport') ->name('today_selling_report'); Route::get('weekly_selling_report','InventoryController@weeklySellingReport') ->name('weekly_selling_report'); Route::get('monthly_selling_report','InventoryController@monthlySellingReport') ->name('monthly_selling_report');
43.5
79
0.743628
c9819eeb703829d067a2fad0b60657a007600991
970
ts
TypeScript
src/fetchProvider.ts
shy2850/area
f837d7358c57a85ce629a6a14e1e0300b703abb7
[ "MIT" ]
null
null
null
src/fetchProvider.ts
shy2850/area
f837d7358c57a85ce629a6a14e1e0300b703abb7
[ "MIT" ]
null
null
null
src/fetchProvider.ts
shy2850/area
f837d7358c57a85ce629a6a14e1e0300b703abb7
[ "MIT" ]
1
2019-09-17T09:21:18.000Z
2019-09-17T09:21:18.000Z
import { getNode, TreeNode } from './MultiSelect' const CALLBACK_NAME = 'area-jsonp' let AreaTree: TreeNode[] = [] window[CALLBACK_NAME] = (paths: string[], children: TreeNode[]) => { if (!paths.length) { AreaTree = children } else { const node = getNode(AreaTree, paths) if (node) { node.children = children } else { throw new Error(`wrong Node:`) } } } export default (options: {base: string}) => (paths = [], callback = (tree: TreeNode[]) => {}) => { const node = getNode(AreaTree, paths) if (node && (!node.children || node.children.length != 0)) { return callback(AreaTree) } const script = document.createElement('script') script.addEventListener('load', e => { callback && callback(AreaTree) document.body.removeChild(script) }) script.src = `${options.base}${paths.concat('1.js').join('/')}` document.body.appendChild(script) }
31.290323
98
0.587629
dd983300a01b49a5a1f50c3900304ca1dd32a741
131
java
Java
CSC455-Game-Programming/ShootThemCircles/core/src/com/jeff/game/util/Function.java
jregistr/Academia
4a52c3e74c6a8451b557d0f8f2e08b682eae0760
[ "MIT" ]
null
null
null
CSC455-Game-Programming/ShootThemCircles/core/src/com/jeff/game/util/Function.java
jregistr/Academia
4a52c3e74c6a8451b557d0f8f2e08b682eae0760
[ "MIT" ]
null
null
null
CSC455-Game-Programming/ShootThemCircles/core/src/com/jeff/game/util/Function.java
jregistr/Academia
4a52c3e74c6a8451b557d0f8f2e08b682eae0760
[ "MIT" ]
null
null
null
package com.jeff.game.util; /** * Function class so not to use java 8 */ public interface Function<T,R> { R apply(T t); }
11.909091
38
0.633588
e2d559a3ca341530971501bcc976d147a40ae603
962
py
Python
tests/st/utils/network.py
PushkarJ/node
097d86c82a57b274a1a5d02de967cad4ee4c0efc
[ "Apache-2.0" ]
3,973
2015-07-29T21:13:46.000Z
2022-03-31T09:27:38.000Z
tests/st/utils/network.py
PushkarJ/node
097d86c82a57b274a1a5d02de967cad4ee4c0efc
[ "Apache-2.0" ]
4,584
2015-07-29T08:47:22.000Z
2022-03-31T22:54:26.000Z
tests/st/utils/network.py
PushkarJ/node
097d86c82a57b274a1a5d02de967cad4ee4c0efc
[ "Apache-2.0" ]
1,066
2015-07-30T06:29:18.000Z
2022-03-31T20:01:47.000Z
# Copyright (c) 2015-2016 Tigera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os logger = logging.getLogger(__name__) class DummyNetwork(object): def __init__(self, name): self.name = name self.network = name self.deleted = False def delete(self, host=None): pass def disconnect(self, host, container): pass def __str__(self): return self.name
31.032258
74
0.709979
a35f451e294bf98861d24e9dc337af6bbc73bb63
1,196
java
Java
src/main/java/com/kiddo/eshop/servlet3/MyWebInitializer.java
KiddoThe2B/shopfinder
41ae0ca132dbdedcbc26d9822a6edbbba11e6dcd
[ "MIT" ]
null
null
null
src/main/java/com/kiddo/eshop/servlet3/MyWebInitializer.java
KiddoThe2B/shopfinder
41ae0ca132dbdedcbc26d9822a6edbbba11e6dcd
[ "MIT" ]
null
null
null
src/main/java/com/kiddo/eshop/servlet3/MyWebInitializer.java
KiddoThe2B/shopfinder
41ae0ca132dbdedcbc26d9822a6edbbba11e6dcd
[ "MIT" ]
null
null
null
package com.kiddo.eshop.servlet3; import com.kiddo.eshop.config.SpringWebConfig; import com.kiddo.eshop.config.HibernateConfig; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.hibernate.Filter; import org.springframework.orm.hibernate3.support.OpenSessionInViewFilter; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getServletConfigClasses() { return new Class[] { SpringWebConfig.class, HibernateConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Class<?>[] getRootConfigClasses() { //return new Class[] { SpringWebConfig.class, HibernateConfig.class }; return null; } }
33.222222
100
0.804348
0ad7305941ef72266d69d81b559d1382cfabc2f0
292
cs
C#
Assets/_Project/Scripts/Game/Util/LoggerAsset.cs
chris-m-cann/LDJam48
e8683179d18c727fead5d842323dbde191c5f5ef
[ "MIT" ]
null
null
null
Assets/_Project/Scripts/Game/Util/LoggerAsset.cs
chris-m-cann/LDJam48
e8683179d18c727fead5d842323dbde191c5f5ef
[ "MIT" ]
null
null
null
Assets/_Project/Scripts/Game/Util/LoggerAsset.cs
chris-m-cann/LDJam48
e8683179d18c727fead5d842323dbde191c5f5ef
[ "MIT" ]
null
null
null
using UnityEngine; namespace Util { // simple logging SO to adding to unity event chains to check they are firing [CreateAssetMenu(menuName = "Custom/Logger")] public class LoggerAsset: ScriptableObject { public void Log(string message) => Debug.Log(message); } }
26.545455
81
0.69863
33e00e6bfceb01b1f02eb4f21adcef22a214f4f8
8,573
sql
SQL
e-filing.sql
ridosimbolon98/project-e-filing-menggunakan-framewaork-codeigniter
252e238026d31667aebd1872eb11c3ceb3dc1c1f
[ "MIT" ]
1
2021-09-13T07:31:32.000Z
2021-09-13T07:31:32.000Z
e-filing.sql
ridosimbolon98/project-e-filing-menggunakan-framewaork-codeigniter
252e238026d31667aebd1872eb11c3ceb3dc1c1f
[ "MIT" ]
null
null
null
e-filing.sql
ridosimbolon98/project-e-filing-menggunakan-framewaork-codeigniter
252e238026d31667aebd1872eb11c3ceb3dc1c1f
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: 01 Apr 2019 pada 09.16 -- Versi Server: 10.1.16-MariaDB -- PHP Version: 7.0.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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: `e-filing` -- -- -------------------------------------------------------- -- -- Struktur dari tabel `akun` -- CREATE TABLE `akun` ( `id` int(11) NOT NULL, `nama` varchar(100) NOT NULL, `username` varchar(100) NOT NULL, `password` varchar(500) NOT NULL, `level` varchar(20) NOT NULL, `kategori` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `akun` -- INSERT INTO `akun` (`id`, `nama`, `username`, `password`, `level`, `kategori`) VALUES (1, 'Admin UP2TI', 'admin_up2ti', '21232f297a57a5a743894a0e4a801fc3', 'admin', 8), (2, 'Admin Informatika', 'admin_informatika', '21232f297a57a5a743894a0e4a801fc3', 'departemen', 6), (3, 'Admin Biologi', 'admin_biologi', '21232f297a57a5a743894a0e4a801fc3', 'departemen', 4), (4, 'Admin Fakultas', 'admin_fakultas', '21232f297a57a5a743894a0e4a801fc3', 'admin_fakultas', 7), (5, 'Admin Statistika', 'admin_statistika', '21232f297a57a5a743894a0e4a801fc3', 'departemen', 5), (6, 'Admin Matematika', 'admin_matematika', '21232f297a57a5a743894a0e4a801fc3', 'departemen', 1), (7, 'Admin Kimia', 'admin_kimia', '21232f297a57a5a743894a0e4a801fc3', 'departemen', 3), (8, 'Admin Fisika', 'admin_fisika', '21232f297a57a5a743894a0e4a801fc3', 'departemen', 2); -- -------------------------------------------------------- -- -- Struktur dari tabel `departemen` -- CREATE TABLE `departemen` ( `id_dep` int(11) NOT NULL, `departemen` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `departemen` -- INSERT INTO `departemen` (`id_dep`, `departemen`) VALUES (1, 'Matematika'), (2, 'Fisika'), (3, 'Kimia'), (4, 'Biologi'), (5, 'Statistika'), (6, 'Ilmu Komputer/Informatika'), (7, 'Admin Fakultas'), (8, 'Admin UP2TI'); -- -------------------------------------------------------- -- -- Struktur dari tabel `dokumen_nsk` -- CREATE TABLE `dokumen_nsk` ( `id` int(11) NOT NULL, `nama_nsk` varchar(250) NOT NULL, `judul` text NOT NULL, `ukuran_file` int(11) NOT NULL, `ekstensi` varchar(11) NOT NULL, `kategori` varchar(50) NOT NULL, `iddepartemen` int(11) NOT NULL, `tahun` year(4) NOT NULL, `date` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `dokumen_nsk` -- INSERT INTO `dokumen_nsk` (`id`, `nama_nsk`, `judul`, `ukuran_file`, `ekstensi`, `kategori`, `iddepartemen`, `tahun`, `date`) VALUES (3, 'BAB_7_Pengenalan_Prolog.pdf', 'File Daftar Matakuliah Terbaru', 10169495, 'pdf', 'akademik', 4, 2019, '2019-03-12'), (4, 'DecisionTree.pdf', 'File nilai mahasiswa', 285564, 'pdf', 'akademik', 4, 2018, '2018-10-16'), (5, '160119_3._Clustering.pdf', 'SK Mat1', 416918, 'pdf', 'akademik', 1, 2019, '2019-03-13'), (6, 'css_link3.html', 'SK KImia', 2196, 'html', 'akademik', 3, 2019, '2019-03-08'), (7, 'css_box3.html', 'SK Fisika', 1812, 'html', 'akademik', 2, 2019, '2019-03-05'), (8, '12-Eksepsi 2018_2.pdf', 'File Daftar Matakuliah Terbaru', 309399, 'pdf', 'akademik', 6, 2019, '2019-03-13'), (9, '9a.pdf', 'SK Ujian Akhir', 88753, 'pdf', 'akademik', 6, 2018, '2018-08-08'), (12, 'artikel stegano.pdf', 'File penting sekali bro', 637002, 'pdf', 'akademik', 2, 0000, '2019-03-14'), (14, 'Software Engineering - A Practitioner''s Approach (Eighth Edition).pdf', 'Sakit Smeua', 24046416, 'pdf', 'akademik', 6, 0000, '2017-03-12'); -- -------------------------------------------------------- -- -- Struktur dari tabel `dokumen_sk` -- CREATE TABLE `dokumen_sk` ( `id` int(11) NOT NULL, `no_sk` varchar(250) NOT NULL, `nama_sk` varchar(250) NOT NULL, `judul` text NOT NULL, `ukuran_file` int(20) NOT NULL, `ekstensi` varchar(20) NOT NULL, `kategori` varchar(50) NOT NULL, `iddepartemen` int(11) NOT NULL, `tahun` year(4) NOT NULL, `date` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `dokumen_sk` -- INSERT INTO `dokumen_sk` (`id`, `no_sk`, `nama_sk`, `judul`, `ukuran_file`, `ekstensi`, `kategori`, `iddepartemen`, `tahun`, `date`) VALUES (18, '001/SK/Mei/2019', 'DecisionTree.pdf', 'SK Pengangkatan Ketua Departemen', 285564, 'pdf', 'akademik', 6, 2019, '2019-03-13'), (22, '003/SK/Mei/2019', 'css_box.html', 'SK Pengukuhan HM', 1459, 'html', 'kemahasiswaan', 6, 2019, '2019-03-04'), (23, '002/SK/Mei/2019', 'css_table.html', 'SK Anggaran Belanja HM', 1001, 'html', 'keuangan', 6, 2018, '2018-07-11'), (25, '002/SK/Mei/2019', 'BAB_7_Pengenalan_Prolog.pdf', 'SK Pengangkatan Ketua Departemen', 10169495, 'pdf', 'akademik', 4, 2019, '2019-03-12'), (26, '006/SK/Mei/2019', 'Praktikum_2_PM.pdf', 'SK Lain', 330602, 'pdf', 'lain-lain', 6, 2018, '2018-08-07'), (27, '002/SK/Mei/2019', '117595_708-2194-1-PB.pdf', 'SK Statistka1', 407946, 'pdf', 'akademik', 5, 2019, '2019-03-13'), (28, '006/SK1/Mei/2019', 'Praktikum_2_PM-1.pdf', 'SK Stat2', 330602, 'pdf', 'akademik', 5, 2018, '2018-05-22'), (29, '005/SKM/Mei/2019', '2.2._Hierarchical-Clustering.pdf', 'SK mat2', 1027622, 'pdf', 'akademik', 1, 2019, '2019-03-06'), (30, '003/SKF/Mei/2019', '11c_form_validasi_Tugas_.html', 'SK MFK', 1914, 'html', 'akademik', 2, 2019, '2019-03-07'), (37, '004/SK/Mei/2019', '9a.pdf', 'sgdgfdg', 88753, 'pdf', 'akademik', 6, 2019, '2019-03-07'), (38, '003/SK/Mei/2019', 'hw9soln_06.pdf', 'sdfsdf', 108783, 'pdf', 'akademik', 6, 2018, '2018-10-09'), (39, '002/SK/Mei/2019', 'HW2-Solutions-2016-Spring.pdf', 'gjhggh', 247209, 'pdf', 'akademik', 6, 2019, '2019-03-05'), (44, '024/SK/Mei/2019', 'jadwal-wisuda-ke-150-undip.pdf', 'dgdfgdf', 816745, 'pdf', 'akademik', 6, 0000, '2019-03-20'), (45, '001/SK/Mei/20191', 'data_isiruang.txt', 'zxczxcz', 402, 'txt', 'akademik', 6, 0000, '2019-03-06'), (46, '004/SK/Mei/2019', 'artikel stegano.pdf', 'sas', 637002, 'pdf', 'akademik', 6, 0000, '2019-03-07'), (47, '004/SK/Mei/2019', 'Model Waterfall.docx', 'aaACA', 17030, 'docx', 'akademik', 6, 0000, '2019-03-21'), (48, '004/SK/Mei/2019', 'jadwal-wisuda-ke-150-undip-1.pdf', 'sass', 816745, 'pdf', 'akademik', 6, 0000, '2019-03-16'), (49, '006/SK/Mei/2019', '9a-1.pdf', 'zxczc', 88753, 'pdf', 'akademik', 6, 0000, '2019-03-02'), (51, '003/SK/Mei/2019', '01-Pengantar.pptx', 'scsc', 272728, 'pptx', 'akademik', 6, 0000, '2019-03-08'); -- -------------------------------------------------------- -- -- Struktur dari tabel `kategori_sk` -- CREATE TABLE `kategori_sk` ( `id` int(11) NOT NULL, `nama_kategori` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `kategori_sk` -- INSERT INTO `kategori_sk` (`id`, `nama_kategori`) VALUES (1, 'akademik'), (2, 'kemahasiswaan'), (3, 'keuangan'), (4, 'lain-lain'); -- -- Indexes for dumped tables -- -- -- Indexes for table `akun` -- ALTER TABLE `akun` ADD PRIMARY KEY (`id`); -- -- Indexes for table `departemen` -- ALTER TABLE `departemen` ADD PRIMARY KEY (`id_dep`); -- -- Indexes for table `dokumen_nsk` -- ALTER TABLE `dokumen_nsk` ADD PRIMARY KEY (`id`), ADD KEY `iddepartemen` (`iddepartemen`); -- -- Indexes for table `dokumen_sk` -- ALTER TABLE `dokumen_sk` ADD PRIMARY KEY (`id`), ADD KEY `iddepartemen` (`iddepartemen`); -- -- Indexes for table `kategori_sk` -- ALTER TABLE `kategori_sk` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `akun` -- ALTER TABLE `akun` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT for table `departemen` -- ALTER TABLE `departemen` MODIFY `id_dep` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT for table `dokumen_nsk` -- ALTER TABLE `dokumen_nsk` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; -- -- AUTO_INCREMENT for table `dokumen_sk` -- ALTER TABLE `dokumen_sk` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=52; -- -- AUTO_INCREMENT for table `kategori_sk` -- ALTER TABLE `kategori_sk` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; /*!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 */;
35.279835
146
0.648548
8eee9fc4406c3bd1e7f250574f3a42746f965d74
5,165
swift
Swift
AlertDemo/ViewController.swift
ByteSlinger/AlertDemo
7b4ca8b2b76138ddb37135050717eb4e4e7c2f0d
[ "MIT" ]
null
null
null
AlertDemo/ViewController.swift
ByteSlinger/AlertDemo
7b4ca8b2b76138ddb37135050717eb4e4e7c2f0d
[ "MIT" ]
1
2018-01-20T23:24:08.000Z
2018-01-20T23:29:08.000Z
AlertDemo/ViewController.swift
ByteSlinger/AlertDemo
7b4ca8b2b76138ddb37135050717eb4e4e7c2f0d
[ "MIT" ]
null
null
null
// // ViewController.swift // AlertDemo - Display and dismiss UIAlertControllers with UIControl (no action buttons) // (similar to Toast on Android OS) // // 4 different ways to close a UIAlertController popup window: // // 1) Timeout - dismiss an Alert Window after a number of seconds (like Android Toast) // 2) Tap outside the Alert Window (tap on Alert Window DOES NOT close it) // 3) Tap the Alert Window (tap anywhere else DOES NOT close it) // 4) Tap anywhere on the screen (on Alert Window or outside of it) to close it // // Created by ByteSlinger on 2018-01-19. // Copyright © 2018 ByteSlinger. All rights reserved. // import UIKit class ViewController: UIViewController { let alertController = UIAlertController(title: "Alert", message: "SO Awesome!", preferredStyle: .alert) let timeoutController = UIAlertController(title: "Timeout", message: "That Alert timed out!", preferredStyle: .actionSheet) let dismissControl = UIControl() @IBOutlet var alertButton1: UIButton! @IBOutlet var alertButton2: UIButton! @IBOutlet var alertButton3: UIButton! @IBOutlet var alertButton4: UIButton! // display a modal popup in the middle, tap outside popup to close @IBAction func displayAlert1(_ sender: UIButton) { alertController.message = "You must wait for this Alert to timeout" self.present(alertController, animated: true, completion: { self.perform(#selector(self.timeoutAlert), with: self.alertController, afterDelay: 3) }) } // display a modal popup in the middle, tap outside popup to close @IBAction func displayAlert2(_ sender: UIButton) { alertController.message = "Tap outside this Alert to close" self.present(alertController, animated: true, completion: { self.dismissControl.frame = self.alertController.view.superview?.bounds ?? CGRect.zero self.alertController.view.superview?.insertSubview(self.dismissControl, belowSubview: self.alertController.view) self.perform(#selector(self.timeoutAlert), with: self.alertController, afterDelay: 3) }) } // display a modal popup in the middle, tap on or outside popup to close @IBAction func displayAlert3(_ sender: UIButton) { alertController.message = "Tap anywhere to close" self.present(alertController, animated: true, completion: { self.dismissControl.frame = self.alertController.view.superview?.bounds ?? CGRect.zero self.alertController.view.superview?.addSubview(self.dismissControl) self.perform(#selector(self.timeoutAlert), with: self.alertController, afterDelay: 3) }) } // display a modal popup in the middle, tap on popup to close @IBAction func displayAlert4(_ sender: UIButton) { alertController.message = "Tap on this Alert to close" self.present(alertController, animated: true, completion: { // important - use bounds: alertController.view.frame WILL NOT WORK self.dismissControl.frame = self.alertController.view.bounds self.alertController.view.addSubview(self.dismissControl) self.perform(#selector(self.timeoutAlert), with: self.alertController, afterDelay: 3) }) } // close the current alert popup (middle) and display the timeout alert (bottom) @objc func timeoutAlert(_ alertController: UIAlertController) { if (alertController == UIApplication.shared.keyWindow?.rootViewController?.presentedViewController) { timeoutController.message = alertController.message! alertController.view.willRemoveSubview(self.dismissControl) alertController.dismiss(animated: true, completion: { self.present(self.timeoutController,animated: true, completion: { self.perform(#selector(self.dismissTimeout), with: self.timeoutController, afterDelay: 2) }) }) } } // dimiss (close) the alert popup @objc func dismissAlert() { // make sure there are no timeoutAlert calls waiting NSObject.cancelPreviousPerformRequests(withTarget: self) alertController.view.willRemoveSubview(self.dismissControl) alertController.dismiss(animated: true, completion: nil) } // dimiss (close) the timeout popup @objc func dismissTimeout(_ alert: UIAlertController) { alert.dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() // make the dismissControl execute dismissAlert for all touch events dismissControl.addTarget(self, action: #selector(self.dismissAlert), for: .allTouchEvents) // make the buttons a little prettier alertButton1.layer.cornerRadius = 32 alertButton2.layer.cornerRadius = 32 alertButton3.layer.cornerRadius = 32 alertButton4.layer.cornerRadius = 32 } }
41.99187
127
0.667764
46b0a9f70924da5a60b719bba641f474ac717ba7
588
sql
SQL
openGaussBase/testcase/KEYWORDS/parameter_specific_catalog/Opengauss_Function_Keyword_Parameter_specific_catalog_Case0026.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/KEYWORDS/parameter_specific_catalog/Opengauss_Function_Keyword_Parameter_specific_catalog_Case0026.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/KEYWORDS/parameter_specific_catalog/Opengauss_Function_Keyword_Parameter_specific_catalog_Case0026.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
-- @testpoint:opengauss关键字parameter_specific_catalog(非保留),作为模式名 --关键字不带引号-成功 drop schema if exists parameter_specific_catalog; create schema parameter_specific_catalog; drop schema parameter_specific_catalog; --关键字带双引号-成功 drop schema if exists "parameter_specific_catalog"; create schema "parameter_specific_catalog"; drop schema "parameter_specific_catalog"; --关键字带单引号-合理报错 drop schema if exists 'parameter_specific_catalog'; create schema 'parameter_specific_catalog'; --关键字带反引号-合理报错 drop schema if exists `parameter_specific_catalog`; create schema `parameter_specific_catalog`;
28
64
0.841837
5ac3e2a60b6fe844b89246e4eda72f1926d9374c
282
sql
SQL
li.strolch.persistence.postgresql/src/main/resources/strolch_db_schema_0.3.0_migration.sql
strolch-li/strolch
f5a33ea8b2106cf4d2410ab59cf459de8b93cf37
[ "Apache-2.0" ]
3
2021-07-15T07:48:06.000Z
2022-01-06T11:30:17.000Z
li.strolch.persistence.postgresql/src/main/resources/strolch_db_schema_0.3.0_migration.sql
4treesCH/strolch
74cddd997d92c9cc9a97daaa468f7c7e11b4a9bc
[ "Apache-2.0" ]
6
2017-02-23T12:38:01.000Z
2020-09-29T09:02:02.000Z
li.strolch.persistence.postgresql/src/main/resources/strolch_db_schema_0.3.0_migration.sql
4treesCH/strolch
74cddd997d92c9cc9a97daaa468f7c7e11b4a9bc
[ "Apache-2.0" ]
5
2017-02-20T12:18:03.000Z
2019-12-14T14:03:15.000Z
-- DB_VERSION ALTER TABLE audits ADD COLUMN element_sub_type character varying(255) NOT NULL DEFAULT '-'; INSERT INTO db_version (version, app, description, created) values( '0.3.0', 'strolch', 'Added new column element_sub_type to table audits', CURRENT_TIMESTAMP );
21.692308
91
0.737589
e56c9f28ddbd5f7bbfe15b1d584e0a1bc6642ed7
323
dart
Dart
lib/bitbucket_code_coverage.dart
arturdm/bitbucket_code_coverage
b3aded230215332d070549e264cd3a640aa3c61f
[ "Apache-2.0" ]
3
2019-06-02T14:43:42.000Z
2020-10-07T08:52:52.000Z
lib/bitbucket_code_coverage.dart
arturdm/bitbucket_code_coverage
b3aded230215332d070549e264cd3a640aa3c61f
[ "Apache-2.0" ]
6
2019-03-04T01:26:03.000Z
2020-10-06T16:02:18.000Z
lib/bitbucket_code_coverage.dart
arturdm/bitbucket_code_coverage
b3aded230215332d070549e264cd3a640aa3c61f
[ "Apache-2.0" ]
1
2020-12-02T16:22:15.000Z
2020-12-02T16:22:15.000Z
export 'src/client/code_coverage_service.dart'; export 'src/client/coverage_converter/coverage_converter.dart'; export 'src/client/coverage_converter/lcov_coverage_converter.dart'; export 'src/client/model/commit_coverage.dart'; export 'src/client/model/coverage_string.dart'; export 'src/client/model/file_coverage.dart';
46.142857
68
0.835913
eb144cb6d418962a0ddafda387a8942b1600619b
6,882
swift
Swift
Sources/Compiler/Implementation/CompilerImpl+Call.swift
LiarPrincess/Violet
0a4268649b0eec3ab631d19015d7043394c6571e
[ "MIT" ]
null
null
null
Sources/Compiler/Implementation/CompilerImpl+Call.swift
LiarPrincess/Violet
0a4268649b0eec3ab631d19015d7043394c6571e
[ "MIT" ]
6
2021-10-14T15:55:16.000Z
2022-03-31T14:04:02.000Z
Sources/Compiler/Implementation/CompilerImpl+Call.swift
LiarPrincess/Violet
0a4268649b0eec3ab631d19015d7043394c6571e
[ "MIT" ]
null
null
null
import Foundation import VioletCore import VioletParser import VioletBytecode // In CPython: // Python -> compile.c // swiftlint:disable function_body_length // swiftlint:disable cyclomatic_complexity // cSpell:ignore ssize subkwargs extension CompilerImpl { /// compiler_call(struct compiler *c, expr_ty e) internal func visit(_ node: CallExpr) throws { if try self.emitOptimizedMethodCall(function: node.function, args: node.args, keywords: node.keywords, context: node.context) { return } try self.visit(node.function) try self.callHelper(args: node.args, keywords: node.keywords, context: node.context, alreadyPushedArgs: 0) } /// maybe_optimize_method_call(struct compiler *c, expr_ty e) private func emitOptimizedMethodCall(function: Expression, args: [Expression], keywords: [KeywordArgument], context: ExpressionContext) throws -> Bool { // Check if it is an method guard let method = function as? AttributeExpr, context == .load else { return false } // No keywords or varargs let hasVarargs = args.contains { $0 is StarredExpr } guard !hasVarargs && keywords.isEmpty else { return false } try self.visit(method.object) self.builder.appendLoadMethod(name: method.name) try self.visit(args) self.builder.appendCallMethod(argumentCount: args.count) return true } /// Shared code between `call` and `class`. /// /// ```c /// compiler_call_helper(struct compiler *c, /// int n, /* Args already pushed */ /// asdl_seq *args, /// asdl_seq *keywords) /// ``` internal func callHelper(args: [Expression], keywords: [KeywordArgument], context: ExpressionContext, alreadyPushedArgs: Int) throws { /// CPython: `nSeen` /// Packed -> transformed to Tuple (to handle `*`/`**`, if needed) var nArgNotPacked = alreadyPushedArgs /// Cpython: `nSubArgs` var nPackedArgs = 0 /// CPython: `nSubKwArgs` var nPackedKwargs = 0 for arg in args { if let star = arg as? StarredExpr { // If we've seen positional arguments, then pack them into a tuple. if nArgNotPacked > 0 { self.builder.appendBuildTuple(elementCount: nArgNotPacked) nArgNotPacked = 0 nPackedArgs += 1 } try self.visit(star.expression) nPackedArgs += 1 } else { try self.visit(arg) nArgNotPacked += 1 } } let hasDictionaryUnpack = keywords.contains { kwarg in switch kwarg.kind { case .named: return false case .dictionaryUnpack: return true } } if nPackedArgs > 0 || hasDictionaryUnpack { // Pack up any trailing positional arguments. if nArgNotPacked > 0 { self.builder.appendBuildTuple(elementCount: nArgNotPacked) nArgNotPacked = 0 nPackedArgs += 1 } assert(nArgNotPacked == 0, "We finished args, now kwargs with clean state") // If we ended up with more than one star arg, // we need to concatenate them into a single sequence. if nPackedArgs == 0 { // We don't have normal 'args', fake empty. self.builder.appendBuildTuple(elementCount: 0) } else if nPackedArgs == 1 { // Exactly as we need it } else { // nPackedArgs > 1 self.builder.appendBuildTupleUnpackWithCall(elementCount: nPackedArgs) } for (index, keyword) in keywords.enumerated() { switch keyword.kind { case .dictionaryUnpack: if nArgNotPacked > 0 { let start = index - nArgNotPacked try self.visitKwargs(keywords: keywords[start..<index]) nPackedKwargs += 1 nArgNotPacked = 0 } try self.visit(keyword.value) nPackedKwargs += 1 case .named: nArgNotPacked += 1 } } // Pack up any trailing keyword arguments. if nArgNotPacked > 0 { let start = keywords.count - nArgNotPacked try self.visitKwargs(keywords: keywords[start..<keywords.count]) nPackedKwargs += 1 } if nPackedKwargs > 1 { self.builder.appendBuildMapUnpackWithCall(elementCount: nPackedKwargs) } self.builder.appendCallFunctionEx(hasKeywordArguments: nPackedKwargs > 0) } else if keywords.any { // All of the 'keywords' are 'named' (no 'dictionaryUnpack') let names = self.getNames(keywords: keywords) let argCount = alreadyPushedArgs + args.count + keywords.count try self.visitKeywords(keywords: keywords) self.builder.appendTuple(names) self.builder.appendCallFunctionKw(argumentCount: argCount) } else { // Only args, no kwargs let argCount = alreadyPushedArgs + args.count self.builder.appendCallFunction(argumentCount: argCount) } } /// Precondition: 'hasDictionaryUnpack' = false private func getNames(keywords: [KeywordArgument]) -> [CodeObject.Constant] { var result = [CodeObject.Constant]() for keyword in keywords { switch keyword.kind { case .dictionaryUnpack: unreachable() case .named(let name): result.append(.string(name)) } } return result } /// compiler_visit_keyword(struct compiler *c, keyword_ty k) private func visitKeywords(keywords: [KeywordArgument]) throws { for keyword in keywords { try self.visit(keyword.value) } } /// compiler_subkwargs(struct compiler *c, asdl_seq *keywords, /// Py_ssize_t begin, Py_ssize_t end) private func visitKwargs(keywords: ArraySlice<KeywordArgument>) throws { assert(keywords.any) if keywords.count == 1 { // swiftlint:disable:next force_unwrapping let keyword = keywords.first! guard case let .named(name) = keyword.kind else { trap("[BUG] Compiler: visitKwargs should not be called for unpack.") } self.builder.appendString(name) try self.visit(keyword.value) self.builder.appendBuildMap(elementCount: 1) } else { var names = [CodeObject.Constant]() for keyword in keywords { guard case let .named(name) = keyword.kind else { trap("[BUG] Compiler: visitKwargs should not be called for unpack.") } try self.visit(keyword.value) names.append(.string(name)) } self.builder.appendTuple(names) self.builder.appendBuildConstKeyMap(elementCount: names.count) } } }
32.009302
83
0.609125
1453bd167b3ae061f91bca3e8cc4070975d57b7b
172
ts
TypeScript
src/lib/repository/operators/save/base/save-operators-type.ts
techmmunity/compassorm
d90a2fdc9a3a02169d802bb3baf0f61a9018aa60
[ "Apache-2.0" ]
11
2021-08-02T23:51:39.000Z
2021-08-17T18:41:36.000Z
src/lib/repository/operators/save/base/save-operators-type.ts
techmmunity-symbiosis/symbiosis
d9c9841fcacb98d81b7aced233a1355014bf002c
[ "Apache-2.0" ]
203
2021-11-18T12:33:05.000Z
2022-03-28T15:08:15.000Z
src/lib/repository/operators/save/base/save-operators-type.ts
techmmunity/symbiosis
d90a2fdc9a3a02169d802bb3baf0f61a9018aa60
[ "Apache-2.0" ]
null
null
null
/** * List of types that SaveOperator can be. */ export type SaveOperatorType = | "append" | "ifNotExists" | "max" | "min" | "minus" | "plus" | "pop" | "remove";
13.230769
42
0.575581
643fdd1b895e36b331549eb024cdf360905a38fa
2,651
py
Python
fastsrv/src/build-conf.py
lingluadmin/operwrt-fast-cli
8f7ad9f9138bea3fd89749aaff37f325ea0aa5a5
[ "Apache-2.0" ]
1
2018-03-08T08:14:08.000Z
2018-03-08T08:14:08.000Z
fastsrv/src/build-conf.py
lingluadmin/operwrt-fast-cli
8f7ad9f9138bea3fd89749aaff37f325ea0aa5a5
[ "Apache-2.0" ]
null
null
null
fastsrv/src/build-conf.py
lingluadmin/operwrt-fast-cli
8f7ad9f9138bea3fd89749aaff37f325ea0aa5a5
[ "Apache-2.0" ]
null
null
null
import yaml import socket import os import shutil import sys from jinja2 import Template CONFIG_FILE='/fastsrv/sites-config/sites-config.yaml' TEMPLATES_DIR='/fastsrv/templates' OUTPUT_DIR='/fastsrv/output' class AppConfigRender: def __init__(self, app, basic_data): self.app = app data = dict(basic_data) data['app'] = app self.data = data def __render_str(self, str): s = Template(str) val = s.render(self.data) return val def __render_template_file(self, template_file): if not os.path.isfile(template_file): return dir = os file = self.nginx_conf_dir + '/' + os.path.basename(template_file) print 'write to %s' % file with open(template_file, 'r') as f: patten = f.read() result = self.__render_str(patten) with open(file, 'w') as fw: fw.write(result) def __render_vars(self, config): vars = config['vars'] ''' for key, val in vars.items(): val = self.__render_str(val) vars[key] = val ''' data = self.data.copy() data.update(vars) self.data = data def __prepare_dir(self): dir = OUTPUT_DIR + '/' + self.app if not os.path.exists(dir): os.makedirs(dir) else: shutil.rmtree(dir) os.makedirs(dir) self.nginx_conf_dir = dir def render(self, config): self.__prepare_dir() self.__render_vars(config) for template_file in config['nginx-templates']: template_file = TEMPLATES_DIR + '/' + template_file template_file = self.__render_str(template_file) self.__render_template_file(template_file) class Updater: def prepare_basic_data(self): env = os.environ shutil.rmtree(OUTPUT_DIR, ignore_errors=True) # mix env data = {} data.update(env) self.basic_data = data def load_yaml(self, file): data = None with open(file, 'r') as f: data = yaml.load(f) return data def run(self): self.prepare_basic_data() yaml = self.load_yaml(CONFIG_FILE) app = 'all' if app in yaml: self.render_app(app, yaml[app]) elif app == 'all': for app_key, item in yaml.items(): self.render_app(app_key, yaml[app_key]) def render_app(self, app, config): render = AppConfigRender(app, self.basic_data) render.render(config) if __name__ == '__main__': updater = Updater() updater.run()
30.471264
74
0.580158
daa572678291f3425b14ae6eba5c85dae685ee30
289
php
PHP
install/include/version/2.0.5.php
Elshara/PHPFox-Legacy
df0cbf2be0b807d17f3c9fca8cde0ed03492e563
[ "MIT" ]
null
null
null
install/include/version/2.0.5.php
Elshara/PHPFox-Legacy
df0cbf2be0b807d17f3c9fca8cde0ed03492e563
[ "MIT" ]
null
null
null
install/include/version/2.0.5.php
Elshara/PHPFox-Legacy
df0cbf2be0b807d17f3c9fca8cde0ed03492e563
[ "MIT" ]
2
2017-04-27T02:27:28.000Z
2018-10-03T10:06:31.000Z
<?php $this->_db()->query('ALTER TABLE ' . Phpfox::getT('ad') . ' CHANGE ad_id ad_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT'); $this->_db()->delete(Phpfox::getT('component'), 'module_id = \'core\' AND component = \'guest\''); $this->_upgradeDatabase('2.0.5'); $bCompleted = true; ?>
28.9
122
0.643599
200e78dddfb6afdb1087411920738008a0205022
8,430
py
Python
py/tests/integration/test_unsigned_tx.py
AndyHongSir/epoch
3ac26ee08c12d5d923c88eb5db5479f3b9d9b294
[ "ISC" ]
null
null
null
py/tests/integration/test_unsigned_tx.py
AndyHongSir/epoch
3ac26ee08c12d5d923c88eb5db5479f3b9d9b294
[ "ISC" ]
null
null
null
py/tests/integration/test_unsigned_tx.py
AndyHongSir/epoch
3ac26ee08c12d5d923c88eb5db5479f3b9d9b294
[ "ISC" ]
null
null
null
# coding: utf-8 import tempfile import os import shutil import time from nose.tools import assert_equals, assert_not_equals, with_setup import common from waiting import wait from swagger_client.rest import ApiException from swagger_client.models.tx import Tx from swagger_client.models.spend_tx import SpendTx from swagger_client.models.contract_create_data import ContractCreateData from swagger_client.models.contract_call_data import ContractCallData from swagger_client.models.contract_call_input import ContractCallInput settings = common.test_settings(__name__.split(".")[-1]) def test_contract_create(): test_settings = settings["test_contract_create"] (root_dir, node, external_api, top) = setup_node_with_tokens(test_settings, "node") internal_api = common.internal_api(node) send_tokens_to_user("alice", test_settings, internal_api, external_api) encoded_tx = get_unsigned_contract_create(test_settings["alice"]["pubkey"], test_settings["create_contract"], external_api) print("Unsigned encoded transaction: " + encoded_tx) unsigned_tx = common.base58_decode(encoded_tx) unpacked_tx = common.unpack_tx(unsigned_tx) tx = common.parse_tx(unpacked_tx) print("Unsigned decoded transaction: " + str(tx)) # make sure same tx assert_equals(tx['type'], 'contract_create') assert_equals(tx['owner'], common.base58_decode(test_settings["alice"]["pubkey"])) assert_equals(tx['vm_version'], test_settings["create_contract"]["vm_version"]) assert_equals(tx['deposit'], test_settings["create_contract"]["deposit"]) assert_equals(tx['amount'], test_settings["create_contract"]["amount"]) assert_equals(tx['gas'], test_settings["create_contract"]["gas"]) assert_equals(tx['gas_price'], test_settings["create_contract"]["gas_price"]) assert_equals(tx['fee'], test_settings["create_contract"]["fee"]) code = bytearray.fromhex(test_settings["create_contract"]["code"][2:]) # without 0x assert_equals(tx['code'], code) call_data = bytearray.fromhex(test_settings["create_contract"]["call_data"][2:]) # without 0x assert_equals(tx['call_data'], call_data) signature = bytearray(list(map(int, test_settings["create_contract"]["signature"].split(",")))) signed = common.encode_signed_tx(unpacked_tx, [signature]) print("Signed transaction " + signed) alice_balance0 = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance tx_object = Tx(tx=signed) external_api.post_tx(tx_object) top = external_api.get_top() common.wait_until_height(external_api, top.height + 3) alice_balance = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance assert_equals(alice_balance0, alice_balance + test_settings["create_contract"]["fee"]) cleanup(node, root_dir) def test_contract_call(): test_settings = settings["test_contract_call"] create_settings = settings["test_contract_create"] (root_dir, node, external_api, top) = setup_node_with_tokens(test_settings, "node") internal_api = common.internal_api(node) send_tokens_to_user("alice", test_settings, internal_api, external_api) ## create contract encoded_tx = get_unsigned_contract_create(test_settings["alice"]["pubkey"], create_settings["create_contract"], external_api) unsigned_tx = common.base58_decode(encoded_tx) unpacked_tx = common.unpack_tx(unsigned_tx) signature = bytearray(list(map(int, create_settings["create_contract"]["signature"].split(",")))) signed = common.encode_signed_tx(unpacked_tx,[signature]) alice_balance0 = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance tx_object = Tx(tx=signed) external_api.post_tx(tx_object) top = external_api.get_top() common.wait_until_height(external_api, top.height + 3) alice_balance = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance # assert contract created: call_contract = test_settings["contract_call"] assert_equals(alice_balance0, alice_balance + create_settings["create_contract"]["fee"]) call_input = ContractCallInput("ring", create_settings["create_contract"]["code"],\ call_contract["data"]["function"],\ call_contract["data"]["argument"]) result = external_api.call_contract(call_input) contract_call_obj = ContractCallData( caller=test_settings["alice"]["pubkey"], contract=call_contract["contract"], vm_version=call_contract["vm_version"], fee=call_contract["fee"], amount=call_contract["amount"], gas=call_contract["gas"], gas_price=call_contract["gas_price"], call_data=result.out) call_tx_obj = external_api.post_contract_call(contract_call_obj) encoded_call_tx = call_tx_obj.tx print("Unsigned encoded transaction: " + encoded_call_tx) unsigned_call_tx = common.base58_decode(encoded_call_tx) unpacked_call_tx = common.unpack_tx(unsigned_call_tx) tx = common.parse_tx(unpacked_call_tx) print("Unsigned decoded transaction: " + str(tx)) signature = bytearray(list(map(int, test_settings["contract_call"]["signature"].split(",")))) signed = common.encode_signed_tx(unpacked_call_tx,[signature]) print("Signed transaction: " + signed) alice_balance0 = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance tx_object = Tx(tx=signed) external_api.post_tx(tx_object) top = external_api.get_top() common.wait_until_height(external_api, top.height + 3) alice_balance = common.get_account_balance(internal_api, pub_key=test_settings["alice"]["pubkey"]).balance print("BALANCE0 " + str(alice_balance0)) print("BALANCE " + str(alice_balance)) # assert contract created: assert_equals(alice_balance0, alice_balance + test_settings["contract_call"]["fee"]) cleanup(node, root_dir) def cleanup(node, root_dir): common.stop_node(node) shutil.rmtree(root_dir) def make_mining_config(root_dir, file_name): sys_config = os.path.join(root_dir, file_name) f = open(sys_config, "w") # if autostart is not true - there will be no miner conf ='[{aecore, [{autostart, true},' + \ ' {expected_mine_rate, 100},' + \ ' {aec_pow_cuckoo, {"mean16s-generic", "-t 5", 16}}]}].' f.write(conf) f.close() return sys_config def setup_node_with_tokens(test_settings, node_name): # prepare a dir to hold the configs and the keys root_dir = tempfile.mkdtemp() # setup the dir with Alice's node mining node = test_settings["nodes"][node_name] sys_config = make_mining_config(root_dir, "sys.config") common.start_node(node, sys_config) api = common.external_api(node) # populate the chain so Alice had mined some blocks and has tokens # to spend blocks_to_mine = test_settings["blocks_to_mine"] common.wait_until_height(api, blocks_to_mine) top = api.get_top() assert_equals(top.height >= blocks_to_mine, True) # Now the node has at least blocks_to_mine blocks mined by Alice return (root_dir, node, api, top) def send_tokens_to_user(user, test_settings, internal_api, external_api): spend_tx_obj = SpendTx( recipient_pubkey=test_settings[user]["pubkey"], amount=test_settings[user]["amount"], fee=test_settings[user]["amount"]) # populate Alice's account internal_api.post_spend_tx(spend_tx_obj) top = external_api.get_top() common.wait_until_height(external_api, top.height + 3) balance_obj = common.get_account_balance(internal_api, pub_key=test_settings[user]["pubkey"]) print(user.capitalize() + "'s balance is now " + str(balance_obj.balance)) def get_unsigned_contract_create(owner, contract, external_api): contract_create_data_obj = ContractCreateData( owner=owner, code=contract["code"], vm_version=contract["vm_version"], deposit=contract["deposit"], amount=contract["amount"], gas=contract["gas"], gas_price=contract["gas_price"], fee=contract["fee"], call_data=contract["call_data"]) tx_obj = external_api.post_contract_create(contract_create_data_obj) return tx_obj.tx
40.724638
129
0.722776
a371a321f83947087f91155e18a17b7605fdb7f8
5,130
java
Java
Projeto3/src/projeto3/GameView.java
LuisFLCCQ/base_cod_java
8a19086ab2e0c0e27f7f2a5dd616c0a49b40accb
[ "MIT" ]
1
2019-03-06T02:51:08.000Z
2019-03-06T02:51:08.000Z
Projeto3/src/projeto3/GameView.java
LuisFLCCQ/base_cod_java
8a19086ab2e0c0e27f7f2a5dd616c0a49b40accb
[ "MIT" ]
null
null
null
Projeto3/src/projeto3/GameView.java
LuisFLCCQ/base_cod_java
8a19086ab2e0c0e27f7f2a5dd616c0a49b40accb
[ "MIT" ]
2
2021-03-17T18:01:06.000Z
2021-12-08T15:10:17.000Z
package projeto3; import javafx.application.Application; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ToolBar; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; import javafx.scene.layout.RowConstraints; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class GameView extends Application { private GridPane grid; private Controller presenter = new Controller(); private Label currentPlayer; public static void main(String [] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { draw(primaryStage); } public void draw(Stage stage) throws Exception { final int rows = 10; final int columns = 10; final int connectWin = 4; presenter.attachView(this); presenter.pushGridValues(rows, columns); stage.setTitle("4 in a Row!" ); BorderPane borderPane = new BorderPane(); Button reset = new Button("reset"); presenter.enterPlayer("Yellow"); presenter.enterPlayer("Red"); currentPlayer = new Label("Current turn: " + presenter.getTurn()); ToolBar tb = new ToolBar(); borderPane.setTop(tb); tb.getItems().addAll(reset, currentPlayer); grid = new GridPane(); grid.getStyleClass().add("game-grid"); for (int i = 0; i < columns; i++) { ColumnConstraints column = new ColumnConstraints(10); grid.getColumnConstraints().add(column); } for (int i = 0; i < rows; i++) { RowConstraints row = new RowConstraints(10); grid.getRowConstraints().add(row); } for (int i = 0; i < columns; i++) { for (int j = 0; j < rows; j++) { Pane pane = new Pane(); pane.setMinSize(25, 25); pane.setOnMouseReleased(e -> { //pinta o círculo a cada clique presenter.updateModelGrid(GridPane.getColumnIndex(pane)); currentPlayer.setText( "Current turn: " + presenter.getTurn()); int playerWin = presenter.checkWin(connectWin); if(playerWin != 0) { Alert winAlert = new Alert(AlertType.INFORMATION); winAlert.setTitle("Game Over!"); winAlert.setHeaderText(null); if(playerWin == 1){ winAlert.setContentText("Yellow wins!"); }else{ winAlert.setContentText("Red wins!"); } winAlert.showAndWait(); try { draw(stage); } catch (Exception ex) { ex.printStackTrace(); } } }); pane.getStyleClass().add("game-grid-cell"); if (i == 0) { pane.getStyleClass().add("first-column"); } if (j == 0) { pane.getStyleClass().add("first-row"); } grid.add(pane, i, j); } } reset.setOnAction((ActionEvent event) -> { try { draw(stage); } catch (Exception e) { e.printStackTrace(); } }); borderPane.setCenter(grid); int sceneWidth, sceneHeight; sceneWidth = 420; sceneHeight = 450; Scene scene = new Scene(borderPane, sceneWidth, sceneHeight); scene.getStylesheets().add("projeto3/resources/game.css"); stage.setResizable(false); stage.setScene(scene); stage.show(); } private Node getNodeByRowColumnIndex(final int row, final int column, GridPane gridPane) { Node result = null; ObservableList<Node> childrens = gridPane.getChildren(); for (Node node : childrens) { if (GridPane.getRowIndex(node) == row && GridPane.getColumnIndex(node) == column) { result = node; break; } } return result; } public void paintCircle(int row, int column) { Circle rect = new Circle(12.5, 12.5, 12.5); if (presenter.getTurn().equals("Yellow")) rect.setFill(Color.YELLOW); else { rect.setFill(Color.RED); } presenter.changeTurn(); Pane p = (Pane) getNodeByRowColumnIndex(row, column, grid); p.getChildren().add(rect); } }
32.264151
95
0.537232
f4a67a7d9191fa0e20b4a92a370720bcf35902c5
6,775
tsx
TypeScript
client/src/CraftingProfits/RunResultDisplay.tsx
hschimke/WorldOfWarcraft_CraftingProfitCalculator
a179d2f0230aff3ffbefff99c7fca4915479cdfe
[ "MIT" ]
2
2021-09-10T03:28:12.000Z
2021-09-10T13:39:44.000Z
client/src/CraftingProfits/RunResultDisplay.tsx
hschimke/WorldOfWarcraft_CraftingProfitCalculator
a179d2f0230aff3ffbefff99c7fca4915479cdfe
[ "MIT" ]
null
null
null
client/src/CraftingProfits/RunResultDisplay.tsx
hschimke/WorldOfWarcraft_CraftingProfitCalculator
a179d2f0230aff3ffbefff99c7fca4915479cdfe
[ "MIT" ]
null
null
null
import { useState } from 'react'; import { textFriendlyOutputFormat } from '../Shared/text-output-helpers'; import './RunResultDisplay.css'; import { GoldFormatter, VendorItemPrice, AHItemPrice } from '../Shared/GoldFormatter'; import { ShoppingLists } from './ShoppingLists'; const hidden_recipe_listing_header = {}; const hidden_run_result_header = {}; export interface RecipeListingProps { recipe: OutputFormatObject["recipes"][number] } export interface RunResultItemProps{ raw_run: ServerRunResultReturn & ServerErrorReturn | ServerRunResultReturn | undefined, show_children?: boolean } export interface RunResultDisplayProps{ raw_run: ServerRunResultReturn & ServerErrorReturn | undefined, status: string, show_raw_result: boolean } function RecipeListing(props:RecipeListingProps) { const [child_visible, setChildVisibility] = useState(false); const toggleChildren : React.MouseEventHandler = (e) => { setChildVisibility(!child_visible); }; const show_ah_price = ((props.recipe.ah !== undefined) && (props.recipe.ah.sales > 0)); const show_parts = (props.recipe.parts !== undefined); const parent_styles = child_visible ? {} : hidden_recipe_listing_header; const child_addins = child_visible ? '' : ' HiddenChild'; return ( <div className="RecipeListing" style={parent_styles}> <div className="RecipeHeader"> <span className="RecipeBanner"> Recipe </span> <span className="RecipeHeaderDetails"> <span className="RecipeName"> {props.recipe.name} </span> <span className="RecipeRank"> {props.recipe.rank} </span> <span className="RecipeId"> ({props.recipe.id}) </span> </span> <span className="RecipeCost"> <GoldFormatter raw_price={props.recipe.high} /> / <GoldFormatter raw_price={props.recipe.low} /> / <GoldFormatter raw_price={props.recipe.average} /> </span> </div> {show_ah_price && <AHItemPrice ah={props.recipe.ah} />} <span className="RecipePartsBanner" onClick={toggleChildren}> {props.recipe.parts.length} Components </span> <div className={'HideableChild' + child_addins}> {show_parts && props.recipe.parts.map(part => { return <RunResultItem key={part.id} raw_run={part} show_children={false} />; }) } </div> </div> ); } function RunResultItem({ raw_run, show_children = true }: RunResultItemProps) { const [child_visibility, updateChildVisibility] = useState(show_children); if (raw_run === undefined) { return null; } const toggleChildren : React.MouseEventHandler = (e) => { updateChildVisibility(!child_visibility); }; let ah_addin = false; let vendor_addin = false; let recipes = false; let bonuses = false; let shopping = false; const output_data = raw_run; ah_addin = ((output_data.ah !== undefined) && (output_data.ah.sales > 0)); vendor_addin = (output_data.vendor > 0); recipes = (output_data.recipes !== undefined); bonuses = (output_data.bonus_prices !== undefined); shopping = ('shopping_lists' in output_data && Object.keys(output_data.shopping_lists).length > 0); const children_classes = child_visibility ? '' : ' HiddenChild'; const parent_styles = child_visibility ? {} : hidden_run_result_header; return ( <div className="RunResultItem"> <div className="RunResultItemRecipes" style={parent_styles}> <div className="RunResultItemRecipesHeader"> <span className="ItemBanner"> Item </span> <span className="ItemName"> {output_data.name} </span> <span className="ItemId"> ({output_data.id}) </span> <span className="Required"> Requires {output_data.required} </span> </div> {ah_addin && <AHItemPrice ah={output_data.ah} /> } {vendor_addin && <VendorItemPrice vendor={output_data.vendor} /> } <span className="ItemRecipesBanner" onClick={toggleChildren}> {output_data.recipes.length} Recipes </span> <div className={'RunResultItemRecipesChildren HideableChild' + children_classes}> {recipes && output_data.recipes.map(recipe => { return <RecipeListing key={recipe.id} recipe={recipe} /> }) } {bonuses && output_data.bonus_prices.map(bonus_price => { return ( <div className="Bonuses"> {output_data.name} ({output_data.id}) iLvl {bonus_price.level} <AHItemPrice ah={bonus_price.ah} /> </div> ); }) } </div> </div> {shopping && <ShoppingLists lists={output_data.shopping_lists} name={output_data.name} /> } </div> ); } function RunResultDisplay(props:RunResultDisplayProps) { const SHOW_RES = props.show_raw_result; let res; if (props.status === 'ready' && props.raw_run !== undefined) { res = textFriendlyOutputFormat(props.raw_run, 1); } return ( <div className="RunResultDisplay"> {props.status !== 'ready' && <div className="Status"> {props.status} </div> } {SHOW_RES && <div className="RawResult"> <pre> {res} </pre> </div> } <div className="WebResult"> <RunResultItem raw_run={props.raw_run} /> </div> </div> ); } export default RunResultDisplay;
37.225275
103
0.516458
729321551c65f2b831ce881b676c31b7291cc236
235
cs
C#
src/Service/Service.Core.DefinedTypes/Pkcs11UserType.cs
myNameIsAndrew00/Playground
c90238c1e6f8dae4a5a352742d9ee9075555e844
[ "MIT" ]
null
null
null
src/Service/Service.Core.DefinedTypes/Pkcs11UserType.cs
myNameIsAndrew00/Playground
c90238c1e6f8dae4a5a352742d9ee9075555e844
[ "MIT" ]
null
null
null
src/Service/Service.Core.DefinedTypes/Pkcs11UserType.cs
myNameIsAndrew00/Playground
c90238c1e6f8dae4a5a352742d9ee9075555e844
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Text; namespace Service.Core.DefinedTypes { public enum Pkcs11UserType : ulong { SecurityOfficer = 0, User = 1, ContextSpecific = 2 } }
16.785714
38
0.651064