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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20d9874a474e7025860488dc3bc574ab410afbed
| 245 |
css
|
CSS
|
src/components/dashboard/projects/ProjectList.css
|
afractal/Daze.Spa
|
97c299026a3a2897dee07d0c186c8c2d72669934
|
[
"MIT"
] | null | null | null |
src/components/dashboard/projects/ProjectList.css
|
afractal/Daze.Spa
|
97c299026a3a2897dee07d0c186c8c2d72669934
|
[
"MIT"
] | 39 |
2017-10-30T22:25:18.000Z
|
2019-09-10T18:11:16.000Z
|
src/components/dashboard/projects/ProjectList.css
|
afractal/Daze.Spa
|
97c299026a3a2897dee07d0c186c8c2d72669934
|
[
"MIT"
] | null | null | null |
.projects-section {
margin: 2em;
}
.project-list {
text-align: center;
cursor: default;
display: inline-flex;
flex-flow: column nowrap;
align-content: center;
align-items: flex-start;
justify-content: center;
}
| 16.333333 | 29 | 0.640816 |
e7790aa36a41901b74bb66a3634417b192fd8c92
| 1,039 |
js
|
JavaScript
|
src/index.js
|
simonma10/wow_react
|
126db1500b11e3ba5e80c5a78441b71fc4c82f88
|
[
"MIT"
] | null | null | null |
src/index.js
|
simonma10/wow_react
|
126db1500b11e3ba5e80c5a78441b71fc4c82f88
|
[
"MIT"
] | null | null | null |
src/index.js
|
simonma10/wow_react
|
126db1500b11e3ba5e80c5a78441b71fc4c82f88
|
[
"MIT"
] | null | null | null |
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import promise from 'redux-promise';
import reducers from './reducers/index';
import Header from "./components/header";
import ToonList from './components/toon_list';
import ToonDetail from './components/toon_detail';
import ToonNew from './components/toon_new';
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<div>
<Header/>
<Switch>
<Route path="/toons/new" component={ ToonNew } />
<Route path="/toons/:id" component={ ToonDetail } />
<Route path="/" component={ ToonList } />
</Switch>
</div>
</BrowserRouter>
</Provider>
, document.querySelector('.container'));
| 33.516129 | 72 | 0.647738 |
753ca75b22fd72039bd1853b056edc9396218818
| 1,416 |
c
|
C
|
dataset/Lab-7/3075/295396_correct.c
|
jyi/ITSP
|
0553f683f99403efb5ef440af826c1d229a52376
|
[
"MIT"
] | 18 |
2017-06-14T07:55:45.000Z
|
2022-03-24T09:32:43.000Z
|
dataset/Lab-7/3075/295396_correct.c
|
jyi/ITSP
|
0553f683f99403efb5ef440af826c1d229a52376
|
[
"MIT"
] | 2 |
2017-07-25T13:44:39.000Z
|
2018-03-16T06:43:40.000Z
|
dataset/Lab-7/3075/295396_correct.c
|
jyi/ITSP
|
0553f683f99403efb5ef440af826c1d229a52376
|
[
"MIT"
] | 5 |
2017-07-29T19:09:37.000Z
|
2021-04-10T16:39:48.000Z
|
/*numPass=9, numTotal=9
Verdict:ACCEPTED, Visibility:1, Input:"abcdef
2", ExpOutput:"efabcd", Output:"efabcd"
Verdict:ACCEPTED, Visibility:1, Input:"programming
11", ExpOutput:"programming", Output:"programming"
Verdict:ACCEPTED, Visibility:1, Input:"hello-@programmer
5", ExpOutput:"ammerhello-@progr", Output:"ammerhello-@progr"
Verdict:ACCEPTED, Visibility:0, Input:"hellodear
3", ExpOutput:"earhellod", Output:"earhellod"
Verdict:ACCEPTED, Visibility:0, Input:"progamming
0", ExpOutput:"progamming", Output:"progamming"
Verdict:ACCEPTED, Visibility:0, Input:"programming
10", ExpOutput:"rogrammingp", Output:"rogrammingp"
Verdict:ACCEPTED, Visibility:0, Input:"programming
13", ExpOutput:"ngprogrammi", Output:"ngprogrammi"
Verdict:ACCEPTED, Visibility:0, Input:"abcde
4", ExpOutput:"bcdea", Output:"bcdea"
Verdict:ACCEPTED, Visibility:0, Input:"abcdz
5", ExpOutput:"abcdz", Output:"abcdz"
*/
#include <stdio.h>
void right_rotate(char s[],int);
int main() {
char str[101];
int n;
scanf("%s%d",str,&n);
right_rotate(str,n);
printf("%s",str);
return 0;
}
void right_rotate(char str[],int n)
{
char str1[101];
int len=0;
while(str[len]!='\0')
{
len++;
}
int i,j;
for(i=0;i<len;++i)
{
if(i+n>=len)
j=(i+n)%len;
else
j=i+n;
str1[j]=str[i];
}
for(i=0;i<len;i++)
str[i]=str1[i];
}
| 26.222222 | 61 | 0.647599 |
9c28610f65db30c04900032be46a50d26e7d9f3a
| 1,918 |
js
|
JavaScript
|
keywordTool/pubfiles/src/code/sphnews/128804/default.js
|
dsofowote/KW-Tool
|
d8d9a5a6f79c33732f0301b7c72ec21d1df4d750
|
[
"MIT"
] | null | null | null |
keywordTool/pubfiles/src/code/sphnews/128804/default.js
|
dsofowote/KW-Tool
|
d8d9a5a6f79c33732f0301b7c72ec21d1df4d750
|
[
"MIT"
] | null | null | null |
keywordTool/pubfiles/src/code/sphnews/128804/default.js
|
dsofowote/KW-Tool
|
d8d9a5a6f79c33732f0301b7c72ec21d1df4d750
|
[
"MIT"
] | null | null | null |
integration.meta = {
'sectionID' : '128804',
'siteName' : 'The Business Times - Tablet - (SG)',
'platform' : 'tablet'
};
integration.testParams = {
};
integration.flaggedTests = [];
integration.params = {
'mf_siteId' : '1035569',
'plr_PageAlignment' : 'center',
'plr_ContentW' : 1200,
'plr_ContentType' : 'PAGESKINEXPRESS',
'plr_UseFullVersion' : true,
'plr_UseCreativeSettings' : true,
'plr_HideElementsByID' : '',
'plr_HideElementsByClass' : ''
};
integration.on('adCallResult', function(e) {
if (e.data.hasSkin) {
var width = $(window).width();
var sideWidth = (width - 984) / 2;
/* content width divided by 2 */
$("#onesignal-bell-launcher, #backtotop").css({
"right" : sideWidth - 100
});
$("#block-dfp-lb1").css({"display": "none"});
$("head").append("<style>.group-image img, .foot-nav, .footer, .main-container, #navbar{width: 1200px !important; margin: 0 auto !important; box-shadow: none;}</style>");
$("head").append("<style>.master-header .top-first, .new-nav-bar, #searchbox, .new-nav-bar.lifestyle #menu, .new-nav-bar.lifestyle, .breadcrumb, .new-footer-wrapper .top-wrap, .social-icons-footer, .footer .copyright-text, .new-nav-bar #menu{box-shadow: none;}</style>");
$("head").append("<style> html {overflow-y: visible !important;}</style>");
if (e.data.productType == 'PageSkinEdgeTablet' || e.data.format == 'Pageskin Edge') {
/* Pageskin Edge specific changes */
integration.base.setCfg({
'plr_PageAlignment' : 'left'
});
$("head").append("<style>.group-image img, .foot-nav, .footer, .main-container, #navbar{margin: 0 !important; box-shadow: none;}</style>");
}
}
});
/* Passback Tag */
window.ISMPassback = function() {
return "<script src='https://www.googletagservices.com/tag/js/gpt.js'>\n googletag.pubads().definePassback('/5908/AdX_Leaderboard_Desktop_Passback', [[970, 250], [728, 90], [970, 90]]).display();\n<\\script>";
};
| 39.958333 | 273 | 0.660063 |
309043dda7df9cf431bc5e5b7325bfe5d9990ed6
| 657 |
html
|
HTML
|
templates/page/new_article.html
|
blackstorm/python3-tornado-blog
|
71198d37cb91ad07a7a7088e67d617d117361f54
|
[
"MIT"
] | 8 |
2016-11-04T09:03:42.000Z
|
2019-04-22T02:14:40.000Z
|
templates/page/new_article.html
|
blackstorm/python3-tornado-blog
|
71198d37cb91ad07a7a7088e67d617d117361f54
|
[
"MIT"
] | null | null | null |
templates/page/new_article.html
|
blackstorm/python3-tornado-blog
|
71198d37cb91ad07a7a7088e67d617d117361f54
|
[
"MIT"
] | 6 |
2016-06-13T00:11:51.000Z
|
2022-01-18T11:35:18.000Z
|
{% extends "../common/main.html" %}
{% block title %}
<title>发表文章</title>
{% end %}
{% block body %}
<table class="art">
<tbody>
<form action="/write" method="post">
<tr>
<td><input class="myTitle" type="text" name='title' placeholder="请输入标题"></td>
</tr>
<tr>
<td><textarea class='myContent' type='text' name="content"></textarea></td>
</tr>
<tr>
<td><input class='myUrl' type="text" name="url" placeholder="请输入Url"></td>
</tr>
<tr>
<td><input class="btn" type="submit" value="提交"></td>
</tr>
</form>
</tbody>
</table>
{% end %}
| 27.375 | 89 | 0.494673 |
287401f8cb0c098e08ebef1b45b9c6df311fe8d7
| 8,459 |
rb
|
Ruby
|
vgvm.rb
|
sonota88/vm2gol-v2
|
9323532d6e6ad63a42ce9a6bcc7a38207df8f2de
|
[
"MIT"
] | 9 |
2021-01-18T22:50:09.000Z
|
2022-01-11T10:25:31.000Z
|
vgvm.rb
|
sonota88/vm2gol-v2
|
9323532d6e6ad63a42ce9a6bcc7a38207df8f2de
|
[
"MIT"
] | null | null | null |
vgvm.rb
|
sonota88/vm2gol-v2
|
9323532d6e6ad63a42ce9a6bcc7a38207df8f2de
|
[
"MIT"
] | null | null | null |
require "json"
require_relative "./common"
module TermColor
RESET = "\e[m"
RED = "\e[0;31m"
BLUE = "\e[0;34m"
end
class Memory
attr_accessor :main, :stack, :vram
MAIN_DUMP_WIDTH = 10
def initialize(stack_size)
@main = []
# スタック領域
@stack = Array.new(stack_size, 0)
@vram = Array.new(50, 0)
end
def dump_main(pc)
work_insns = []
@main.each_with_index do |insn, i|
work_insns << { addr: i, insn: insn }
end
work_insns
.select do |work_insn|
pc - MAIN_DUMP_WIDTH <= work_insn[:addr] &&
work_insn[:addr] <= pc + MAIN_DUMP_WIDTH
end
.map do |work_insn|
head =
if work_insn[:addr] == pc
"pc =>"
else
" "
end
opcode = work_insn[:insn][0]
color =
case opcode
when "exit", "call", "ret", "jump", "jump_eq"
TermColor::RED
when "_cmt", "_debug"
TermColor::BLUE
else
""
end
indent =
if opcode == "label"
""
else
" "
end
format(
"%s %02d #{color}%s%s#{TermColor::RESET}",
head,
work_insn[:addr],
indent,
work_insn[:insn].inspect
)
end
.join("\n")
end
def dump_stack(sp, bp)
lines = []
@stack.each_with_index do |x, i|
addr = i
next if addr < sp - 8
next if addr > sp + 8
head =
case addr
when sp
if sp == bp
"sp bp => "
else
"sp => "
end
when bp
" bp => "
else
" "
end
lines << head + "#{addr} #{x.inspect}"
end
lines.join("\n")
end
def format_cols(cols)
cols.map { |col| col == 1 ? "@" : "." }.join("")
end
def dump_vram
rows = @vram.each_slice(5).to_a
main = rows[0..4]
buf = rows[5..9]
(0..4)
.map do |li| # line index
format_cols(main[li]) + " " + format_cols(buf[li])
end
.join("\n")
end
end
class Vm
FLAG_TRUE = 1
FLAG_FALSE = 0
def initialize(mem, stack_size)
@pc = 0 # program counter
# registers
@reg_a = 0
@reg_b = 0
@zf = FLAG_FALSE # zero flag
@mem = mem
@sp = stack_size - 1 # stack pointer
@bp = stack_size - 1 # base pointer
@step = 0
@debug = false
end
def test?
ENV.key?("TEST")
end
def set_sp(addr)
raise "Stack overflow" if addr < 0
@sp = addr
end
def load_program_file(path)
insns = File.open(path).each_line.map { |line| JSON.parse(line) }
load_program(insns)
end
def load_program(insns)
@mem.main = insns
end
def execute
insn = @mem.main[@pc]
opcode = insn[0]
case opcode
when "exit" then return true
when "cp" then cp() ; @pc += 1
when "add_ab" then add_ab() ; @pc += 1
when "mult_ab" then mult_ab() ; @pc += 1
when "add_sp" then add_sp() ; @pc += 1
when "sub_sp" then sub_sp() ; @pc += 1
when "compare" then compare() ; @pc += 1
when "label" then @pc += 1
when "jump" then jump()
when "jump_eq" then jump_eq()
when "call" then call()
when "ret" then ret()
when "push" then push() ; @pc += 1
when "pop" then pop() ; @pc += 1
when "set_vram" then set_vram() ; @pc += 1
when "get_vram" then get_vram() ; @pc += 1
when "_cmt" then @pc += 1
when "_debug" then _debug() ; @pc += 1
else
raise "Unknown opcode (#{opcode})"
end
false
end
def start
unless test?
dump() # 初期状態
puts "Press enter key to start"
$stdin.gets
end
loop do
@step += 1
do_exit = execute()
return if do_exit
unless test?
if ENV.key?("STEP") || @debug
dump()
$stdin.gets
else
dump() if @step % 10 == 0
end
end
end
end
def dump_reg
[
"reg_a(#{ @reg_a.inspect })",
"reg_b(#{ @reg_b.inspect })"
].join(" ")
end
def dump
puts <<~DUMP
================================
#{ @step }: #{ dump_reg() } zf(#{ @zf })
---- memory (main) ----
#{ @mem.dump_main(@pc) }
---- memory (stack) ----
#{ @mem.dump_stack(@sp, @bp) }
---- memory (vram) ----
#{ @mem.dump_vram() }
DUMP
end
def calc_indirect_addr(str)
_, base_str, disp_str = str.split(":")
base =
case base_str
when "bp"
@bp
else
raise not_yet_impl("base_str", base_str)
end
base + disp_str.to_i
end
def add_ab
@reg_a = @reg_a + @reg_b
end
def mult_ab
@reg_a = @reg_a * @reg_b
end
def cp
arg_src = @mem.main[@pc][1]
arg_dest = @mem.main[@pc][2]
src_val =
case arg_src
when Integer
arg_src
when "reg_a"
@reg_a
when "sp"
@sp
when "bp"
@bp
when /^ind:/
@mem.stack[calc_indirect_addr(arg_src)]
else
raise not_yet_impl("copy src", arg_src)
end
case arg_dest
when "reg_a"
@reg_a = src_val
when "reg_b"
@reg_b = src_val
when "bp"
@bp = src_val
when "sp"
set_sp(src_val)
when /^ind:/
@mem.stack[calc_indirect_addr(arg_dest)] = src_val
else
raise not_yet_impl("copy dest", arg_dest)
end
end
def add_sp
set_sp(@sp + @mem.main[@pc][1])
end
def sub_sp
set_sp(@sp - @mem.main[@pc][1])
end
def compare
@zf = (@reg_a == @reg_b) ? FLAG_TRUE : FLAG_FALSE
end
def jump
jump_dest = @mem.main[@pc][1]
@pc = jump_dest
end
def jump_eq
if @zf == FLAG_TRUE
jump_dest = @mem.main[@pc][1]
@pc = jump_dest
else
@pc += 1
end
end
def call
set_sp(@sp - 1) # スタックポインタを1減らす
@mem.stack[@sp] = @pc + 1 # 戻り先を記憶
next_addr = @mem.main[@pc][1] # ジャンプ先
@pc = next_addr
end
def ret
ret_addr = @mem.stack[@sp] # 戻り先アドレスを取得
@pc = ret_addr # 戻る
set_sp(@sp + 1) # スタックポインタを戻す
end
def push
arg = @mem.main[@pc][1]
val_to_push =
case arg
when Integer
arg
when String
case arg
when "reg_a"
@reg_a
when "bp"
@bp
when /^ind:/
stack_addr = calc_indirect_addr(arg)
@mem.stack[stack_addr]
else
raise not_yet_impl("push", arg)
end
else
raise not_yet_impl("push", arg)
end
set_sp(@sp - 1)
@mem.stack[@sp] = val_to_push
end
def pop
arg = @mem.main[@pc][1]
val = @mem.stack[@sp]
case arg
when "reg_a"
@reg_a = val
when "reg_b"
@reg_b = val
when "bp"
@bp = val
else
raise not_yet_impl("pop", arg)
end
set_sp(@sp + 1)
end
def set_vram
arg_vram = @mem.main[@pc][1]
arg_val = @mem.main[@pc][2]
src_val =
case arg_val
when Integer
arg_val
when "reg_a"
@reg_a
when /^ind:/
stack_addr = calc_indirect_addr(arg_val)
@mem.stack[stack_addr]
else
raise not_yet_impl("arg_val", arg_val)
end
case arg_vram
when Integer
@mem.vram[arg_vram] = src_val
when /^ind:/
stack_addr = calc_indirect_addr(arg_vram)
vram_addr = @mem.stack[stack_addr]
@mem.vram[vram_addr] = src_val
else
raise not_yet_impl("arg_vram", arg_vram)
end
end
def get_vram
arg_vram = @mem.main[@pc][1]
arg_dest = @mem.main[@pc][2]
vram_addr =
case arg_vram
when Integer
arg_vram
when String
case arg_vram
when /^ind:/
stack_addr = calc_indirect_addr(arg_vram)
@mem.stack[stack_addr]
else
raise not_yet_impl("arg_vram", arg_vram)
end
else
raise not_yet_impl("arg_vram", arg_vram)
end
val = @mem.vram[vram_addr]
case arg_dest
when "reg_a"
@reg_a = val
else
raise not_yet_impl("arg_dest", arg_dest)
end
end
def _debug
@debug = true
end
end
if $PROGRAM_NAME == __FILE__
exe_file = ARGV[0]
stack_size = 50
mem = Memory.new(stack_size)
vm = Vm.new(mem, stack_size)
vm.load_program_file(exe_file)
vm.start
vm.dump()
$stderr.puts "exit"
end
| 18.881696 | 69 | 0.506916 |
e15b7eb9099a761e2ac54aba5ed851cec854a407
| 75 |
tab
|
SQL
|
wordLists/wikt/wn-wikt-pav.tab
|
vatbub/auto-hotkey-noun-replacer
|
467c34292c1cc6465cb2d4003a91021b763b22d7
|
[
"Apache-2.0"
] | 3 |
2016-07-11T21:11:08.000Z
|
2016-10-04T01:27:06.000Z
|
wordLists/wikt/wn-wikt-pav.tab
|
vatbub/auto-hotkey-noun-replacer
|
467c34292c1cc6465cb2d4003a91021b763b22d7
|
[
"Apache-2.0"
] | 55 |
2016-06-24T00:14:38.000Z
|
2022-03-01T04:03:47.000Z
|
wordLists/wikt/wn-wikt-pav.tab
|
vatbub/auto-hotkey-noun-replacer
|
467c34292c1cc6465cb2d4003a91021b763b22d7
|
[
"Apache-2.0"
] | null | null | null |
# Wiktionary pav http://wiktionary.org/ CC BY-SA
02512053-n pav:lemma hwam
| 25 | 48 | 0.76 |
229cba16fcfae357646335daf3ae227f3a6dd61c
| 276 |
html
|
HTML
|
exercicios/ex007/html4.html
|
MuriWolf/html-css
|
35ef493e09f8a717869d4763b5f32403fd20d3cc
|
[
"MIT"
] | null | null | null |
exercicios/ex007/html4.html
|
MuriWolf/html-css
|
35ef493e09f8a717869d4763b5f32403fd20d3cc
|
[
"MIT"
] | null | null | null |
exercicios/ex007/html4.html
|
MuriWolf/html-css
|
35ef493e09f8a717869d4763b5f32403fd20d3cc
|
[
"MIT"
] | null | null | null |
<html>
<head>
<title>Meu site html4</title>
</head>
<body bgcolor="gray">
<h1>HTML4</h1>
Eu moro na <u>Rua Churusbango Churusbago, 1987 - Acre</u>
<marquee behavior="" direction="right">Teste de Marquee</marquee>
</body>
</html>
| 27.6 | 73 | 0.572464 |
4a30212f06c52a278d54bb3d71adec34ed1cf665
| 1,935 |
js
|
JavaScript
|
bin/redis-queue-worker.js
|
davidahouse/redis-queue
|
b672cadc7b3b0b3c957178bc05612ee5bd620893
|
[
"MIT"
] | null | null | null |
bin/redis-queue-worker.js
|
davidahouse/redis-queue
|
b672cadc7b3b0b3c957178bc05612ee5bd620893
|
[
"MIT"
] | 2 |
2019-03-24T17:36:45.000Z
|
2019-03-25T11:38:22.000Z
|
bin/redis-queue-worker.js
|
davidahouse/redis-queue-worker
|
b672cadc7b3b0b3c957178bc05612ee5bd620893
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env node
const chalk = require('chalk')
const clear = require('clear')
const figlet = require('figlet')
const redis = require('redis')
const conf = require('rc')('redisqueueworker', {
// defaults
sourceRedisHost: 'localhost',
sourceRedisPort: 6379,
sourceRedisPassword: null,
sourceQueueName: 'github',
targetRedisHost: 'localhost',
targetRedisPort: 6379,
targetRedisPassword: null,
targetQueueName: 'github'
})
let sourceClient = createRedisClient(conf.sourceRedisHost, conf.sourceRedisPort,
conf.sourceRedisPassword)
let targetClient = createRedisClient(conf.targetRedisHost, conf.targetRedisPort,
conf.targetRedisPassword)
sourceClient.on('error', function(err) {
console.log('source redis connect error: ' + err)
})
targetClient.on('error', function(err) {
console.log('target redis connect error: ' + err)
})
clear()
console.log(chalk.red(figlet.textSync('redisQworker', {horizontalLayout: 'full'})))
console.log(chalk.red('Source Redis Host: ' + conf.sourceRedisHost))
console.log(chalk.red('Source Redis Port: ' + conf.sourceRedisPort))
console.log(chalk.red('Target Redis Host: ' + conf.targetRedisHost))
console.log(chalk.red('Target Redis Port: ' + conf.targetRedisPort))
checkSourceQueue()
function checkSourceQueue() {
sourceClient.brpop(conf.sourceQueueName, 10, function(list, item) {
if (item != null) {
console.log(chalk.yellow('--> ' + conf.sourceQueueName))
targetClient.rpush(conf.targetQueueName, item[1])
}
process.nextTick(checkSourceQueue)
})
}
function createRedisClient(host, port, password) {
if (password != null) {
return redis.createClient({host: host,
port: port,
password: password})
} else {
return redis.createClient({host: host,
port: port})
}
}
| 32.25 | 83 | 0.663049 |
9b842d6b267b9285d71f0249fd0efbe8bb1aad0a
| 542 |
js
|
JavaScript
|
api/pmc.js
|
FahimEcho/Bubu
|
6cb05d4f464f47bc1b166a75c6e6d65ebecff8df
|
[
"MIT"
] | null | null | null |
api/pmc.js
|
FahimEcho/Bubu
|
6cb05d4f464f47bc1b166a75c6e6d65ebecff8df
|
[
"MIT"
] | 9 |
2020-07-19T18:22:55.000Z
|
2022-02-13T02:59:27.000Z
|
api/pmc.js
|
hubgit/bibu
|
76a9b0629d8c401a670d2778838af9311017d189
|
[
"MIT"
] | null | null | null |
const bibutils = require('bibutils.js')
const axios = require('axios')
module.exports = async (req, res) => {
const { toFormat = 'ris', id } = req.query
const response = await axios.get(
'https://api.ncbi.nlm.nih.gov/lit/ctxp/v1/pmc/',
{
params: {
format: 'ris',
id
} ,
headers: {
'User-Agent': 'bibu'
}
}
)
if (response && response.data) {
bibutils.convert('ris', toFormat, response.data, output => {
res.send(output)
})
} else {
res.send(500)
}
}
| 19.357143 | 64 | 0.5369 |
6b52d484f72d299ffa0f80dbe2a5dad34864b091
| 15,812 |
rs
|
Rust
|
bril-rs/src/lib.rs
|
femtomc/bril
|
51bb0c5a4d38787b12204882d3502c94e963103a
|
[
"MIT"
] | 1 |
2021-02-15T04:24:08.000Z
|
2021-02-15T04:24:08.000Z
|
bril-rs/src/lib.rs
|
femtomc/bril
|
51bb0c5a4d38787b12204882d3502c94e963103a
|
[
"MIT"
] | null | null | null |
bril-rs/src/lib.rs
|
femtomc/bril
|
51bb0c5a4d38787b12204882d3502c94e963103a
|
[
"MIT"
] | null | null | null |
use std::fmt::{self, Display, Formatter};
use std::io::{self, Write};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Program {
pub functions: Vec<Function>,
}
impl Display for Program {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
for func in self.functions.iter() {
writeln!(f, "{}", func)?;
}
Ok(())
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Function {
pub name: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub args: Vec<Argument>,
#[serde(rename = "type")]
#[serde(skip_serializing_if = "Option::is_none")]
pub return_type: Option<Type>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub instrs: Vec<Code>,
}
impl Display for Function {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "@{}(", self.name)?;
for (i, arg) in self.args.iter().enumerate() {
if i != 0 {
write!(f, ", ")?;
}
write!(f, "{}", arg)?;
}
write!(f, ")")?;
if let Some(tpe) = self.return_type.as_ref() {
write!(f, ": {}", tpe)?;
}
writeln!(f, " {{")?;
for instr in self.instrs.iter() {
writeln!(f, "{}", instr)?;
}
write!(f, "}}")?;
Ok(())
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Argument {
pub name: String,
#[serde(rename = "type")]
pub arg_type: Type,
}
impl Display for Argument {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.name, self.arg_type)
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(untagged)]
pub enum Code {
Label { label: String },
Instruction(Instruction),
}
impl Display for Code {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Code::Label { label } => write!(f, ".{}:", label),
Code::Instruction(instr) => write!(f, " {}", instr),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(untagged)]
pub enum Instruction {
Constant {
op: ConstOps,
dest: String,
#[serde(rename = "type")]
const_type: Type,
value: Literal,
},
Value {
op: ValueOps,
dest: String,
#[serde(rename = "type")]
op_type: Type,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
args: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
funcs: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
labels: Vec<String>,
},
Effect {
op: EffectOps,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
args: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
funcs: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
labels: Vec<String>,
},
}
impl Display for Instruction {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Instruction::Constant {
op,
dest,
const_type,
value,
} => {
write!(f, "{}: {} = {} {};", dest, const_type, op, value)
}
Instruction::Value {
op,
dest,
op_type,
args,
funcs,
labels,
} => {
write!(f, "{}: {} = {}", dest, op_type, op)?;
for func in funcs {
write!(f, " @{}", func)?;
}
for arg in args {
write!(f, " {}", arg)?;
}
for label in labels {
write!(f, " .{}", label)?;
}
write!(f, ";")
}
Instruction::Effect {
op,
args,
funcs,
labels,
} => {
write!(f, "{}", op)?;
for func in funcs {
write!(f, " @{}", func)?;
}
for arg in args {
write!(f, " {}", arg)?;
}
for label in labels {
write!(f, " .{}", label)?;
}
write!(f, ";")
}
}
}
}
#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum ConstOps {
#[serde(rename = "const")]
Const,
}
impl Display for ConstOps {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
ConstOps::Const => write!(f, "const"),
}
}
}
#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[serde(rename_all = "lowercase")]
pub enum EffectOps {
#[serde(rename = "jmp")]
Jump,
#[serde(rename = "br")]
Branch,
Call,
#[serde(rename = "ret")]
Return,
Print,
Nop,
#[cfg(feature = "memory")]
Store,
#[cfg(feature = "memory")]
Free,
#[cfg(feature = "speculate")]
Speculate,
#[cfg(feature = "speculate")]
Commit,
#[cfg(feature = "speculate")]
Guard,
}
impl Display for EffectOps {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
EffectOps::Jump => write!(f, "jmp"),
EffectOps::Branch => write!(f, "br"),
EffectOps::Call => write!(f, "call"),
EffectOps::Return => write!(f, "ret"),
EffectOps::Print => write!(f, "print"),
EffectOps::Nop => write!(f, "nop"),
#[cfg(feature = "memory")]
EffectOps::Store => write!(f, "store"),
#[cfg(feature = "memory")]
EffectOps::Free => write!(f, "free"),
#[cfg(feature = "speculate")]
EffectOps::Speculate => write!(f, "speculate"),
#[cfg(feature = "speculate")]
EffectOps::Commit => write!(f, "commit"),
#[cfg(feature = "speculate")]
EffectOps::Guard => write!(f, "guard"),
}
}
}
#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[serde(rename_all = "lowercase")]
pub enum ValueOps {
Add,
Sub,
Mul,
Div,
Eq,
Lt,
Gt,
Le,
Ge,
Not,
And,
Or,
Call,
Id,
#[cfg(feature = "ssa")]
Phi,
#[cfg(feature = "float")]
Fadd,
#[cfg(feature = "float")]
Fsub,
#[cfg(feature = "float")]
Fmul,
#[cfg(feature = "float")]
Fdiv,
#[cfg(feature = "float")]
Feq,
#[cfg(feature = "float")]
Flt,
#[cfg(feature = "float")]
Fgt,
#[cfg(feature = "float")]
Fle,
#[cfg(feature = "float")]
Fge,
#[cfg(feature = "memory")]
Alloc,
#[cfg(feature = "memory")]
Load,
#[cfg(feature = "memory")]
PtrAdd,
}
impl Display for ValueOps {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
ValueOps::Add => write!(f, "add"),
ValueOps::Sub => write!(f, "sub"),
ValueOps::Mul => write!(f, "mul"),
ValueOps::Div => write!(f, "div"),
ValueOps::Eq => write!(f, "eq"),
ValueOps::Lt => write!(f, "lt"),
ValueOps::Gt => write!(f, "gt"),
ValueOps::Le => write!(f, "le"),
ValueOps::Ge => write!(f, "ge"),
ValueOps::Not => write!(f, "not"),
ValueOps::And => write!(f, "and"),
ValueOps::Or => write!(f, "or"),
ValueOps::Call => write!(f, "call"),
ValueOps::Id => write!(f, "id"),
#[cfg(feature = "ssa")]
ValueOps::Phi => write!(f, "phi"),
#[cfg(feature = "float")]
ValueOps::Fadd => write!(f, "fadd"),
#[cfg(feature = "float")]
ValueOps::Fsub => write!(f, "fsub"),
#[cfg(feature = "float")]
ValueOps::Fmul => write!(f, "fmul"),
#[cfg(feature = "float")]
ValueOps::Fdiv => write!(f, "fdiv"),
#[cfg(feature = "float")]
ValueOps::Feq => write!(f, "feq"),
#[cfg(feature = "float")]
ValueOps::Flt => write!(f, "flt"),
#[cfg(feature = "float")]
ValueOps::Fgt => write!(f, "fgt"),
#[cfg(feature = "float")]
ValueOps::Fle => write!(f, "fle"),
#[cfg(feature = "float")]
ValueOps::Fge => write!(f, "fge"),
#[cfg(feature = "memory")]
ValueOps::Alloc => write!(f, "alloc"),
#[cfg(feature = "memory")]
ValueOps::Load => write!(f, "load"),
#[cfg(feature = "memory")]
ValueOps::PtrAdd => write!(f, "ptrAdd"),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
#[serde(rename_all = "lowercase")]
pub enum Type {
Int,
Bool,
#[cfg(feature = "float")]
Float,
#[cfg(feature = "memory")]
#[serde(rename = "ptr")]
Pointer(Box<Type>),
}
impl Display for Type {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Type::Int => write!(f, "int"),
Type::Bool => write!(f, "bool"),
#[cfg(feature = "float")]
Type::Float => write!(f, "float"),
#[cfg(feature = "memory")]
Type::Pointer(tpe) => write!(f, "ptr<{}>", tpe),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(untagged)]
pub enum Literal {
Int(i64),
Bool(bool),
#[cfg(feature = "float")]
Float(f64),
}
impl Display for Literal {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Literal::Int(i) => write!(f, "{}", i),
Literal::Bool(b) => write!(f, "{}", b),
#[cfg(feature = "float")]
Literal::Float(x) => write!(f, "{}", x),
}
}
}
impl Literal {
pub fn get_type(&self) -> Type {
match self {
Literal::Int(_) => Type::Int,
Literal::Bool(_) => Type::Bool,
#[cfg(feature = "float")]
Literal::Float(_) => Type::Float,
}
}
}
pub fn load_program_from_read<R: std::io::Read>(mut input: R) -> Program {
let mut buffer = String::new();
input.read_to_string(&mut buffer).unwrap();
serde_json::from_str(&buffer).unwrap()
}
pub fn load_program() -> Program {
load_program_from_read(std::io::stdin())
}
pub fn output_program(p: &Program) {
io::stdout()
.write_all(serde_json::to_string(p).unwrap().as_bytes())
.unwrap();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn full_program() {
let expected = "@main(cond: bool) {
a: bool = const true;
br cond .left .right;
.left:
c: int = add a b;
jmp .end;
.right:
jmp .end;
.end:
print d;
}
";
let program = Program {
functions: vec![Function {
name: "main".to_owned(),
args: vec![Argument {
name: "cond".to_owned(),
arg_type: Type::Bool,
}],
return_type: None,
instrs: vec![
Code::Instruction(Instruction::Constant {
op: ConstOps::Const,
dest: "a".to_owned(),
const_type: Type::Bool,
value: Literal::Bool(true),
}),
Code::Instruction(Instruction::Effect {
op: EffectOps::Branch,
args: vec!["cond".to_owned()],
funcs: vec![],
labels: vec!["left".to_owned(), "right".to_owned()],
}),
Code::Label {
label: "left".to_owned(),
},
Code::Instruction(Instruction::Value {
op: ValueOps::Add,
dest: "c".to_owned(),
op_type: Type::Int,
args: vec!["a".to_owned(), "b".to_owned()],
funcs: vec![],
labels: vec![],
}),
Code::Instruction(Instruction::Effect {
op: EffectOps::Jump,
args: vec![],
funcs: vec![],
labels: vec!["end".to_owned()],
}),
Code::Label {
label: "right".to_owned(),
},
Code::Instruction(Instruction::Effect {
op: EffectOps::Jump,
args: vec![],
funcs: vec![],
labels: vec!["end".to_owned()],
}),
Code::Label {
label: "end".to_owned(),
},
Code::Instruction(Instruction::Effect {
op: EffectOps::Print,
args: vec!["d".to_owned()],
funcs: vec![],
labels: vec![],
}),
],
}],
};
assert_eq!(expected, format!("{}", program));
}
#[test]
fn value_call() {
assert_eq!(
"mod: int = call @mod a b;",
format!(
"{}",
Instruction::Value {
op: ValueOps::Call,
dest: "mod".to_owned(),
op_type: Type::Int,
args: vec!["a".to_owned(), "b".to_owned()],
funcs: vec!["mod".to_owned()],
labels: vec![],
}
)
)
}
#[test]
fn effect_call() {
assert_eq!(
"call @callPrint v1;",
format!(
"{}",
Instruction::Effect {
op: EffectOps::Call,
args: vec!["v1".to_owned()],
funcs: vec!["callPrint".to_owned()],
labels: vec![],
}
)
)
}
#[test]
fn pointer() {
assert_eq!(
"myptr: ptr<int> = alloc ten;",
format!(
"{}",
Instruction::Value {
op: ValueOps::Alloc,
dest: "myptr".to_owned(),
op_type: Type::Pointer(Box::new(Type::Int)),
args: vec!["ten".to_owned()],
funcs: vec![],
labels: vec![],
}
)
)
}
#[test]
fn phi() {
assert_eq!(
"x: int = phi a b .here .there;",
format!(
"{}",
Instruction::Value {
op: ValueOps::Phi,
dest: "x".to_owned(),
op_type: Type::Int,
args: vec!["a".to_owned(), "b".to_owned()],
funcs: vec![],
labels: vec!["here".to_owned(), "there".to_owned()],
}
)
)
}
#[test]
fn speculation() {
assert_eq!(
"speculate;",
format!(
"{}",
Instruction::Effect {
op: EffectOps::Speculate,
args: vec![],
funcs: vec![],
labels: vec![],
}
)
)
}
}
| 28.235714 | 76 | 0.426195 |
50358040403f6a1725a127e427d22ad39a3a386a
| 608 |
go
|
Go
|
lib/dtos/github_commit.go
|
skeswa/gophr
|
e811c582b32b7fd3ec5915d1b91e28c81e47d8cd
|
[
"Apache-2.0"
] | 19 |
2016-03-12T19:47:43.000Z
|
2016-09-28T15:48:31.000Z
|
lib/dtos/github_commit.go
|
skeswa/gophr
|
e811c582b32b7fd3ec5915d1b91e28c81e47d8cd
|
[
"Apache-2.0"
] | 126 |
2016-03-29T18:28:12.000Z
|
2016-09-29T03:29:45.000Z
|
lib/dtos/github_commit.go
|
gophr-pm/gophr
|
e811c582b32b7fd3ec5915d1b91e28c81e47d8cd
|
[
"Apache-2.0"
] | 2 |
2016-11-01T03:04:07.000Z
|
2016-11-22T06:35:36.000Z
|
package dtos
import "time"
//go:generate ffjson $GOFILE
// GithubCommit is the response to a Github API commit detail request.
type GithubCommit struct {
SHA string `json:"sha"`
}
// GithubCommitLookUp is the response to a Github API commit detail request.
type GithubCommitLookUp struct {
Commit *GithubCommitDetail `json:"commit"`
}
// GithubCommitDetail is part of GithubCommitLookUp.
type GithubCommitDetail struct {
Committer *GithubCommitCommitter `json:"committer"`
}
// GithubCommitCommitter is part of GithubCommitDetail.
type GithubCommitCommitter struct {
Date time.Time `json:"date"`
}
| 23.384615 | 76 | 0.779605 |
21f1f3d8fd4f389d53110caa6d795484086370ad
| 103 |
html
|
HTML
|
docs/archive/documents/161.html
|
Basileus4/site
|
9af12c1c45b345e566fa900659506fc2e1f9e5c2
|
[
"Apache-2.0"
] | null | null | null |
docs/archive/documents/161.html
|
Basileus4/site
|
9af12c1c45b345e566fa900659506fc2e1f9e5c2
|
[
"Apache-2.0"
] | null | null | null |
docs/archive/documents/161.html
|
Basileus4/site
|
9af12c1c45b345e566fa900659506fc2e1f9e5c2
|
[
"Apache-2.0"
] | null | null | null |
---
layout: tei
tei: '../tei/161.xml'
facs: '../facs/161.html'
prev: '160'
self: '161'
next: '162'
---
| 11.444444 | 24 | 0.553398 |
3285c7bcf8a45e226a8861a3ccbc819526f84ad0
| 993 |
lua
|
Lua
|
test/tests/colonrange.lua
|
jugglerchris/textadept-vi
|
46eb2c6502df9a0166a4de2a8c14fca66b4a0220
|
[
"MIT"
] | 35 |
2015-02-06T01:48:41.000Z
|
2022-01-01T17:31:10.000Z
|
test/tests/colonrange.lua
|
jugglerchris/textadept-vi
|
46eb2c6502df9a0166a4de2a8c14fca66b4a0220
|
[
"MIT"
] | 31 |
2015-02-24T22:23:30.000Z
|
2020-12-11T22:50:45.000Z
|
test/tests/colonrange.lua
|
jugglerchris/textadept-vi
|
46eb2c6502df9a0166a4de2a8c14fca66b4a0220
|
[
"MIT"
] | 9 |
2015-06-21T11:51:17.000Z
|
2020-05-27T17:13:19.000Z
|
-- Check that running :commands works.
-- Add a dummy command
local assertEq = test.assertEq
local myvar = nil
local vi_mode = require 'textadept-vi.vi_mode'
local cmd_errors = {}
local function save_errors(f)
return function(...)
ok, err = pcall(f, ...)
if ok then return err end
cmd_errors[#cmd_errors+1] = err
end
end
vi_mode.ex_mode.add_ex_command('tester', save_errors(function(args, range)
assertEq(args, {'tester', 'arg1', 'arg2'})
assertEq(range, {1, 4})
myvar = range
end), nil) -- no completer
-- test.key doesn't currently work from the command entry, so we instead
-- need to use physkey, with one final key at the end (which will wait for
-- the keypress to have been handled).
test.keys(':1,4tester arg1 arg2')
test.key('enter')
assertEq(cmd_errors, {})
assertEq(myvar,{1,4})
-- remove the test command
assert(vi_mode.ex_mode.ex_commands['tester'])
vi_mode.ex_mode.ex_commands['tester'] = nil
| 29.205882 | 74 | 0.668681 |
5c76396750dd1efc593e3327d96f190c7f22c18d
| 289 |
h
|
C
|
RunTime/Six/RunTimeExample/RunTimeExample/Module/RunTime/Views/RunTimeCell.h
|
CainRun/iOS-Project-Example
|
a02b669a14b5ade94456924c41421d511ffd12f7
|
[
"MIT"
] | 10 |
2017-08-12T03:14:39.000Z
|
2017-11-26T04:08:22.000Z
|
RunTime/Five/RunTimeExample/RunTimeExample/Module/RunTime/Views/RunTimeCell.h
|
CainLuo/iOS-Project-Example
|
a02b669a14b5ade94456924c41421d511ffd12f7
|
[
"MIT"
] | 1 |
2017-08-16T03:36:28.000Z
|
2017-08-16T03:37:06.000Z
|
RunTime/Five/RunTimeExample/RunTimeExample/Module/RunTime/Views/RunTimeCell.h
|
CainLuo/iOS-Project-Example
|
a02b669a14b5ade94456924c41421d511ffd12f7
|
[
"MIT"
] | 6 |
2018-01-16T06:48:46.000Z
|
2021-11-11T03:37:28.000Z
|
//
// RunTimeCell.h
// RunTimeExample
//
// Created by Cain on 2017/9/26.
// Copyright © 2017年 Cain. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "RunTimeModel.h"
@interface RunTimeCell : UITableViewCell
- (void)cl_confgiRunTimeCellWithModel:(RunTimeModel *)model;
@end
| 17 | 60 | 0.716263 |
21d9807dea4a56c43f7241d8c80bc88e5da14f74
| 565 |
html
|
HTML
|
www/templates/tab-insert.html
|
raqystyle/kid-tracker-app
|
279e6acf1edaf8c92b47e7c31757abcfb1a38739
|
[
"MIT"
] | null | null | null |
www/templates/tab-insert.html
|
raqystyle/kid-tracker-app
|
279e6acf1edaf8c92b47e7c31757abcfb1a38739
|
[
"MIT"
] | null | null | null |
www/templates/tab-insert.html
|
raqystyle/kid-tracker-app
|
279e6acf1edaf8c92b47e7c31757abcfb1a38739
|
[
"MIT"
] | null | null | null |
<ion-view view-title="Add activity">
<ion-content class="padding">
<button ng-click="InsertC.addBreastFeeding()" class="button button-block button-positive">
Had breast
</button>
<button ng-click="InsertC.addFormula()" class="button button-block button-positive">
Ate formula
</button>
<button ng-click="InsertC.addPee()" class="button button-block button-positive">
Pee
</button>
<button ng-click="InsertC.addPoop()" class="button button-block button-positive">
Poop
</button>
</ion-content>
</ion-view>
| 33.235294 | 94 | 0.670796 |
5c892372dbaf3a6d0723f82a094a2eee24af9345
| 2,373 |
h
|
C
|
src/Generic/patterns/UnionPattern.h
|
BBN-E/serif
|
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
|
[
"Apache-2.0"
] | 1 |
2022-03-24T19:57:00.000Z
|
2022-03-24T19:57:00.000Z
|
src/Generic/patterns/UnionPattern.h
|
BBN-E/serif
|
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
|
[
"Apache-2.0"
] | null | null | null |
src/Generic/patterns/UnionPattern.h
|
BBN-E/serif
|
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (c) 2006 by BBNT Solutions LLC
// All Rights Reserved.
#ifndef UNION_PATTERN_H
#define UNION_PATTERN_H
#include "Generic/common/Symbol.h"
#include "Generic/patterns/Pattern.h"
#include "Generic/patterns/PatternTypes.h"
/** A sentence-matching pattern that will match a sentence iff any of its
* subpatterns matches the sentence. A UnionPattern can either be greedy,
* in which case the returned feature set will only contain the features
* from the first match; or non-greedy, in which case the returned feature
* set will contain features from all matches. (Note that greed does not
* affect *which* sentences get matched, but instead affect what gets
* returned. Greedy matching is faster, since it can return immediately
* as soon as one subpattern matches.)
*
* The multiMatchesSentence() method can currently only be used with greedy
* union patterns, and will always return either 0 or 1 feature sets.
*/
class UnionPattern : public LanguageVariantSwitchingPattern, public SentenceMatchingPattern
{
private:
UnionPattern(Sexp *sexp, const Symbol::HashSet &entityLabels, const PatternWordSetMap& wordSets);
BOOST_MAKE_SHARED_3ARG_CONSTRUCTOR(UnionPattern, Sexp*, const Symbol::HashSet&, const PatternWordSetMap&);
public:
~UnionPattern() {}
bool isGreedy() const { return _is_greedy; }
// Sentence-level matching
PatternFeatureSet_ptr matchesSentence(PatternMatcher_ptr patternMatcher, SentenceTheory *sTheory, UTF8OutputStream *debug = 0);
std::vector<PatternFeatureSet_ptr> multiMatchesSentence(PatternMatcher_ptr patternMatcher, SentenceTheory *sTheory, UTF8OutputStream *debug = 0);
// Overridden virtual methods:
virtual std::string typeName() const { return "UnionPattern"; }
virtual Pattern_ptr replaceShortcuts(const SymbolToPatternMap &refPatterns);
virtual void getReturns(PatternReturnVecSeq & output) const;
virtual void dump(std::ostream &out, int indent = 0) const;
virtual Symbol getFirstValidID() const;
private:
virtual bool initializeFromAtom(Sexp *childSexp, const Symbol::HashSet &entityLabels, const PatternWordSetMap& wordSets);
virtual bool initializeFromSubexpression(Sexp *childSexp, const Symbol::HashSet &entityLabels, const PatternWordSetMap& wordSets);
std::vector<Pattern_ptr> _patternList;
bool _is_greedy;
};
#endif
| 44.773585 | 147 | 0.770333 |
fbe07604ef5299ddd13b9220eaa963ba3d0046a9
| 873 |
asm
|
Assembly
|
sw/552tests/rand_simple/t_2_srli.asm
|
JPShen-UWM/ThreadKraken
|
849c510531f28e36d3469535737b2120bd774935
|
[
"MIT"
] | 1 |
2022-02-15T16:03:25.000Z
|
2022-02-15T16:03:25.000Z
|
sw/552tests/rand_simple/t_2_srli.asm
|
JPShen-UWM/ThreadKraken
|
849c510531f28e36d3469535737b2120bd774935
|
[
"MIT"
] | null | null | null |
sw/552tests/rand_simple/t_2_srli.asm
|
JPShen-UWM/ThreadKraken
|
849c510531f28e36d3469535737b2120bd774935
|
[
"MIT"
] | null | null | null |
// seed 2
lbi r0, 104 // icount 0
slbi r0, 209 // icount 1
lbi r1, 44 // icount 2
slbi r1, 82 // icount 3
lbi r2, 45 // icount 4
slbi r2, 104 // icount 5
lbi r3, 216 // icount 6
slbi r3, 122 // icount 7
lbi r4, 119 // icount 8
slbi r4, 97 // icount 9
lbi r5, 239 // icount 10
slbi r5, 62 // icount 11
lbi r6, 118 // icount 12
slbi r6, 238 // icount 13
lbi r7, 121 // icount 14
slbi r7, 2 // icount 15
srli r2, r5, 8 // icount 16
srli r7, r7, 12 // icount 17
srli r0, r2, 2 // icount 18
srli r3, r1, 4 // icount 19
srli r4, r6, 15 // icount 20
srli r2, r7, 0 // icount 21
srli r7, r5, 13 // icount 22
srli r0, r7, 4 // icount 23
srli r1, r6, 3 // icount 24
srli r5, r2, 10 // icount 25
srli r7, r0, 14 // icount 26
srli r6, r7, 15 // icount 27
srli r3, r6, 1 // icount 28
srli r3, r0, 8 // icount 29
srli r3, r5, 7 // icount 30
srli r2, r4, 9 // icount 31
halt // icount 32
| 24.942857 | 28 | 0.620848 |
4508ee6008e7ebc72fbd03560085019adbd695fd
| 8,982 |
asm
|
Assembly
|
src/test/cpp/raw/pmp/build/pmp.asm
|
cjearls/VexRiscv
|
b92e408bc40cfd93730213312877447c19475f2d
|
[
"MIT"
] | 1 |
2021-07-04T05:24:20.000Z
|
2021-07-04T05:24:20.000Z
|
src/test/cpp/raw/pmp/build/pmp.asm
|
cjearls/VexRiscv
|
b92e408bc40cfd93730213312877447c19475f2d
|
[
"MIT"
] | null | null | null |
src/test/cpp/raw/pmp/build/pmp.asm
|
cjearls/VexRiscv
|
b92e408bc40cfd93730213312877447c19475f2d
|
[
"MIT"
] | 1 |
2021-07-04T05:24:24.000Z
|
2021-07-04T05:24:24.000Z
|
build/pmp.elf: file format elf32-littleriscv
Disassembly of section .crt_section:
80000000 <_start>:
80000000: 00000097 auipc ra,0x0
80000004: 01008093 addi ra,ra,16 # 80000010 <trap>
80000008: 30509073 csrw mtvec,ra
8000000c: 00c0006f j 80000018 <test0>
80000010 <trap>:
80000010: 341f1073 csrw mepc,t5
80000014: 30200073 mret
80000018 <test0>:
80000018: 00000e13 li t3,0
8000001c: 00000f17 auipc t5,0x0
80000020: 27cf0f13 addi t5,t5,636 # 80000298 <fail>
80000024: 800000b7 lui ra,0x80000
80000028: 80008237 lui tp,0x80008
8000002c: deadc137 lui sp,0xdeadc
80000030: eef10113 addi sp,sp,-273 # deadbeef <pass+0x5eadbc4b>
80000034: 0020a023 sw sp,0(ra) # 80000000 <pass+0xfffffd5c>
80000038: 00222023 sw sp,0(tp) # 80008000 <pass+0x7d5c>
8000003c: 0000a183 lw gp,0(ra)
80000040: 24311c63 bne sp,gp,80000298 <fail>
80000044: 00022183 lw gp,0(tp) # 0 <_start-0x80000000>
80000048: 24311863 bne sp,gp,80000298 <fail>
8000004c: 071202b7 lui t0,0x7120
80000050: 3a029073 csrw pmpcfg0,t0
80000054: 3a002373 csrr t1,pmpcfg0
80000058: 24629063 bne t0,t1,80000298 <fail>
8000005c: 191f02b7 lui t0,0x191f0
80000060: 30428293 addi t0,t0,772 # 191f0304 <_start-0x66e0fcfc>
80000064: 3a129073 csrw pmpcfg1,t0
80000068: 000f02b7 lui t0,0xf0
8000006c: 50628293 addi t0,t0,1286 # f0506 <_start-0x7ff0fafa>
80000070: 3a229073 csrw pmpcfg2,t0
80000074: 0f1e22b7 lui t0,0xf1e2
80000078: 90028293 addi t0,t0,-1792 # f1e1900 <_start-0x70e1e700>
8000007c: 3a329073 csrw pmpcfg3,t0
80000080: 200002b7 lui t0,0x20000
80000084: 3b029073 csrw pmpaddr0,t0
80000088: 3b002373 csrr t1,pmpaddr0
8000008c: 20629663 bne t0,t1,80000298 <fail>
80000090: fff00293 li t0,-1
80000094: 3b129073 csrw pmpaddr1,t0
80000098: 200022b7 lui t0,0x20002
8000009c: 3b229073 csrw pmpaddr2,t0
800000a0: 200042b7 lui t0,0x20004
800000a4: fff28293 addi t0,t0,-1 # 20003fff <_start-0x5fffc001>
800000a8: 3b329073 csrw pmpaddr3,t0
800000ac: 200042b7 lui t0,0x20004
800000b0: fff28293 addi t0,t0,-1 # 20003fff <_start-0x5fffc001>
800000b4: 3b429073 csrw pmpaddr4,t0
800000b8: 200042b7 lui t0,0x20004
800000bc: fff28293 addi t0,t0,-1 # 20003fff <_start-0x5fffc001>
800000c0: 3b529073 csrw pmpaddr5,t0
800000c4: 200022b7 lui t0,0x20002
800000c8: fff28293 addi t0,t0,-1 # 20001fff <_start-0x5fffe001>
800000cc: 3b629073 csrw pmpaddr6,t0
800000d0: 200062b7 lui t0,0x20006
800000d4: fff28293 addi t0,t0,-1 # 20005fff <_start-0x5fffa001>
800000d8: 3b729073 csrw pmpaddr7,t0
800000dc: 2000c2b7 lui t0,0x2000c
800000e0: 3b829073 csrw pmpaddr8,t0
800000e4: 2000d2b7 lui t0,0x2000d
800000e8: 3b929073 csrw pmpaddr9,t0
800000ec: fff00293 li t0,-1
800000f0: 3ba29073 csrw pmpaddr10,t0
800000f4: 00000293 li t0,0
800000f8: 3bb29073 csrw pmpaddr11,t0
800000fc: 00000293 li t0,0
80000100: 3bc29073 csrw pmpaddr12,t0
80000104: 00000293 li t0,0
80000108: 3bd29073 csrw pmpaddr13,t0
8000010c: 00000293 li t0,0
80000110: 3be29073 csrw pmpaddr14,t0
80000114: 00000293 li t0,0
80000118: 3bf29073 csrw pmpaddr15,t0
8000011c: 00c10137 lui sp,0xc10
80000120: fee10113 addi sp,sp,-18 # c0ffee <_start-0x7f3f0012>
80000124: 0020a023 sw sp,0(ra)
80000128: 00222023 sw sp,0(tp) # 0 <_start-0x80000000>
8000012c: 0000a183 lw gp,0(ra)
80000130: 16311463 bne sp,gp,80000298 <fail>
80000134: 00000193 li gp,0
80000138: 00022183 lw gp,0(tp) # 0 <_start-0x80000000>
8000013c: 14311e63 bne sp,gp,80000298 <fail>
80000140 <test1>:
80000140: 00100e13 li t3,1
80000144: 00000f17 auipc t5,0x0
80000148: 154f0f13 addi t5,t5,340 # 80000298 <fail>
8000014c: 079212b7 lui t0,0x7921
80000150: 80828293 addi t0,t0,-2040 # 7920808 <_start-0x786df7f8>
80000154: 3a029073 csrw pmpcfg0,t0
80000158: 3a002373 csrr t1,pmpcfg0
8000015c: 12629e63 bne t0,t1,80000298 <fail>
80000160: 800080b7 lui ra,0x80008
80000164: deadc137 lui sp,0xdeadc
80000168: eef10113 addi sp,sp,-273 # deadbeef <pass+0x5eadbc4b>
8000016c: 0020a023 sw sp,0(ra) # 80008000 <pass+0x7d5c>
80000170: 00000f17 auipc t5,0x0
80000174: 010f0f13 addi t5,t5,16 # 80000180 <test2>
80000178: 0000a183 lw gp,0(ra)
8000017c: 11c0006f j 80000298 <fail>
80000180 <test2>:
80000180: 00200e13 li t3,2
80000184: 00000f17 auipc t5,0x0
80000188: 114f0f13 addi t5,t5,276 # 80000298 <fail>
8000018c: 071202b7 lui t0,0x7120
80000190: 3a029073 csrw pmpcfg0,t0
80000194: 3a002373 csrr t1,pmpcfg0
80000198: 3b205073 csrwi pmpaddr2,0
8000019c: 3b202373 csrr t1,pmpaddr2
800001a0: 0e030c63 beqz t1,80000298 <fail>
800001a4: 0e628a63 beq t0,t1,80000298 <fail>
800001a8: 800080b7 lui ra,0x80008
800001ac: deadc137 lui sp,0xdeadc
800001b0: eef10113 addi sp,sp,-273 # deadbeef <pass+0x5eadbc4b>
800001b4: 0020a023 sw sp,0(ra) # 80008000 <pass+0x7d5c>
800001b8: 00000f17 auipc t5,0x0
800001bc: 010f0f13 addi t5,t5,16 # 800001c8 <test3>
800001c0: 0000a183 lw gp,0(ra)
800001c4: 0d40006f j 80000298 <fail>
800001c8 <test3>:
800001c8: 00300e13 li t3,3
800001cc: 00000f17 auipc t5,0x0
800001d0: 0ccf0f13 addi t5,t5,204 # 80000298 <fail>
800001d4: 00000117 auipc sp,0x0
800001d8: 01010113 addi sp,sp,16 # 800001e4 <test4>
800001dc: 34111073 csrw mepc,sp
800001e0: 30200073 mret
800001e4 <test4>:
800001e4: 00400e13 li t3,4
800001e8: 00000f17 auipc t5,0x0
800001ec: 0b0f0f13 addi t5,t5,176 # 80000298 <fail>
800001f0: deadc137 lui sp,0xdeadc
800001f4: eef10113 addi sp,sp,-273 # deadbeef <pass+0x5eadbc4b>
800001f8: 800080b7 lui ra,0x80008
800001fc: 0020a023 sw sp,0(ra) # 80008000 <pass+0x7d5c>
80000200: 00000f17 auipc t5,0x0
80000204: 010f0f13 addi t5,t5,16 # 80000210 <test5>
80000208: 0000a183 lw gp,0(ra)
8000020c: 08c0006f j 80000298 <fail>
80000210 <test5>:
80000210: 00500e13 li t3,5
80000214: deadc137 lui sp,0xdeadc
80000218: eef10113 addi sp,sp,-273 # deadbeef <pass+0x5eadbc4b>
8000021c: 800000b7 lui ra,0x80000
80000220: 0020a023 sw sp,0(ra) # 80000000 <pass+0xfffffd5c>
80000224: 0000a183 lw gp,0(ra)
80000228: 06311863 bne sp,gp,80000298 <fail>
8000022c <test6>:
8000022c: 00600e13 li t3,6
80000230: 800100b7 lui ra,0x80010
80000234: 0000a183 lw gp,0(ra) # 80010000 <pass+0xfd5c>
80000238: 00000f17 auipc t5,0x0
8000023c: 06cf0f13 addi t5,t5,108 # 800002a4 <pass>
80000240: 0030a023 sw gp,0(ra)
80000244: 0540006f j 80000298 <fail>
80000248 <test7>:
80000248: 00700e13 li t3,7
8000024c: 00000f17 auipc t5,0x0
80000250: 04cf0f13 addi t5,t5,76 # 80000298 <fail>
80000254: deadc137 lui sp,0xdeadc
80000258: eef10113 addi sp,sp,-273 # deadbeef <pass+0x5eadbc4b>
8000025c: 800300b7 lui ra,0x80030
80000260: ff808093 addi ra,ra,-8 # 8002fff8 <pass+0x2fd54>
80000264: 00222023 sw sp,0(tp) # 0 <_start-0x80000000>
80000268: 00000f17 auipc t5,0x0
8000026c: fa8f0f13 addi t5,t5,-88 # 80000210 <test5>
80000270: 00022183 lw gp,0(tp) # 0 <_start-0x80000000>
80000274: 0240006f j 80000298 <fail>
80000278 <test8>:
80000278: 00800e13 li t3,8
8000027c: 800400b7 lui ra,0x80040
80000280: ff808093 addi ra,ra,-8 # 8003fff8 <pass+0x3fd54>
80000284: 0000a183 lw gp,0(ra)
80000288: 00000f17 auipc t5,0x0
8000028c: 01cf0f13 addi t5,t5,28 # 800002a4 <pass>
80000290: 0030a023 sw gp,0(ra)
80000294: 0040006f j 80000298 <fail>
80000298 <fail>:
80000298: f0100137 lui sp,0xf0100
8000029c: f2410113 addi sp,sp,-220 # f00fff24 <pass+0x700ffc80>
800002a0: 01c12023 sw t3,0(sp)
800002a4 <pass>:
800002a4: f0100137 lui sp,0xf0100
800002a8: f2010113 addi sp,sp,-224 # f00fff20 <pass+0x700ffc7c>
800002ac: 00012023 sw zero,0(sp)
| 44.029412 | 75 | 0.631374 |
7f0f21abeeec2906c522c0a9c1ca06cf0a0b4f94
| 1,405 |
rs
|
Rust
|
src/data/streams.rs
|
merembablas/spearmint
|
7c4545872a987840fbf97f5466380d4595bb35dd
|
[
"MIT"
] | null | null | null |
src/data/streams.rs
|
merembablas/spearmint
|
7c4545872a987840fbf97f5466380d4595bb35dd
|
[
"MIT"
] | null | null | null |
src/data/streams.rs
|
merembablas/spearmint
|
7c4545872a987840fbf97f5466380d4595bb35dd
|
[
"MIT"
] | 1 |
2022-02-07T04:27:47.000Z
|
2022-02-07T04:27:47.000Z
|
use binance::websockets::*;
use comfy_table::Table;
use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
pub fn run(exchange: &str, symbols: Vec<String>) {
if exchange == "binance" {
let mut endpoints: Vec<String> = Vec::new();
let mut prices: HashMap<String, f32> = HashMap::new();
for symbol in symbols.iter() {
endpoints.push(format!("{}@ticker", symbol.to_lowercase()));
}
let keep_running = AtomicBool::new(true);
let mut web_socket: WebSockets<'_> = WebSockets::new(|event: WebsocketEvent| {
if let WebsocketEvent::DayTicker(ticker_event) = event {
prices.insert(
ticker_event.symbol,
ticker_event.current_close.parse().unwrap(),
);
print!("\x1B[2J\x1B[1;1H");
let mut table = Table::new();
table.set_header(vec!["Pair", "Price"]);
for (pair, price) in &prices {
table.add_row(vec![pair, &format!("{}", price)]);
}
println!("{}", table);
}
Ok(())
});
web_socket.connect_multiple_streams(&endpoints).unwrap();
if let Err(e) = web_socket.event_loop(&keep_running) {
println!("Error: {:?}", e);
}
web_socket.disconnect().unwrap();
}
}
| 30.543478 | 86 | 0.520285 |
12351d5936fea3081f9fadcaa00f98d24ac38e3b
| 3,293 |
h
|
C
|
include/Circuit.h
|
cross-platform/route20
|
ad9ecccac16c782caa1df55055f4583dae15e7a9
|
[
"BSD-2-Clause"
] | 1 |
2021-09-18T22:59:35.000Z
|
2021-09-18T22:59:35.000Z
|
include/Circuit.h
|
cross-platform/route20
|
ad9ecccac16c782caa1df55055f4583dae15e7a9
|
[
"BSD-2-Clause"
] | null | null | null |
include/Circuit.h
|
cross-platform/route20
|
ad9ecccac16c782caa1df55055f4583dae15e7a9
|
[
"BSD-2-Clause"
] | 3 |
2021-07-05T01:39:26.000Z
|
2022-03-27T17:09:35.000Z
|
/************************************************************************
Route20 - Cross-Platform C++ Dataflow Metaprogramming Framework
Copyright (c) 2021 Marcus Tomlinson
This file is part of Route20.
Simplified BSD Licence:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
************************************************************************/
#pragma once
#include <Common.h>
#include <map>
namespace Route20
{
template <auto... components>
class Circuit final
{
public:
Circuit()
{
InitMaps<components...>();
}
Circuit( const Circuit& ) = delete;
Circuit& operator=( const Circuit& ) = delete;
void Tick()
{
Tick<components...>();
for ( auto& [_, ticked] : tickeds )
{
ticked = false;
}
}
private:
template <auto comp, auto comp2, auto... comps>
void InitMaps()
{
InitMaps<comp>();
InitMaps<comp2, comps...>();
}
template <auto comp>
void InitMaps()
{
using CompRt = typename decltype( comp )::runtime;
rts[comp.id].template emplace<CompRt>();
tickeds[comp.id] = false;
}
template <auto comp, auto comp2, auto... comps>
void Tick()
{
Tick<comp>();
Tick<comp2, comps...>();
}
template <auto comp>
void Tick()
{
if ( tickeds[comp.id] )
{
return;
}
tickeds[comp.id] = true;
using CompRt = typename decltype( comp )::runtime;
comp.InputWires( [this]<auto fromComp, auto output, auto input>() {
Tick<fromComp>();
using FromCompRt = typename decltype( fromComp )::runtime;
std::get<input>( std::get<CompRt>( rts[comp.id] ).inputs ) =
std::get<output>( std::get<FromCompRt>( rts[fromComp.id] ).outputs );
} );
comp.Tick( std::get<CompRt>( rts[comp.id] ) );
}
std::map<unsigned int, dedup_variant<std::variant<typename decltype( components )::runtime...>>> rts;
std::map<unsigned int, bool> tickeds;
};
} // namespace Route20
| 29.141593 | 105 | 0.628606 |
f333d79fdc55230b0697b969290a6db3f721c691
| 282 |
lua
|
Lua
|
plugins/cwweapons/items/cwweapons/sh_tokarev.lua
|
LtTaylor97/taylors-ix-plugins
|
72a7471218c3aa1d3bdfddcf67df942a8e413b7f
|
[
"MIT"
] | 1 |
2022-02-26T18:03:51.000Z
|
2022-02-26T18:03:51.000Z
|
plugins/cwweapons/items/cwweapons/sh_tokarev.lua
|
LtTaylor97/taylors-ix-plugins
|
72a7471218c3aa1d3bdfddcf67df942a8e413b7f
|
[
"MIT"
] | null | null | null |
plugins/cwweapons/items/cwweapons/sh_tokarev.lua
|
LtTaylor97/taylors-ix-plugins
|
72a7471218c3aa1d3bdfddcf67df942a8e413b7f
|
[
"MIT"
] | null | null | null |
ITEM.name = "Tokarev TT-33"
ITEM.description = "An old semi-automatic handgun. Fires 7.62x25mm."
ITEM.model = "models/weapons/ethereal/w_tokarev.mdl"
ITEM.class = "cw_kk_ins2_tokarev"
ITEM.weaponCategory = "secondary"
ITEM.width = 2
ITEM.height = 1
ITEM.price = 1150
ITEM.weight = 3
| 31.333333 | 68 | 0.755319 |
b1af606db9680128ac0ff91d7a876390af18e546
| 302 |
h
|
C
|
Example/RHMarkdownLabelExample/AppDelegate.h
|
chriscdn/RHMarkdownLabel
|
86bd7221a8ccba22a60eb1a5f31e8c0e19d064ad
|
[
"MIT"
] | 1 |
2018-03-28T12:26:56.000Z
|
2018-03-28T12:26:56.000Z
|
Example/RHMarkdownLabelExample/AppDelegate.h
|
chriscdn/RHMarkdownLabel
|
86bd7221a8ccba22a60eb1a5f31e8c0e19d064ad
|
[
"MIT"
] | 2 |
2018-04-06T09:26:04.000Z
|
2019-01-20T11:00:07.000Z
|
Example/RHMarkdownLabelExample/AppDelegate.h
|
chriscdn/RHMarkdownLabel
|
86bd7221a8ccba22a60eb1a5f31e8c0e19d064ad
|
[
"MIT"
] | 1 |
2018-03-28T13:34:09.000Z
|
2018-03-28T13:34:09.000Z
|
//
// AppDelegate.h
// RHMarkdownLabelExample
//
// Created by Christopher Meyer on 23/02/16.
// Copyright © 2016 Christopher Meyer. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| 20.133333 | 60 | 0.735099 |
d9b16eb71f19f7742e1cf04a91b75e444a4a9f13
| 996 |
lua
|
Lua
|
tools/sysbench-mongo/sysbench/sysbench/tests/mongodb/write_only.lua
|
DipanshKhandelwal/litmus
|
69c679f9fc59fcd23f9d8daa2fddb766b559cbc8
|
[
"Apache-2.0"
] | 20 |
2019-06-20T08:54:38.000Z
|
2022-03-17T00:08:59.000Z
|
tools/sysbench-mongo/sysbench/sysbench/tests/mongodb/write_only.lua
|
DipanshKhandelwal/litmus
|
69c679f9fc59fcd23f9d8daa2fddb766b559cbc8
|
[
"Apache-2.0"
] | 49 |
2019-08-12T11:23:51.000Z
|
2022-03-14T16:24:38.000Z
|
tools/sysbench-mongo/sysbench/sysbench/tests/mongodb/write_only.lua
|
DipanshKhandelwal/litmus
|
69c679f9fc59fcd23f9d8daa2fddb766b559cbc8
|
[
"Apache-2.0"
] | 42 |
2019-05-16T12:35:04.000Z
|
2022-02-23T16:57:46.000Z
|
-- Copyright (C) 2016 Percona
pathtest = string.match(test, "(.*/)") or ""
dofile(pathtest .. "common.lua")
function thread_init(thread_id)
db_connect()
set_vars()
end
function event(thread_id)
for i=1, oltp_index_updates do
mongodb_index_update("sbtest" .. sb_rand(1, oltp_tables_count), sb_rand(1, oltp_table_size))
end
for i=1, oltp_non_index_updates do
mongodb_non_index_update("sbtest" .. sb_rand(1, oltp_tables_count), sb_rand(1, oltp_table_size))
end
for i=1, oltp_inserts do
local c_val = sb_rand_str([[
###########-###########-###########-###########-###########-###########-###########-###########-###########-###########]])
local pad_val = sb_rand_str([[
###########-###########-###########-###########-###########]])
mongodb_oltp_insert("sbtest" .. sb_rand(1, oltp_tables_count), sb_rand(oltp_table_size*2, oltp_table_size*3) + thread_id, sb_rand(1, oltp_table_size), c_val, pad_val)
end
mongodb_fake_commit()
end
| 32.129032 | 167 | 0.575301 |
0b656cc83021e203c812d1aff73f032e83584937
| 16,883 |
sql
|
SQL
|
src/sql/plugins/appointment/plugin/create_db_appointment.sql
|
lutece-platform/lutece-apps-plugin-appointment
|
fda78dfd38cbdf3a5abcf635540763b7d9a74844
|
[
"Unlicense"
] | 2 |
2019-03-18T11:19:46.000Z
|
2022-03-13T20:17:23.000Z
|
src/sql/plugins/appointment/plugin/create_db_appointment.sql
|
lutece-platform/lutece-apps-plugin-appointment
|
fda78dfd38cbdf3a5abcf635540763b7d9a74844
|
[
"Unlicense"
] | 13 |
2020-04-16T09:13:10.000Z
|
2022-01-26T15:05:09.000Z
|
src/sql/plugins/appointment/plugin/create_db_appointment.sql
|
lutece-platform/lutece-apps-plugin-appointment
|
fda78dfd38cbdf3a5abcf635540763b7d9a74844
|
[
"Unlicense"
] | 10 |
2016-11-10T09:37:39.000Z
|
2022-03-30T15:11:27.000Z
|
DROP TABLE IF EXISTS appointment_reservation_rule ;
DROP TABLE IF EXISTS appointment_appointment_response ;
DROP TABLE IF EXISTS appointment_form_message ;
DROP TABLE IF EXISTS appointment_form_portlet ;
DROP TABLE IF EXISTS appointment_time_slot ;
DROP TABLE IF EXISTS appointment_working_day ;
DROP TABLE IF EXISTS appointment_week_definition ;
DROP TABLE IF EXISTS appointment_closing_day ;
DROP TABLE IF EXISTS appointment_form_rule ;
DROP TABLE IF EXISTS appointment_display ;
DROP TABLE IF EXISTS appointment_localization ;
DROP TABLE IF EXISTS appointment_calendar_template ;
DROP TABLE IF EXISTS appointment_appointment ;
DROP TABLE IF EXISTS appointment_user ;
DROP TABLE IF EXISTS appointment_slot ;
DROP TABLE IF EXISTS appointment_form ;
DROP TABLE IF EXISTS appointment_category ;
DROP TABLE IF EXISTS appointment_comment;
DROP TABLE IF EXISTS appointment_comment_notification_cf;
-- -----------------------------------------------------
-- Table appointment_category
-- -----------------------------------------------------
CREATE TABLE appointment_category (
id_category INT AUTO_INCREMENT,
label VARCHAR(255) NOT NULL,
nb_max_appointments_per_user INT DEFAULT 0 NOT NULL,
PRIMARY KEY (id_category)
);
CREATE UNIQUE INDEX appointment_category_unique_label ON appointment_category (label);
-- -----------------------------------------------------
-- Table appointment_user
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_user (
id_user INT AUTO_INCREMENT,
guid VARCHAR(255) NULL,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
email VARCHAR(255) NULL,
phone_number VARCHAR(255) NULL,
PRIMARY KEY (id_user)
);
CREATE INDEX email_idx ON appointment_user (email ASC);
-- -----------------------------------------------------
-- Table appointment_form
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_form (
id_form INT AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL,
reference VARCHAR(255) NULL,
id_category INT NULL,
starting_validity_date DATE NULL,
ending_validity_date DATE NULL,
is_active BOOLEAN DEFAULT FALSE NOT NULL,
id_workflow INT NULL,
workgroup varchar(255) NULL,
is_multislot_appointment BOOLEAN DEFAULT FALSE NOT NULL,
role_fo varchar(255),
capacity_per_slot INT DEFAULT 0 NOT NULL,
PRIMARY KEY (id_form),
CONSTRAINT fk_appointment_form_appointment_category
FOREIGN KEY (id_category)
REFERENCES appointment_category (id_category)
);
CREATE INDEX starting_validity_date_idx ON appointment_form (starting_validity_date ASC);
CREATE INDEX ending_validity_date_idx ON appointment_form (ending_validity_date ASC);
CREATE INDEX fk_appointment_form_appointment_category_idx ON appointment_form (id_category ASC);
-- -----------------------------------------------------
-- Table appointment_slot
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_slot (
id_slot INT AUTO_INCREMENT,
starting_date_time TIMESTAMP NULL,
ending_date_time TIMESTAMP NULL,
is_open BOOLEAN DEFAULT TRUE NOT NULL,
is_specific BOOLEAN DEFAULT FALSE NOT NULL,
max_capacity INT DEFAULT 0 NOT NULL,
nb_remaining_places INT DEFAULT 0 NOT NULL,
nb_potential_remaining_places INT DEFAULT 0 NOT NULL,
nb_places_taken INT DEFAULT 0 NOT NULL,
id_form INT NOT NULL,
PRIMARY KEY (id_slot),
CONSTRAINT fk_appointment_slot_appointment_form
FOREIGN KEY (id_form)
REFERENCES appointment_form (id_form)
);
CREATE INDEX fk_appointment_slot_appointment_form_idx ON appointment_slot (id_form ASC);
CREATE INDEX starting_date_time_idx ON appointment_slot (starting_date_time ASC);
CREATE INDEX ending_date_time_idx ON appointment_slot (ending_date_time ASC);
CREATE UNIQUE INDEX appointment_slot_unique_starting ON appointment_slot (id_form,starting_date_time);
CREATE UNIQUE INDEX appointment_slot_unique_ending ON appointment_slot (id_form,ending_date_time);
-- -----------------------------------------------------
-- Table appointment_appointment
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_appointment (
id_appointment INT AUTO_INCREMENT,
reference VARCHAR(45) NULL,
nb_places INT DEFAULT 0 NOT NULL,
is_cancelled BOOLEAN DEFAULT FALSE NOT NULL,
id_action_cancelled INT,
id_action_reported INT,
notification INT DEFAULT 0 NOT NULL,
id_admin_user INT DEFAULT 0 NULL,
date_appointment_create TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
admin_access_code_create VARCHAR(100) ,
id_user INT NOT NULL,
is_surbooked BOOLEAN DEFAULT FALSE NOT NULL,
PRIMARY KEY (id_appointment ),
CONSTRAINT fk_appointment_appointment_appointment_user
FOREIGN KEY (id_user)
REFERENCES appointment_user (id_user)
);
CREATE INDEX fk_appointment_appointment_appointment_user_idx ON appointment_appointment (id_user ASC);
CREATE UNIQUE INDEX reference_idx ON appointment_appointment (reference ASC);
-- -----------------------------------------------------
-- Table appointment_appointment_slot
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_appointment_slot (
id_appointment INT NOT NULL,
id_slot INT NOT NULL,
nb_places INT NOT NULL,
PRIMARY KEY (id_appointment, id_slot ),
CONSTRAINT fk_appointment_appointment_slot_appointment
FOREIGN KEY (id_appointment)
REFERENCES appointment_appointment (id_appointment),
CONSTRAINT fk_appointment_appointment_slot_slot
FOREIGN KEY (id_slot)
REFERENCES appointment_slot (id_slot)
);
-- -----------------------------------------------------
-- Table appointment_appointment_response
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_appointment_response (
id_appointment_response INT AUTO_INCREMENT,
id_response INT NOT NULL,
id_appointment INT NOT NULL,
PRIMARY KEY (id_appointment_response),
CONSTRAINT fk_appointment_appointment_response_appointment_appointment
FOREIGN KEY (id_appointment)
REFERENCES appointment_appointment (id_appointment)
);
CREATE INDEX fk_appointment_appointment_response_appointment_appointment_idx ON appointment_appointment_response (id_appointment ASC);
CREATE UNIQUE INDEX appointment_appointment_response_unique ON appointment_appointment_response (id_appointment,id_response);
-- -----------------------------------------------------
-- Table appointment_calendar_template
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_calendar_template (
id_calendar_template INT AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL,
template_path VARCHAR(255) NOT NULL,
PRIMARY KEY (id_calendar_template)
);
-- -----------------------------------------------------
-- Table appointment_form_message
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_form_message (
id_form_message INT AUTO_INCREMENT,
calendar_title VARCHAR(255) NOT NULL,
field_firstname_title VARCHAR(255) NOT NULL,
field_firstname_help VARCHAR(255) NOT NULL,
field_lastname_title VARCHAR(255) NOT NULL,
field_lastname_help VARCHAR(255) NOT NULL,
field_email_title VARCHAR(255) NOT NULL,
field_email_help VARCHAR(255) NOT NULL,
field_confirmationEmail_title VARCHAR(255) NOT NULL,
field_confirmationEmail_help VARCHAR(255) NOT NULL,
text_appointment_created LONG VARCHAR NOT NULL,
url_redirect_after_creation VARCHAR(255) NOT NULL,
text_appointment_canceled LONG VARCHAR NOT NULL,
label_button_redirection VARCHAR(255) NOT NULL,
no_available_slot VARCHAR(255) NOT NULL,
calendar_description LONG VARCHAR NOT NULL,
calendar_reserve_label VARCHAR(255) NOT NULL,
calendar_full_label VARCHAR(255) NOT NULL,
id_form INT NOT NULL,
PRIMARY KEY (id_form_message),
CONSTRAINT fk_appointment_form_message_appointment_form
FOREIGN KEY (id_form)
REFERENCES appointment_form (id_form)
);
CREATE INDEX fk_appointment_form_message_appointment_form_idx ON appointment_form_message (id_form ASC);
-- -----------------------------------------------------
-- Table appointment_form_portlet
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_form_portlet (
id_portlet INT NOT NULL,
id_form INT NOT NULL,
PRIMARY KEY (id_portlet, id_form),
CONSTRAINT fk_appointment_form_portlet_appointment_form
FOREIGN KEY (id_form)
REFERENCES appointment_form (id_form)
);
CREATE INDEX fk_appointment_form_portlet_appointment_form_idx ON appointment_form_portlet (id_form ASC);
-- -----------------------------------------------------
-- Table appointment_reservation_rule
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_reservation_rule (
id_reservation_rule INT AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL,
color VARCHAR(255),
enable BOOLEAN DEFAULT TRUE NOT NULL,
max_capacity_per_slot INT DEFAULT 0 NOT NULL,
max_people_per_appointment INT DEFAULT 0 NOT NULL,
duration_appointments int DEFAULT 15 NOT NULL,
id_form INT NOT NULL,
PRIMARY KEY (id_reservation_rule),
CONSTRAINT fk_appointment_reservation_rule_appointment_form
FOREIGN KEY (id_form)
REFERENCES appointment_form (id_form)
);
CREATE INDEX fk_appointment_reservation_rule_appointment_form_idx ON appointment_reservation_rule (id_form ASC);
-- -----------------------------------------------------
-- Table appointment_week_definition
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_week_definition (
id_week_definition INT AUTO_INCREMENT,
id_reservation_rule INT NOT NULL,
date_of_apply DATE NOT NULL,
ending_date_of_apply DATE NOT NULL,
PRIMARY KEY (id_week_definition),
CONSTRAINT fk_appointment_week_definition_appointment_reservation_rule
FOREIGN KEY (id_reservation_rule)
REFERENCES appointment_reservation_rule (id_reservation_rule)
);
CREATE INDEX date_of_apply_idx ON appointment_week_definition (date_of_apply ASC);
CREATE UNIQUE INDEX appointment_week_definition_unique_date ON appointment_week_definition (id_reservation_rule,date_of_apply);
-- -----------------------------------------------------
-- Table appointment_working_day
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_working_day (
id_working_day INT AUTO_INCREMENT,
day_of_week INT NOT NULL,
id_reservation_rule INT NOT NULL,
PRIMARY KEY (id_working_day),
CONSTRAINT fk_appointment_working_day_appointment_reservation_rule
FOREIGN KEY (id_reservation_rule)
REFERENCES appointment_reservation_rule (id_reservation_rule)
);
CREATE INDEX fk_appointment_working_day_appointment_reservation_rule_idx ON appointment_reservation_rule (id_reservation_rule ASC);
CREATE UNIQUE INDEX appointment_working_day_unique ON appointment_working_day (id_reservation_rule,day_of_week);
-- -----------------------------------------------------
-- Table appointment_time_slot
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_time_slot (
id_time_slot INT AUTO_INCREMENT,
starting_time TIME NOT NULL,
ending_time TIME NOT NULL,
is_open BOOLEAN DEFAULT TRUE NOT NULL,
max_capacity INT DEFAULT 0 NOT NULL,
id_working_day INT NOT NULL,
PRIMARY KEY (id_time_slot),
CONSTRAINT fk_appointment_time_slot_appointment_working_day
FOREIGN KEY (id_working_day)
REFERENCES appointment_working_day (id_working_day)
);
CREATE INDEX fk_appointment_time_slot_appointment_working_day_idx ON appointment_time_slot (id_working_day ASC);
CREATE INDEX starting_time_idx ON appointment_time_slot (starting_time ASC);
CREATE INDEX ending_time_idx ON appointment_time_slot (ending_time ASC);
CREATE UNIQUE INDEX appointment_time_slot_unique_starting ON appointment_time_slot (id_working_day,starting_time);
CREATE UNIQUE INDEX appointment_time_slot_unique_ending ON appointment_time_slot (id_working_day,ending_time);
-- -----------------------------------------------------
-- Table appointment_localization
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_localization (
id_localization INT AUTO_INCREMENT,
longitude FLOAT NULL,
latitude FLOAT NULL,
address VARCHAR(255) NULL,
id_form INT NOT NULL,
PRIMARY KEY (id_localization),
CONSTRAINT fk_appointment_localization_appointment_form
FOREIGN KEY (id_form)
REFERENCES appointment_form (id_form)
);
CREATE INDEX fk_appointment_localization_appointment_form_idx ON appointment_localization (id_form ASC);
-- -----------------------------------------------------
-- Table appointment_display
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_display (
id_display INT AUTO_INCREMENT,
display_title_fo BOOLEAN DEFAULT FALSE NOT NULL,
icon_form_content LONG VARBINARY NULL,
icon_form_mime_type VARCHAR(255) NULL,
nb_weeks_to_display INT DEFAULT 0 NOT NULL,
is_displayed_on_portlet BOOLEAN DEFAULT TRUE NOT NULL,
id_calendar_template INT NOT NULL,
id_form INT NOT NULL,
PRIMARY KEY (id_display),
CONSTRAINT fk_appointment_display_appointment_calendar_template
FOREIGN KEY (id_calendar_template)
REFERENCES appointment_calendar_template (id_calendar_template),
CONSTRAINT fk_appointment_display_appointment_form
FOREIGN KEY (id_form)
REFERENCES appointment_form (id_form)
);
CREATE INDEX fk_appointment_display_appointment_calendar_template_idx ON appointment_display (id_calendar_template ASC);
CREATE UNIQUE INDEX appointment_display_unique ON appointment_display (id_form);
-- -----------------------------------------------------
-- Table appointment_form_rule
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_form_rule (
id_form_rule INT AUTO_INCREMENT,
is_captcha_enabled BOOLEAN DEFAULT FALSE NOT NULL,
is_mandatory_email_enabled BOOLEAN DEFAULT FALSE NOT NULL,
is_active_authentication BOOLEAN DEFAULT FALSE NOT NULL,
nb_days_before_new_appointment INT DEFAULT 0 NOT NULL,
min_time_before_appointment INT DEFAULT 0 NOT NULL,
nb_max_appointments_per_user INT DEFAULT 0 NOT NULL,
nb_days_for_max_appointments_per_user INT DEFAULT 0 NOT NULL,
bo_overbooking BOOLEAN DEFAULT FALSE NOT NULL,
id_form INT NOT NULL,
PRIMARY KEY (id_form_rule),
CONSTRAINT fk_appointment_form_rule_appointment_form
FOREIGN KEY (id_form)
REFERENCES appointment_form (id_form)
);
CREATE UNIQUE INDEX appointment_form_rule_unique ON appointment_form_rule (id_form);
-- -----------------------------------------------------
-- Table appointment_closing_day
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS appointment_closing_day (
id_closing_day INT AUTO_INCREMENT,
date_of_closing_day DATE NOT NULL,
id_form INT NOT NULL,
PRIMARY KEY (id_closing_day),
CONSTRAINT fk_appointment_closing_day_appointment_form
FOREIGN KEY (id_form)
REFERENCES appointment_form (id_form)
);
CREATE INDEX fk_appointment_closing_day_appointment_form_idx ON appointment_closing_day (id_form ASC);
CREATE INDEX date_of_closing_day ON appointment_closing_day (date_of_closing_day ASC);
CREATE UNIQUE INDEX appointment_closing_day_unique ON appointment_closing_day (id_form,date_of_closing_day);
--
-- Structure for table appointment_comment
--
CREATE TABLE appointment_comment (
id_comment int AUTO_INCREMENT,
id_form int default '0' NOT NULL,
starting_validity_date date NOT NULL,
starting_validity_time TIME,
ending_validity_date date NOT NULL,
ending_validity_time TIME,
comment long varchar NOT NULL,
comment_creation_date date NOT NULL,
comment_user_creator VARCHAR(255) NOT NULL,
PRIMARY KEY (id_comment),
CONSTRAINT fk_appointment_comment FOREIGN KEY (id_form)
REFERENCES appointment_form (id_form)
);
-- -----------------------------------------------------------
-- Table structure for table appointment_notification_cf --
-- -----------------------------------------------------------
CREATE TABLE appointment_comment_notification_cf
(
notify_type VARCHAR(45) NOT NULL,
sender_name VARCHAR(255) DEFAULT NULL,
subject VARCHAR(255) DEFAULT NULL,
message LONG VARCHAR DEFAULT NULL
);
| 42.102244 | 135 | 0.70106 |
f034b8b6b6d0852450c50577d53070c406d80750
| 770 |
py
|
Python
|
lambda-archive/lambda-functions/codebreaker-update-testcaseCount/lambda_function.py
|
singaporezoo/codebreaker-official
|
1fe5792f1c36f922abd0836d8dcb42d271a9323d
|
[
"MIT"
] | 11 |
2021-09-19T06:32:44.000Z
|
2022-03-14T19:09:46.000Z
|
lambda-archive/lambda-functions/codebreaker-update-testcaseCount/lambda_function.py
|
singaporezoo/codebreaker-official
|
1fe5792f1c36f922abd0836d8dcb42d271a9323d
|
[
"MIT"
] | null | null | null |
lambda-archive/lambda-functions/codebreaker-update-testcaseCount/lambda_function.py
|
singaporezoo/codebreaker-official
|
1fe5792f1c36f922abd0836d8dcb42d271a9323d
|
[
"MIT"
] | 1 |
2022-03-02T13:27:27.000Z
|
2022-03-02T13:27:27.000Z
|
import json
import boto3 # Amazon S3 client library
s3 = boto3.resource('s3')
dynamodb = boto3.resource('dynamodb')
problems_table = dynamodb.Table('codebreaker-problems')
bucket = s3.Bucket('codebreaker-testdata')
def lambda_handler(event, context):
problemName = event['problemName']
testcaseCount = 0
for obj in bucket.objects.filter(Prefix="{0}/".format(problemName)):
testcaseCount += 1
print(testcaseCount)
problems_table.update_item(
Key = {'problemName':problemName},
UpdateExpression = f'set #b=:a',
ExpressionAttributeValues={':a':int(testcaseCount/2)},
ExpressionAttributeNames={'#b':'testcaseCount'}
)
return {
'statusCode': 200,
'testcaseCount':testcaseCount
}
| 28.518519 | 72 | 0.672727 |
1df4f103df8598e40d21d6583bae177c600aa9d5
| 23,290 |
sql
|
SQL
|
hj-sw.sql
|
iamhj/ssms
|
fb867728bf6518bb97bdee188cb30ebe25d4014e
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
hj-sw.sql
|
iamhj/ssms
|
fb867728bf6518bb97bdee188cb30ebe25d4014e
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
hj-sw.sql
|
iamhj/ssms
|
fb867728bf6518bb97bdee188cb30ebe25d4014e
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
/*
Navicat Premium Data Transfer
Source Server : iamhj
Source Server Type : MySQL
Source Server Version : 50726
Source Host : localhost:3306
Source Schema : sw
Target Server Type : MySQL
Target Server Version : 50726
File Encoding : 65001
Date: 09/07/2021 17:35:02
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for hj_goods
-- ----------------------------
DROP TABLE IF EXISTS `hj_goods`;
CREATE TABLE `hj_goods` (
`goods_id` int(11) NOT NULL AUTO_INCREMENT,
`goods_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`type_id` int(11) NULL DEFAULT NULL,
`price` int(11) NULL DEFAULT NULL,
`number` int(11) NULL DEFAULT NULL,
`describe` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`picture` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`seller_id` int(10) NULL DEFAULT NULL,
PRIMARY KEY (`goods_id`) USING BTREE,
INDEX `user_id`(`seller_id`) USING BTREE,
INDEX `type_id`(`type_id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 27 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of hj_goods
-- ----------------------------
INSERT INTO `hj_goods` VALUES (20, 'ThinkPHP网站开发教程', 4, 15, 20, '本书讲解使用ThinkPHP框架开发动态网站,有丰富的实战例子。', 'https://img10.360buyimg.com/n1/s200x200_jfs/t1/137034/33/225/47746/5eca3b72Ec415a16b/38ba44c31adade76.jpg', 84);
INSERT INTO `hj_goods` VALUES (18, 'Type-C数据线', 2, 5, 20, '适合Type-C充电接口的数码产品;双面都能充电', 'https://img13.360buyimg.com/n1/s450x450_jfs/t1/111738/21/13859/29678/5f27d8adE29e30fd4/c61787aba129b976.jpg', 84);
INSERT INTO `hj_goods` VALUES (19, '小风扇', 3, 10, 20, 'Micro-USB接口可充电迷你小风扇,绿色的', 'http://www.doublepow.com/Uploads/5acad69ad9c20.jpg', 84);
INSERT INTO `hj_goods` VALUES (21, '白色U盘', 2, 20, 20, '128G超大容量的U盘', 'https://img12.360buyimg.com/n7/jfs/t1/125142/12/10776/80410/5f4473f0Eeed8da73/870f3709c4480751.jpg', 84);
INSERT INTO `hj_goods` VALUES (17, '黑色签字笔', 1, 1, 20, '巨能写签字笔,油墨超多,书写时间超长', 'https://cdn.cnbj0.fds.api.mi-img.com/b2c-shopapi-pms/pms_1559616366.16874615.jpg', 84);
INSERT INTO `hj_goods` VALUES (25, '无线充电套装', 2, 50, 20, '20W高通无线充;白色', '/uploads/20210108/cc1770e74ba65cf7a49bbdecd0865c1c.jpg', 87);
INSERT INTO `hj_goods` VALUES (26, '自拍杆', 2, 20, 20, '小米支架式自拍杆;雅蓝色', '/uploads/20210108/5b0b1d39583d32c9c7d2a7f5a07ff651.jpg', 87);
-- ----------------------------
-- Table structure for hj_goods_type
-- ----------------------------
DROP TABLE IF EXISTS `hj_goods_type`;
CREATE TABLE `hj_goods_type` (
`type_id` int(11) NOT NULL AUTO_INCREMENT,
`type_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`type_id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of hj_goods_type
-- ----------------------------
INSERT INTO `hj_goods_type` VALUES (1, '学习用品');
INSERT INTO `hj_goods_type` VALUES (2, '数码产品');
INSERT INTO `hj_goods_type` VALUES (3, '生活用品');
INSERT INTO `hj_goods_type` VALUES (4, '书籍');
-- ----------------------------
-- Table structure for hj_menu
-- ----------------------------
DROP TABLE IF EXISTS `hj_menu`;
CREATE TABLE `hj_menu` (
`menu_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '菜单编号',
`url` varchar(80) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '菜单地址',
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '菜单名称',
`icon` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '图标',
`parent_id` int(5) NOT NULL DEFAULT 0 COMMENT '父栏目ID',
`sort` int(11) NULL DEFAULT 1 COMMENT '排序',
`visible` tinyint(1) NULL DEFAULT NULL COMMENT '是否可见',
`open` tinyint(1) NULL DEFAULT NULL COMMENT '是否展开',
PRIMARY KEY (`menu_id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of hj_menu
-- ----------------------------
INSERT INTO `hj_menu` VALUES (4, '', '商品管理', 'layui-icon-app', 0, 1, 1, 1);
INSERT INTO `hj_menu` VALUES (5, '/hj/goods/index', '所有商品', '', 4, 1, 1, 1);
INSERT INTO `hj_menu` VALUES (6, '/hj/goods_type/index', '商品类型', NULL, 4, 1, 1, 1);
INSERT INTO `hj_menu` VALUES (7, '', '店铺管理', 'layui-icon-home', 0, 1, 1, 1);
INSERT INTO `hj_menu` VALUES (8, '/hj/order/seller_order', '店铺订单', '', 7, 1, 1, 1);
INSERT INTO `hj_menu` VALUES (9, '/hj/goods/seller_form', '店铺商品', '', 7, 1, 1, 1);
INSERT INTO `hj_menu` VALUES (10, '/hj/order/buyer_order', '购买订单', '', 4, 1, 1, 1);
-- ----------------------------
-- Table structure for hj_order
-- ----------------------------
DROP TABLE IF EXISTS `hj_order`;
CREATE TABLE `hj_order` (
`order_id` int(11) NOT NULL AUTO_INCREMENT,
`buyer_id` int(11) NULL DEFAULT NULL COMMENT '买家编号',
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '收货人姓名',
`seller_id` int(11) NULL DEFAULT NULL COMMENT '卖家编号',
`phone` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '电话号码',
`address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '收货地址',
`goods_id` int(11) NULL DEFAULT NULL COMMENT '商品编号',
`goods_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '商品名称',
`buy_number` int(11) NULL DEFAULT NULL COMMENT '商品数量',
`pay` int(11) NULL DEFAULT NULL COMMENT '支付金额',
`send_status` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '未发货' COMMENT '商品发货状态',
`receive_status` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '未收货' COMMENT '商品收货状态',
`picture` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '商品图片',
PRIMARY KEY (`order_id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 50 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of hj_order
-- ----------------------------
INSERT INTO `hj_order` VALUES (41, 89, '刘燕', 84, '13879003333', '湖北省武汉市555号', 21, '白色U盘', 1, 20, '未发货', '未收货', 'https://img12.360buyimg.com/n7/jfs/t1/125142/12/10776/80410/5f4473f0Eeed8da73/870f3709c4480751.jpg');
INSERT INTO `hj_order` VALUES (38, 85, '李明', 87, '13879001111', '江西省南昌市111号', 25, '无线充电套装', 1, 50, '未发货', '未收货', '/uploads/20210108/cc1770e74ba65cf7a49bbdecd0865c1c.jpg');
INSERT INTO `hj_order` VALUES (42, 84, '王红', 84, '13879002222', '北京市111号', 17, '黑色签字笔', 1, 1, '未发货', '未收货', 'https://cdn.cnbj0.fds.api.mi-img.com/b2c-shopapi-pms/pms_1559616366.16874615.jpg');
INSERT INTO `hj_order` VALUES (40, 89, '刘燕', 87, '13879003333', '湖北省武汉市555号', 26, '自拍杆', 1, 20, '未发货', '未收货', '/uploads/20210108/5b0b1d39583d32c9c7d2a7f5a07ff651.jpg');
INSERT INTO `hj_order` VALUES (37, 85, '张三峰', 84, '18079003333', '江西省华东交通大学1号', 20, 'ThinkPHP网站开发教程', 1, 15, '已发货', '未收货', 'https://img10.360buyimg.com/n1/s200x200_jfs/t1/137034/33/225/47746/5eca3b72Ec415a16b/38ba44c31adade76.jpg');
INSERT INTO `hj_order` VALUES (49, 85, '李明', 84, '13879001111', '江西省南昌市111号', 21, '白色U盘', 1, 20, '未发货', '未收货', 'https://img12.360buyimg.com/n7/jfs/t1/125142/12/10776/80410/5f4473f0Eeed8da73/870f3709c4480751.jpg');
-- ----------------------------
-- Table structure for hj_role
-- ----------------------------
DROP TABLE IF EXISTS `hj_role`;
CREATE TABLE `hj_role` (
`role_id` smallint(6) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
`menus` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`role_id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of hj_role
-- ----------------------------
INSERT INTO `hj_role` VALUES (2, '普通用户', '4,5,10,');
INSERT INTO `hj_role` VALUES (3, '店主', '4,5,7,8,9,10,');
-- ----------------------------
-- Table structure for hj_user
-- ----------------------------
DROP TABLE IF EXISTS `hj_user`;
CREATE TABLE `hj_user` (
`user_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '用户编号',
`user_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
`password` varchar(70) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '密码',
`real_name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '真实姓名',
`role_id` mediumint(8) NULL DEFAULT NULL COMMENT '角色编号',
`gender` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '性别',
`avatar` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '头像',
`phone` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '电话号码',
`address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '收货地址',
PRIMARY KEY (`user_id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 90 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '用户表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of hj_user
-- ----------------------------
INSERT INTO `hj_user` VALUES (87, 'seller2', 'e10adc3949ba59abbe56e057f20f883e', '胡帅', 3, '男', '', '13879004444', '上海市333号');
INSERT INTO `hj_user` VALUES (85, 'buyer1', 'e10adc3949ba59abbe56e057f20f883e', '李明', 2, '男', '/uploads/20201230/4016080765fb9e9a5bf68385f2d00358.jpg', '13879001111', '江西省南昌市111号');
INSERT INTO `hj_user` VALUES (84, 'seller1', 'e10adc3949ba59abbe56e057f20f883e', '王红', 3, '女', '', '13879002222', '北京市111号');
INSERT INTO `hj_user` VALUES (89, 'buyer2', 'e10adc3949ba59abbe56e057f20f883e', '刘燕', 2, '女', '', '13879003333', '湖北省武汉市555号');
-- ----------------------------
-- Table structure for sw_course
-- ----------------------------
DROP TABLE IF EXISTS `sw_course`;
CREATE TABLE `sw_course` (
`course_id` int(11) NOT NULL AUTO_INCREMENT,
`course_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '课程名',
`semester_id` int(22) NULL DEFAULT NULL COMMENT '学期',
`address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '上课地址',
`time` date NULL DEFAULT NULL COMMENT '上课时间',
`credit` int(11) NULL DEFAULT NULL COMMENT '学分',
`quantity` int(11) NULL DEFAULT NULL COMMENT '容量',
`selected_number` int(11) NULL DEFAULT 0 COMMENT '已选',
`rest_number` int(11) NULL DEFAULT NULL COMMENT '可选',
`user_id` int(10) NULL DEFAULT NULL COMMENT '任课教师',
`status` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '未开班' COMMENT '开班状态',
`select_status` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '未选课' COMMENT '选课状态',
PRIMARY KEY (`course_id`) USING BTREE,
INDEX `user_id`(`user_id`) USING BTREE,
INDEX `semester_id`(`semester_id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 27 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of sw_course
-- ----------------------------
INSERT INTO `sw_course` VALUES (20, '【1508100011】高等数学(A)Ⅰ', 1, '逸夫楼', '2021-06-16', 3, 120, 2, 118, 80, '已开班', '未选课');
INSERT INTO `sw_course` VALUES (18, '【1509100011】大学英语Ⅰ', 1, '明智楼', '2021-06-17', 4, 120, 14, 106, 81, '已开班', '已选课');
INSERT INTO `sw_course` VALUES (19, '【1508100311】大学物理Ⅰ', 2, '31栋', '2021-06-19', 4, 120, 3, 117, 82, '已开班', '已选课');
INSERT INTO `sw_course` VALUES (17, '【1506110890】离散数学', 3, '明智楼', '2021-06-14', 4, 120, 0, 120, 83, '未开班', '未选课');
INSERT INTO `sw_course` VALUES (16, '【1506110260】计算机网络', 4, '6栋', '2021-06-15', 4, 120, 1, 119, 84, '已开班', '未选课');
INSERT INTO `sw_course` VALUES (15, '【1506110900】数据结构', 3, '明智楼', '2021-06-19', 4, 120, 1, 119, 85, '已开班', '已选课');
INSERT INTO `sw_course` VALUES (14, '【1506110360】操作系统', 5, '逸夫楼', '2021-06-15', 4, 120, 0, 120, 86, '未开班', '未选课');
INSERT INTO `sw_course` VALUES (13, '【1506190130】软件工程', 6, '明智楼', '2021-06-18', 4, 120, 0, 120, 87, '未开班', '未选课');
INSERT INTO `sw_course` VALUES (12, '【1514190020】信息安全技术', 6, '逸夫楼', '2021-06-14', 4, 120, 1, 119, 83, '已开班', '已选课');
INSERT INTO `sw_course` VALUES (11, '【1506110880】编译原理', 6, '逸夫楼', '2021-06-15', 4, 120, 1, 119, 88, '已开班', '已选课');
INSERT INTO `sw_course` VALUES (22, '【1508100012】高等数学(A)Ⅱ', 2, '逸夫楼', '2021-06-16', 4, 40, 1, 39, 80, '已开班', '未选课');
INSERT INTO `sw_course` VALUES (24, '【1509101482】大学英语Ⅱ', 2, '明智楼', '2021-06-16', 4, 30, 2, 28, 81, '已开班', '未选课');
INSERT INTO `sw_course` VALUES (25, '【1506100050】程序设计基础(C语言)', 1, '逸夫楼101', '2021-06-25', 2, 80, 0, 80, 80, '已开班', '未选课');
INSERT INTO `sw_course` VALUES (26, '【1506100101】计算机基础', 1, '图书馆101', '2021-06-24', 3, 60, 0, 60, 80, '已开班', '未选课');
-- ----------------------------
-- Table structure for sw_menu
-- ----------------------------
DROP TABLE IF EXISTS `sw_menu`;
CREATE TABLE `sw_menu` (
`menu_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '菜单编号',
`url` varchar(80) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '菜单地址',
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '菜单名称',
`icon` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '图标',
`parent_id` int(5) NOT NULL DEFAULT 0 COMMENT '父栏目ID',
`sort` int(11) NULL DEFAULT 0 COMMENT '排序',
`visible` tinyint(1) NULL DEFAULT 1 COMMENT '是否可见',
`open` tinyint(1) NULL DEFAULT 1 COMMENT '是否展开',
PRIMARY KEY (`menu_id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 15 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of sw_menu
-- ----------------------------
INSERT INTO `sw_menu` VALUES (1, '', '系统功能', 'layui-icon-set', 0, 1, 1, 1);
INSERT INTO `sw_menu` VALUES (2, '/sw/role/index', '角色管理', NULL, 1, 1, 1, 1);
INSERT INTO `sw_menu` VALUES (3, '/sw/user/index', '用户管理', NULL, 1, 3, 1, 1);
INSERT INTO `sw_menu` VALUES (4, '', '选课管理', 'layui-icon-app', 0, 1, 1, 1);
INSERT INTO `sw_menu` VALUES (5, '/sw/course/index', '课程列表', NULL, 4, 1, 1, 1);
INSERT INTO `sw_menu` VALUES (6, '/sw/semester/index', '学期', NULL, 4, 1, 1, 1);
INSERT INTO `sw_menu` VALUES (7, '', '课程管理', 'layui-icon-home', 0, 1, 1, 1);
INSERT INTO `sw_menu` VALUES (8, '/sw/select/teacher_select', '选课学生列表', NULL, 7, 1, 1, 1);
INSERT INTO `sw_menu` VALUES (9, '/sw/course/teacher_form', '我的课程列表', NULL, 7, 1, 1, 1);
INSERT INTO `sw_menu` VALUES (10, '/sw/select/student_select', '已选课程列表', NULL, 4, 1, 1, 1);
INSERT INTO `sw_menu` VALUES (11, '', '成绩管理', 'layui-icon-read', 0, 1, 1, 1);
INSERT INTO `sw_menu` VALUES (12, '/sw/select/teacher_score', '班级成绩', NULL, 11, 1, 1, 1);
INSERT INTO `sw_menu` VALUES (13, '/sw/select/student_score', '我的成绩', NULL, 11, 1, 1, 1);
INSERT INTO `sw_menu` VALUES (14, '/sw/select/select', '选课列表', NULL, 7, 1, 1, 1);
-- ----------------------------
-- Table structure for sw_role
-- ----------------------------
DROP TABLE IF EXISTS `sw_role`;
CREATE TABLE `sw_role` (
`role_id` smallint(6) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
`role_key` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`menus` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`role_id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of sw_role
-- ----------------------------
INSERT INTO `sw_role` VALUES (1, 'admin', 'admin', '1,2,3,4,5,6,7,14,');
INSERT INTO `sw_role` VALUES (2, 'student', 'student', '4,5,10,11,13,');
INSERT INTO `sw_role` VALUES (3, 'teacher', 'teacher', '4,5,7,8,9,11,12,');
-- ----------------------------
-- Table structure for sw_select
-- ----------------------------
DROP TABLE IF EXISTS `sw_select`;
CREATE TABLE `sw_select` (
`select_id` int(11) NOT NULL AUTO_INCREMENT,
`student_id` int(11) NULL DEFAULT NULL COMMENT '学生编号',
`teacher_id` int(11) NULL DEFAULT NULL COMMENT '教师编号',
`course_id` int(11) NULL DEFAULT NULL COMMENT '课程编号',
`course_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '课程名称',
`semester_id` int(11) NULL DEFAULT NULL COMMENT '学期',
`address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '上课地址',
`time` date NULL DEFAULT NULL COMMENT '上课时间',
`credit` int(11) NULL DEFAULT NULL COMMENT '学分',
`score_status` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '未打分' COMMENT '分数状态',
`normal_score` int(5) NULL DEFAULT NULL COMMENT '平时成绩',
`test_score` int(5) NULL DEFAULT NULL COMMENT '考试成绩',
`total_score` int(5) NULL DEFAULT NULL COMMENT '总评分',
`grade_score` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '等级',
PRIMARY KEY (`select_id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 59 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of sw_select
-- ----------------------------
INSERT INTO `sw_select` VALUES (1, 91, 80, 20, '【1508100011】高等数学(A)Ⅰ', 1, '逸夫楼', '2021-06-16', 4, '已打分', 90, 90, 90, '优秀');
INSERT INTO `sw_select` VALUES (2, 92, 80, 20, '【1508100011】高等数学(A)Ⅰ', 1, '逸夫楼', '2021-06-16', 4, '未打分', NULL, NULL, NULL, NULL);
INSERT INTO `sw_select` VALUES (3, 91, 81, 18, '【1509100011】大学英语Ⅰ', 1, '明智楼', '2021-06-17', 4, '未打分', NULL, NULL, NULL, NULL);
INSERT INTO `sw_select` VALUES (52, 91, 83, 12, '【1514190020】信息安全技术', 6, '逸夫楼', '2021-06-14', 4, '未打分', NULL, NULL, NULL, NULL);
INSERT INTO `sw_select` VALUES (58, 80, 81, 18, '【1509100011】大学英语Ⅰ', 1, '明智楼', '2021-06-17', 4, '未打分', NULL, NULL, NULL, NULL);
INSERT INTO `sw_select` VALUES (49, 91, 84, 16, '【1506110260】计算机网络', 4, '6栋', '2021-06-15', 4, '未打分', NULL, NULL, NULL, NULL);
INSERT INTO `sw_select` VALUES (50, 91, 82, 19, '【1508100311】大学物理Ⅰ', 2, '31栋', '2021-06-19', 4, '未打分', NULL, NULL, NULL, NULL);
INSERT INTO `sw_select` VALUES (51, 91, 88, 11, '【1506110880】编译原理', 6, '逸夫楼', '2021-06-15', 4, '已打分', 65, 65, 65, '及格');
INSERT INTO `sw_select` VALUES (54, 91, 82, 19, '【1508100311】大学物理Ⅰ', 2, '31栋', '2021-06-19', 4, '未打分', NULL, NULL, NULL, NULL);
-- ----------------------------
-- Table structure for sw_semester
-- ----------------------------
DROP TABLE IF EXISTS `sw_semester`;
CREATE TABLE `sw_semester` (
`semester_id` int(11) NOT NULL AUTO_INCREMENT,
`semester_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`semester_id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 10 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of sw_semester
-- ----------------------------
INSERT INTO `sw_semester` VALUES (1, '2018-2019第一学期');
INSERT INTO `sw_semester` VALUES (2, '2018-2019第二学期');
INSERT INTO `sw_semester` VALUES (3, '2019-2020第一学期');
INSERT INTO `sw_semester` VALUES (4, '2019-2020第二学期');
INSERT INTO `sw_semester` VALUES (5, '2020-2021第一学期');
INSERT INTO `sw_semester` VALUES (6, '2020-2021第二学期');
INSERT INTO `sw_semester` VALUES (7, '2021-2022第一学期');
INSERT INTO `sw_semester` VALUES (8, '2021-2022第二学期');
-- ----------------------------
-- Table structure for sw_user
-- ----------------------------
DROP TABLE IF EXISTS `sw_user`;
CREATE TABLE `sw_user` (
`user_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '用户编号',
`user_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
`password` varchar(70) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '密码',
`real_name` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '真实姓名',
`role_id` mediumint(8) NULL DEFAULT NULL COMMENT '角色编号',
`gender` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '性别',
`avatar` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '头像',
`phone` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '电话号码',
`address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '江西南昌' COMMENT '家庭地址',
`status` tinyint(2) NULL DEFAULT 1,
`login_time` int(11) NULL DEFAULT NULL,
`online` int(11) NULL DEFAULT 0,
`company` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`identity` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`user_id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 95 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '用户表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of sw_user
-- ----------------------------
INSERT INTO `sw_user` VALUES (80, '2001', 'e10adc3949ba59abbe56e057f20f883e', '左黎明', 3, '男', '/uploads/20210616/7e3b52b4388fdf582b50b49b8e9fe617.png', '18079014431', '江西赣州', 1, 1625822506, 1, '信息工程学院', '教授');
INSERT INTO `sw_user` VALUES (81, '2002', 'e10adc3949ba59abbe56e057f20f883e', '李宗', 3, '女', '/uploads/20210617/b8e0f726a7a904edd57a0aeaa776d5fa.png', '11111111111', '江西南昌', 1, 1624034162, 0, '信息工程学院', '讲师');
INSERT INTO `sw_user` VALUES (82, '2003', 'e10adc3949ba59abbe56e057f20f883e', '刘正方', 3, '男', NULL, '18079002222', '江西南昌', 1, NULL, 0, '信息工程学院', '副教授');
INSERT INTO `sw_user` VALUES (83, '2004', 'e10adc3949ba59abbe56e057f20f883e', '万涛', 3, '女', NULL, '18079001111', '江西南昌', 1, NULL, 0, '信息工程学院', '副教授');
INSERT INTO `sw_user` VALUES (84, '2005', 'e10adc3949ba59abbe56e057f20f883e', '谢昕', 3, '男', '/uploads/20201230/a11502d2fc1026fdb0397364a153093f.jpg', '19970720985', '江西赣州', 1, NULL, 0, '信息工程学院', '教授');
INSERT INTO `sw_user` VALUES (85, '2006', 'e10adc3949ba59abbe56e057f20f883e', '刘艳丽', 3, '女', '/uploads/20210109/fe8ec829606d2260f9dc3a8a3e489027.jpg', '19970720985', '江西赣州于都', 1, NULL, 0, '信息工程学院', '教授');
INSERT INTO `sw_user` VALUES (86, '2007', 'e10adc3949ba59abbe56e057f20f883e', '刘美香', 3, '女', NULL, '11111111113', '江西南昌', 1, NULL, 0, '信息工程学院', '讲师');
INSERT INTO `sw_user` VALUES (87, '2008', 'e10adc3949ba59abbe56e057f20f883e', '舒文豪', 3, '女', '/uploads/20201230/a11502d2fc1026fdb0397364a153093f.jpg', '19970720985', '江西赣州', 1, NULL, 0, '信息工程学院', '副教授');
INSERT INTO `sw_user` VALUES (88, '2009', 'e10adc3949ba59abbe56e057f20f883e', '邹长军', 3, '男', '/uploads/20201230/a11502d2fc1026fdb0397364a153093f.jpg', '19970720985', '江西赣州', 1, 1624503768, 0, '信息工程学院', '讲师');
INSERT INTO `sw_user` VALUES (91, '2018061008000401', 'e10adc3949ba59abbe56e057f20f883e', '小胡', 2, '男', '/uploads/20210625/1191a754a8d23e78f25c976a7107a955.jpg', '18079014431', '江西新余', 1, 1624618313, 1, '信息工程学院', '本专科生');
INSERT INTO `sw_user` VALUES (92, '2018061008000402', 'e10adc3949ba59abbe56e057f20f883e', '小承', 2, '女', NULL, '12333532354', '江西赣州', 1, 1624034140, 0, '信息工程学院', '本专科生');
INSERT INTO `sw_user` VALUES (93, 'admin', 'e10adc3949ba59abbe56e057f20f883e', 'admin', 1, '男', NULL, '19023456879', '江西赣州', 1, 1624698237, 1, '信息工程学院', '管理员');
INSERT INTO `sw_user` VALUES (94, '123', '202cb962ac59075b964b07152d234b70', NULL, 2, '', NULL, '11111111118', '江西南昌', 1, NULL, 0, NULL, NULL);
SET FOREIGN_KEY_CHECKS = 1;
| 65.238095 | 232 | 0.663718 |
d1c3b7b35fc90da2b462faf8a1838db04649f99a
| 308 |
rs
|
Rust
|
terraria-protocol/src/packets/sync_extra_value.rs
|
annihilatorrrr/terry
|
d17e029eebd7ef21c7e8b8eac42a838376d64fad
|
[
"Apache-2.0",
"MIT"
] | 8 |
2020-07-09T21:34:30.000Z
|
2022-01-19T09:59:26.000Z
|
terraria-protocol/src/packets/sync_extra_value.rs
|
annihilatorrrr/terry
|
d17e029eebd7ef21c7e8b8eac42a838376d64fad
|
[
"Apache-2.0",
"MIT"
] | 3 |
2021-06-27T11:18:14.000Z
|
2021-10-03T11:24:02.000Z
|
terraria-protocol/src/packets/sync_extra_value.rs
|
annihilatorrrr/terry
|
d17e029eebd7ef21c7e8b8eac42a838376d64fad
|
[
"Apache-2.0",
"MIT"
] | 8 |
2020-07-14T08:40:10.000Z
|
2021-12-14T15:27:29.000Z
|
use crate::serde::packet_struct;
use crate::structures::Vec2;
packet_struct! {
/// Sync an extra value.
///
/// Direction: Server <-> Client (Sync).
pub struct SyncExtraValue {
const TAG = 92;
pub npc_index: u16,
pub extra_value: i32,
pub pos: Vec2,
}
}
| 19.25 | 44 | 0.574675 |
43998fdc33c60fef19e2c8f6867383e734085ebb
| 282 |
go
|
Go
|
parser/generator_test.go
|
haklop/bazooka
|
616e5a8ddba9ab22c725b9c4f55073204c670840
|
[
"MIT"
] | 72 |
2015-02-26T14:55:04.000Z
|
2022-03-13T10:40:11.000Z
|
parser/generator_test.go
|
haklop/bazooka
|
616e5a8ddba9ab22c725b9c4f55073204c670840
|
[
"MIT"
] | 121 |
2015-02-26T13:27:53.000Z
|
2019-02-01T11:05:23.000Z
|
parser/generator_test.go
|
haklop/bazooka
|
616e5a8ddba9ab22c725b9c4f55073204c670840
|
[
"MIT"
] | 5 |
2015-04-18T08:02:58.000Z
|
2019-09-09T19:20:48.000Z
|
package main
import (
"testing"
"text/template"
)
func TestParseTemplate(t *testing.T) {
template.Must(template.ParseFiles("template/bazooka_phase.sh"))
template.Must(template.ParseFiles("template/bazooka_run.sh"))
template.Must(template.ParseFiles("template/Dockerfile"))
}
| 21.692308 | 64 | 0.77305 |
c41a05b41f7b4fe9752387216be9014b7d867dec
| 2,177 |
h
|
C
|
firmware/CellularTCPIP_SIM800.h
|
tzurolo/Water-Tank-Display
|
4ff9bd102ffa00f3b0057647cf8a4d13e682add0
|
[
"MIT"
] | null | null | null |
firmware/CellularTCPIP_SIM800.h
|
tzurolo/Water-Tank-Display
|
4ff9bd102ffa00f3b0057647cf8a4d13e682add0
|
[
"MIT"
] | null | null | null |
firmware/CellularTCPIP_SIM800.h
|
tzurolo/Water-Tank-Display
|
4ff9bd102ffa00f3b0057647cf8a4d13e682add0
|
[
"MIT"
] | null | null | null |
//
// Cellular Communications, TCP/IP sesssions for SIM800
//
// You can poll for connection status using CellularTCPIP_connectionStatus() or
// you can use the callback you pass to the connect function.
//
#ifndef CELLULARTCPIP_H
#define CELLULARTCPIP_H
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#include <avr/pgmspace.h>
#include "CharString.h"
#include "SIM800.h"
// TCP/IP connection status
typedef enum CellularTCPIPConnectionStatus_enum {
cs_connecting,
cs_connected,
cs_sendingData,
cs_disconnecting,
cs_disconnected
} CellularTCPIPConnectionStatus;
// prototypes for functions that clients supply to
// provide and receive data
typedef bool (*CellularTCPIP_DataProvider)(void); // return true when done
typedef void (*CellularTCPIP_SendCompletionCallback)(const bool success);
typedef void (*CellularTCPIP_ConnectionStateChangeCallback)(const CellularTCPIPConnectionStatus status);
extern void CellularTCPIP_Initialize (void);
extern CellularTCPIPConnectionStatus CellularTCPIP_connectionStatus (void);
extern void CellularTCPIP_connect (
const CharString_t *hostAddress,
const uint16_t hostPort,
SIM800_IPDataCallback receiver, // will be called when data from host arrives
CellularTCPIP_ConnectionStateChangeCallback stateChangeCallback);
extern void CellularTCPIP_sendData (
CellularTCPIP_DataProvider provider, // will be called to write data
CellularTCPIP_SendCompletionCallback completionCallback);
extern void CellularTCPIP_disconnect (void);
extern void CellularTCPIP_notifyConnectionClosed (void);
extern bool CellularTCPIP_hasSubtaskWorkToDo (void);
extern void CellularTCPIP_Subtask (void);
extern int CellularTCPIP_state (void);
// these functions are to be called only by DataProvider
// functions
extern uint16_t CellularTCPIP_availableSpaceForWriteData (void);
extern void CellularTCPIP_writeDataP (
PGM_P data);
extern void CellularTCPIP_writeDataCS (
CharString_t *data);
extern void CellularTCPIP_writeDataCSS (
CharStringSpan_t *data);
#endif // CELLULARTCPIP_H
| 32.014706 | 105 | 0.776298 |
f00829ce69ca21d2a75d867579f5065b5c43824d
| 395 |
py
|
Python
|
lib/locator/location_test.py
|
alt-locator/address-locator-python
|
9f052dc7721223bde926723648790a17b06e9d7a
|
[
"MIT"
] | null | null | null |
lib/locator/location_test.py
|
alt-locator/address-locator-python
|
9f052dc7721223bde926723648790a17b06e9d7a
|
[
"MIT"
] | null | null | null |
lib/locator/location_test.py
|
alt-locator/address-locator-python
|
9f052dc7721223bde926723648790a17b06e9d7a
|
[
"MIT"
] | null | null | null |
import location
import unittest
class LocationTest(unittest.TestCase):
def testToJson(self):
test_location = location.Location(name='foo',
local_ip_address={'en0': {'local_ip_address': '1.2.3.4'}})
test_json = test_location.to_json()
self.assertEqual(test_json['name'], 'foo')
self.assertEqual(test_json['local_ip_address']['en0']['local_ip_address'],
'1.2.3.4')
| 30.384615 | 78 | 0.698734 |
98955a0b5198154ca8aed79f178970d92fe263fe
| 432 |
html
|
HTML
|
src/app/components/ui-elements/toolbar-navigation/toolbar-navigation-menu/toolbar-navigation-menu.component.html
|
wilsonsergio2500/fogo-cms
|
1eeba260b9175d03da9f1d6393d96c39adadee95
|
[
"MIT"
] | null | null | null |
src/app/components/ui-elements/toolbar-navigation/toolbar-navigation-menu/toolbar-navigation-menu.component.html
|
wilsonsergio2500/fogo-cms
|
1eeba260b9175d03da9f1d6393d96c39adadee95
|
[
"MIT"
] | 1 |
2021-12-26T21:32:30.000Z
|
2021-12-26T21:32:30.000Z
|
src/app/components/ui-elements/toolbar-navigation/toolbar-navigation-menu/toolbar-navigation-menu.component.html
|
wilsonsergio2500/fogo-cms
|
1eeba260b9175d03da9f1d6393d96c39adadee95
|
[
"MIT"
] | 1 |
2022-01-05T04:35:26.000Z
|
2022-01-05T04:35:26.000Z
|
<mat-menu #menu>
<ng-container *ngFor="let item of navigations">
<a *ngIf="!item.children?.length; else branch" routerLink="{{item.Url}}" mat-menu-item>{{item.Label}}</a>
<ng-template #branch>
<a mat-menu-item [matMenuTriggerFor]="innerPanel.menu">{{item.Label}}</a>
<toolbar-navigation-menu #innerPanel [navigations]="item.children"></toolbar-navigation-menu>
</ng-template>
</ng-container>
</mat-menu>
| 43.2 | 109 | 0.671296 |
c16ceeec6201e4f54d20f9700d90b73c8cbd98c6
| 2,525 |
lua
|
Lua
|
plugins/easymedikit/sv_hooks.lua
|
Frosty1940/helix-hl2rp
|
0c14c75cc7502164b3989d173d7a149e683eda56
|
[
"MIT"
] | null | null | null |
plugins/easymedikit/sv_hooks.lua
|
Frosty1940/helix-hl2rp
|
0c14c75cc7502164b3989d173d7a149e683eda56
|
[
"MIT"
] | null | null | null |
plugins/easymedikit/sv_hooks.lua
|
Frosty1940/helix-hl2rp
|
0c14c75cc7502164b3989d173d7a149e683eda56
|
[
"MIT"
] | null | null | null |
local PLUGIN = PLUGIN
PLUGIN.BulletDamages = {
[DMG_BULLET] = true,
[DMG_SLASH] = true,
[DMG_BLAST] = true,
[DMG_AIRBOAT] = true,
[DMG_BUCKSHOT] = true,
[DMG_SNIPER] = true,
[DMG_MISSILEDEFENSE] = true
}
function PLUGIN:EntityTakeDamage(target, info)
if ( target:IsValid() and target:IsPlayer() ) then
if ( self.BulletDamages[info:GetDamageType()] and target:Armor() < 0 ) then
if ( math.random(10) > 7 ) then
self:SetBleeding(target, true)
end
elseif ( info:GetDamageType() == DMG_FALL and target:Team() != FACTION_OTA ) then
if math.random(10) > 7 then
self:SetFracture(target, true)
end
end
end
end
function PLUGIN:PlayerLoadedCharacter(client, character)
if (!character:GetFracture()) then
self:SetFracture(client, false)
end
if (!character:GetBleeding()) then
self:SetBleeding(client, false)
end
if (character:GetFracture()) then
self:SetFracture(client, true)
end
if (character:GetBleeding()) then
self:SetBleeding(client, true)
end
end
function PLUGIN:SetBleeding(client, status)
local character = client:GetCharacter()
local bStatus = hook.Run("CanCharacterGetBleeding", client, character)
if (bStatus) then return end
character:SetBleeding(status)
if (status) then
timer.Create("bleeding."..client:AccountID(), 7, 0, function()
if IsValid(client) and character then
client:SetHealth( client:Health() - math.random(3) )
client:ScreenFade( SCREENFADE.IN, Color(255, 0, 0, 128), 0.3, 0 )
if (client:Health() <= 0) then
client:Kill()
self:ClearWounds(client)
elseif (client:Health() >= client:GetMaxHealth()) then
self:ClearWounds(client)
end
end
end)
else
if timer.Exists("bleeding."..client:AccountID()) then
timer.Remove("bleeding."..client:AccountID())
end
end
end
function PLUGIN:SetFracture(client, status)
local character = client:GetCharacter()
local bStatus = hook.Run("CanCharacterGetFracture", client, character)
if (bStatus) then return end
character:SetFracture(status)
if (status) then
client:SetWalkSpeed(ix.config.Get("walkSpeed", 100) / 1.4)
client:SetRunSpeed(ix.config.Get("walkSpeed", 100) / 1.4)
else
client:SetWalkSpeed(ix.config.Get("walkSpeed"))
client:SetRunSpeed(ix.config.Get("runSpeed"))
end
end
function PLUGIN:ClearWounds(client)
self:SetFracture(client, false)
self:SetBleeding(client, false)
end
function PLUGIN:DoPlayerDeath(client)
self:ClearWounds(client)
end
function PLUGIN:PlayerDeath(client)
self:ClearWounds(client)
end
| 25.505051 | 83 | 0.716832 |
e9dd366c5c2991ca31f4412a4046e939cc1940f2
| 714 |
rb
|
Ruby
|
lib/acapi/config.rb
|
ideacrew/acapi
|
8f4b6cf53d7eb98f331c722bbcdf8e21aa265a76
|
[
"MIT"
] | 2 |
2015-04-01T19:00:07.000Z
|
2018-06-22T20:21:45.000Z
|
lib/acapi/config.rb
|
ideacrew/acapi
|
8f4b6cf53d7eb98f331c722bbcdf8e21aa265a76
|
[
"MIT"
] | null | null | null |
lib/acapi/config.rb
|
ideacrew/acapi
|
8f4b6cf53d7eb98f331c722bbcdf8e21aa265a76
|
[
"MIT"
] | 3 |
2015-06-14T04:27:13.000Z
|
2017-08-09T20:49:36.000Z
|
require "acapi/config/environment"
# require "acapi/config/options"
module Acapi
module Config
extend self
def load!(path, environment = nil)
settings = Environment.load_yaml(path, environment)
if settings.present?
load_configuration(settings)
end
settings
end
def load_configuration(settings)
configuration = settings.with_indifferent_access
self.options = configuration[:options]
self.sessions = configuration[:sessions]
end
def options=(options)
if options
options.each_pair do |option, value|
Validators::Option.validate(option)
send("#{option}=", value)
end
end
end
end
end
| 21.636364 | 57 | 0.654062 |
e9147cf4bcc0292e88382d6f3ee6df51daa6215d
| 1,947 |
rb
|
Ruby
|
spec/flight_radar_spec.rb
|
kupolak/flight_radar
|
673bc47d18f0b8b47b010ecc605ac922d94c8580
|
[
"MIT"
] | null | null | null |
spec/flight_radar_spec.rb
|
kupolak/flight_radar
|
673bc47d18f0b8b47b010ecc605ac922d94c8580
|
[
"MIT"
] | null | null | null |
spec/flight_radar_spec.rb
|
kupolak/flight_radar
|
673bc47d18f0b8b47b010ecc605ac922d94c8580
|
[
"MIT"
] | null | null | null |
# frozen_string_literal: true
require "spec_helper"
RSpec.describe FlightRadar do
it "gets airlines" do
result = FlightRadar.airlines
expect(result.count).to be >= 100
end
it "gets airports" do
airports = FlightRadar.airports
expect(airports.count).to be > 4000
end
it "gets airport" do
airports = %w[ATL LAX DXB DFW]
count = 0
airports.each do |airport|
count += 1 if FlightRadar.airport(airport) != {}
end
expect(count).to be >= 3
end
it "gets zones" do
result = FlightRadar.zones
check = %w[europe northamerica southamerica oceania asia africa atlantic maldives northatlantic].all? do |s|
result.key? s
end
expect(check).to be_truthy
end
it "gets flights" do
result = FlightRadar.flights
expect(result.count).to be >= 100
end
it "gets flight details" do
flight = FlightRadar.flights
flight = flight.sample
flight_details = FlightRadar.flight_details(flight.id)
expect(flight_details["identification"]["id"]).to be == flight.id
end
it "gets flights by airline" do
airlines = %w[SWA GLO AZU UAL THY]
count = 0
airlines.each do |airline|
count += 1 if FlightRadar.flights(airline: airline)
end
expect(count).to be >= 3
end
it "gets flights by bounds" do
zone = FlightRadar.zones["europe"]
bounds = FlightRadar.bounds(zone)
result = FlightRadar.flights(bounds: bounds)
expect(result.count).to be >= 30
end
it "gets airline logo" do
airline = [%w[WN SWA], %w[G3 GLO], %w[AD AZU], %w[AA AAL], %w[TK THY]].sample
logo = FlightRadar.airline_logo(airline[0], airline[1])
expect(logo[0]).to_not be nil
expect(logo[1]).to_not be nil
end
it "gets country flag" do
country = "United States"
flag_url = FlightRadar.country_flag(country)
expect(flag_url).to eq "https://www.flightradar24.com/static/images/data/flags-small/united-states.gif"
end
end
| 26.310811 | 112 | 0.671803 |
b2fdd34a89c4f597f4f4706f3635728cd6c36c6a
| 2,827 |
py
|
Python
|
train_utils.py
|
BatyrM/QL-Net
|
b245aadeb106810d075064137f26d773b2dbd679
|
[
"MIT"
] | null | null | null |
train_utils.py
|
BatyrM/QL-Net
|
b245aadeb106810d075064137f26d773b2dbd679
|
[
"MIT"
] | null | null | null |
train_utils.py
|
BatyrM/QL-Net
|
b245aadeb106810d075064137f26d773b2dbd679
|
[
"MIT"
] | null | null | null |
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).sum(0)
res.append(100*correct_k/batch_size)
return res
def adjust_learning_rate(lr, optimizer, epoch):
"""Sets the learning rate to the initial LR decayed by 10 after 3 and 6 epochs"""
lr = lr * (0.1 ** (epoch // 6))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def train(net,trainloader, testloader, num_epoch, lr, device):
criterion = nn.CrossEntropyLoss() #
optimizer = optim.SGD(net.parameters(), lr=lr, momentum=0.9, weight_decay=5e-4)
best = 0.0
for epoch in range(num_epoch): # loop over the dataset multiple times
net.train()
adjust_learning_rate(lr, optimizer, epoch)
running_loss = 0.0
for i, (inputs, labels) in enumerate(trainloader, 0):
inputs = inputs.to(device)
labels = labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
prec1 = accuracy(outputs.data, labels, topk=(1,))[0]
if i % 30 == 0: # print every 2 mini-batches
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}\tAccuracy: {:.2f}'.format(
epoch, i * len(inputs), len(trainloader.dataset),
100. * i / len(trainloader), loss.item(), prec1.item()))
print("----- Validation ----------")
score = test(net, testloader, device)
if score > best:
print("Saving model")
torch.save(net.state_dict(), 'mnist_baseline.pth')
best = score
print("---------------------------")
print('Finished Training')
return net
def test(net, testloader, device):
net.eval()
correct = 0.0
total = 0.0
i = 0.0
for (images, labels) in testloader:
images, labels = images.to(device), labels.to(device)
with torch.no_grad():
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum()
i=i+1.0
accuracy = 100.0 * correct.item() / total
print('Accuracy of the network on the 10000 test images: %.2f %%' % (accuracy))
return accuracy
| 36.714286 | 97 | 0.573753 |
d53b0c9051915c1223dcd291230166274cc27b46
| 4,232 |
sql
|
SQL
|
db/schema.sql
|
gabiseabra/hs-picturefarm
|
f8440c75216815f2cd8e4202c0997e4811622a75
|
[
"BSD-3-Clause"
] | 3 |
2020-02-27T15:36:48.000Z
|
2021-04-22T01:57:21.000Z
|
db/schema.sql
|
gabiseabra/hs-picturefarm
|
f8440c75216815f2cd8e4202c0997e4811622a75
|
[
"BSD-3-Clause"
] | null | null | null |
db/schema.sql
|
gabiseabra/hs-picturefarm
|
f8440c75216815f2cd8e4202c0997e4811622a75
|
[
"BSD-3-Clause"
] | null | null | null |
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
--
-- Name: uuid-ossp; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;
--
-- Name: EXTENSION "uuid-ossp"; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION "uuid-ossp" IS 'generate universally unique identifiers (UUIDs)';
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: picture_tags; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.picture_tags (
picture_uuid uuid NOT NULL,
tag character varying NOT NULL
);
--
-- Name: pictures; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.pictures (
id integer NOT NULL,
uuid uuid DEFAULT public.uuid_generate_v4() NOT NULL,
file_name character varying NOT NULL,
file_hash character(32) NOT NULL,
url character varying NOT NULL,
mime_type character varying NOT NULL,
created_at timestamp(6) without time zone DEFAULT now() NOT NULL,
updated_at timestamp(6) without time zone DEFAULT now() NOT NULL,
resource_type character varying
);
--
-- Name: pictures_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--
CREATE SEQUENCE public.pictures_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
--
-- Name: pictures_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--
ALTER SEQUENCE public.pictures_id_seq OWNED BY public.pictures.id;
--
-- Name: schema_migrations; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.schema_migrations (
version character varying(255) NOT NULL
);
--
-- Name: tag_aliases; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.tag_aliases (
tag character varying NOT NULL,
alias character varying NOT NULL,
created_at timestamp(6) without time zone DEFAULT now() NOT NULL,
updated_at timestamp(6) without time zone DEFAULT now() NOT NULL
);
--
-- Name: pictures id; Type: DEFAULT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.pictures ALTER COLUMN id SET DEFAULT nextval('public.pictures_id_seq'::regclass);
--
-- Name: picture_tags picture_tags_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.picture_tags
ADD CONSTRAINT picture_tags_pkey PRIMARY KEY (picture_uuid, tag);
--
-- Name: pictures pictures_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.pictures
ADD CONSTRAINT pictures_pkey PRIMARY KEY (id);
--
-- Name: pictures pictures_uuid_key; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.pictures
ADD CONSTRAINT pictures_uuid_key UNIQUE (uuid);
--
-- Name: schema_migrations schema_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.schema_migrations
ADD CONSTRAINT schema_migrations_pkey PRIMARY KEY (version);
--
-- Name: tag_aliases tag_aliases_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.tag_aliases
ADD CONSTRAINT tag_aliases_pkey PRIMARY KEY (tag, alias);
--
-- Name: pictures_file_name_idx; Type: INDEX; Schema: public; Owner: -
--
CREATE INDEX pictures_file_name_idx ON public.pictures USING btree (file_name);
--
-- Name: picture_tags picture_tags_picture_uuid_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.picture_tags
ADD CONSTRAINT picture_tags_picture_uuid_fkey FOREIGN KEY (picture_uuid) REFERENCES public.pictures(uuid);
--
-- PostgreSQL database dump complete
--
--
-- Dbmate schema migrations
--
INSERT INTO public.schema_migrations (version) VALUES
('20200125213105'),
('20200125213320'),
('20200125213531'),
('20200223083851');
| 22.631016 | 110 | 0.725662 |
3e70634f44bcb23bf0bd42868426660d485ce647
| 94,454 |
c
|
C
|
sdktools/debuggers/imagehlp/walkx86.c
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17 |
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
sdktools/debuggers/imagehlp/walkx86.c
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2 |
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
sdktools/debuggers/imagehlp/walkx86.c
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14 |
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
/*++
Copyright (c) 1993-2002 Microsoft Corporation
Module Name:
walkx86.c
Abstract:
This file implements the Intel x86 stack walking api. This api allows for
the presence of "real mode" stack frames. This means that you can trace
into WOW code.
Author:
Wesley Witt (wesw) 1-Oct-1993
Environment:
User Mode
--*/
#define _IMAGEHLP_SOURCE_
#include <nt.h>
#include <ntrtl.h>
#include <nturtl.h>
#include "private.h"
#define NOEXTAPI
#include "wdbgexts.h"
#include "ntdbg.h"
#include <objbase.h>
#include <wx86dll.h>
#include <symbols.h>
#include <globals.h>
#include "dia2.h"
#define WDB(Args) SdbOut Args
#define SAVE_EBP(f) (f->Reserved[0])
#define IS_EBP_SAVED(f) (f->Reserved[0] && ((f->Reserved[0] >> 32) != 0xEB))
#define TRAP_TSS(f) (f->Reserved[1])
#define TRAP_EDITED(f) (f->Reserved[1])
#define SAVE_TRAP(f) (f->Reserved[2])
#define CALLBACK_STACK(f) (f->KdHelp.ThCallbackStack)
#define CALLBACK_NEXT(f) (f->KdHelp.NextCallback)
#define CALLBACK_FUNC(f) (f->KdHelp.KiCallUserMode)
#define CALLBACK_THREAD(f) (f->KdHelp.Thread)
#define CALLBACK_FP(f) (f->KdHelp.FramePointer)
#define CALLBACK_DISPATCHER(f) (f->KdHelp.KeUserCallbackDispatcher)
#define SYSTEM_RANGE_START(f) (f->KdHelp.SystemRangeStart)
#define STACK_SIZE (sizeof(DWORD))
#define FRAME_SIZE (STACK_SIZE * 2)
#define STACK_SIZE16 (sizeof(WORD))
#define FRAME_SIZE16 (STACK_SIZE16 * 2)
#define FRAME_SIZE1632 (STACK_SIZE16 * 3)
#define MAX_STACK_SEARCH 64 // in STACK_SIZE units
#define MAX_JMP_CHAIN 64 // in STACK_SIZE units
#define MAX_CALL 7 // in bytes
#define MIN_CALL 2 // in bytes
#define MAX_FUNC_PROLOGUE 64 // in bytes
#define PUSHBP 0x55
#define MOVBPSP 0xEC8B
ULONG g_vc7fpo = 1;
#define DoMemoryRead(addr,buf,sz,br) \
ReadMemoryInternal( Process, Thread, addr, buf, sz, \
br, ReadMemory, TranslateAddress, FALSE )
#define DoMemoryReadAll(addr,buf,sz) \
ReadMemoryInternal( Process, Thread, addr, buf, sz, \
NULL, ReadMemory, TranslateAddress, TRUE )
BOOL
WalkX86Init(
HANDLE Process,
HANDLE Thread,
LPSTACKFRAME64 StackFrame,
PX86_CONTEXT ContextRecord,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccess,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
);
BOOL
WalkX86Next(
HANDLE Process,
HANDLE Thread,
LPSTACKFRAME64 StackFrame,
PX86_CONTEXT ContextRecord,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccess,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
);
BOOL
ReadMemoryInternal(
HANDLE Process,
HANDLE Thread,
LPADDRESS64 lpBaseAddress,
LPVOID lpBuffer,
DWORD nSize,
LPDWORD lpNumberOfBytesRead,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress,
BOOL MustReadAll
);
BOOL
IsFarCall(
HANDLE Process,
HANDLE Thread,
LPSTACKFRAME64 StackFrame,
BOOL *Ok,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
);
BOOL
ReadTrapFrame(
HANDLE Process,
DWORD64 TrapFrameAddress,
PX86_KTRAP_FRAME TrapFrame,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory
);
BOOL
TaskGate2TrapFrame(
HANDLE Process,
USHORT TaskRegister,
PX86_KTRAP_FRAME TrapFrame,
PULONG64 off,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory
);
DWORD64
SearchForReturnAddress(
HANDLE Process,
DWORD64 uoffStack,
DWORD64 funcAddr,
DWORD funcSize,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase,
BOOL AcceptUnreadableCallSite
);
//----------------------------------------------------------------------------
//
// DIA IDiaStackWalkFrame implementation.
//
//----------------------------------------------------------------------------
class X86WalkFrame : public IDiaStackWalkFrame
{
public:
X86WalkFrame(HANDLE Process,
X86_CONTEXT* Context,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase,
PFPO_DATA PreviousFpo)
{
m_Process = Process;
m_Context = Context;
m_ReadMemory = ReadMemory;
m_GetModuleBase = GetModuleBase;
m_Locals = 0;
m_Params = 0;
m_VirtFrame = Context->Ebp;
m_PreviousFpo = PreviousFpo;
m_EbpSet = FALSE;
}
// IUnknown.
STDMETHOD(QueryInterface)(
THIS_
IN REFIID InterfaceId,
OUT PVOID* Interface
);
STDMETHOD_(ULONG, AddRef)(
THIS
);
STDMETHOD_(ULONG, Release)(
THIS
);
// IDiaStackWalkFrame.
STDMETHOD(get_registerValue)(DWORD reg, ULONGLONG* pValue);
STDMETHOD(put_registerValue)(DWORD reg, ULONGLONG value);
STDMETHOD(readMemory)(ULONGLONG va, DWORD cbData,
DWORD* pcbData, BYTE* data);
STDMETHOD(searchForReturnAddress)(IDiaFrameData* frame,
ULONGLONG* pResult);
STDMETHOD(searchForReturnAddressStart)(IDiaFrameData* frame,
ULONGLONG startAddress,
ULONGLONG* pResult);
BOOL WasEbpSet(void)
{
return m_EbpSet;
}
private:
HANDLE m_Process;
X86_CONTEXT* m_Context;
PREAD_PROCESS_MEMORY_ROUTINE64 m_ReadMemory;
PGET_MODULE_BASE_ROUTINE64 m_GetModuleBase;
ULONGLONG m_Locals;
ULONGLONG m_Params;
ULONGLONG m_VirtFrame;
PFPO_DATA m_PreviousFpo;
BOOL m_EbpSet;
};
STDMETHODIMP
X86WalkFrame::QueryInterface(
THIS_
IN REFIID InterfaceId,
OUT PVOID* Interface
)
{
HRESULT Status;
*Interface = NULL;
Status = E_NOINTERFACE;
if (IsEqualIID(InterfaceId, IID_IDiaStackWalkFrame)) {
*Interface = (IDiaStackWalkFrame*)this;
Status = S_OK;
}
return Status;
}
STDMETHODIMP_(ULONG)
X86WalkFrame::AddRef(
THIS
)
{
// Stack allocated, no refcount.
return 1;
}
STDMETHODIMP_(ULONG)
X86WalkFrame::Release(
THIS
)
{
// Stack allocated, no refcount.
return 0;
}
STDMETHODIMP
X86WalkFrame::get_registerValue( DWORD reg, ULONGLONG* pVal )
{
switch( reg ) {
// debug registers
case CV_REG_DR0:
*pVal = m_Context->Dr0;
break;
case CV_REG_DR1:
*pVal = m_Context->Dr1;
break;
case CV_REG_DR2:
*pVal = m_Context->Dr2;
break;
case CV_REG_DR3:
*pVal = m_Context->Dr3;
break;
case CV_REG_DR6:
*pVal = m_Context->Dr6;
break;
case CV_REG_DR7:
*pVal = m_Context->Dr7;
break;
// segment registers
case CV_REG_GS:
*pVal = m_Context->SegGs;
break;
case CV_REG_FS:
*pVal = m_Context->SegFs;
break;
case CV_REG_ES:
*pVal = m_Context->SegEs;
break;
case CV_REG_DS:
*pVal = m_Context->SegDs;
break;
// integer registers
case CV_REG_EDI:
*pVal = m_Context->Edi;
break;
case CV_REG_ESI:
*pVal = m_Context->Esi;
break;
case CV_REG_EBX:
*pVal = m_Context->Ebx;
break;
case CV_REG_EDX:
*pVal = m_Context->Edx;
break;
case CV_REG_ECX:
*pVal = m_Context->Ecx;
break;
case CV_REG_EAX:
*pVal = m_Context->Eax;
break;
// control registers
case CV_REG_EBP:
*pVal = m_Context->Ebp;
break;
case CV_REG_EIP:
*pVal = m_Context->Eip;
break;
case CV_REG_CS:
*pVal = m_Context->SegCs;
break;
case CV_REG_EFLAGS:
*pVal = m_Context->EFlags;
break;
case CV_REG_ESP:
*pVal = m_Context->Esp;
break;
case CV_REG_SS:
*pVal = m_Context->SegSs;
break;
case CV_ALLREG_LOCALS:
*pVal = m_Locals;
break;
case CV_ALLREG_PARAMS:
*pVal = m_Params;
break;
case CV_ALLREG_VFRAME:
*pVal = m_VirtFrame;
break;
default:
*pVal = 0;
return E_FAIL;
}
return S_OK;
}
STDMETHODIMP
X86WalkFrame::put_registerValue( DWORD reg, ULONGLONG LongVal )
{
ULONG val = (ULONG)LongVal;
switch( reg ) {
// debug registers
case CV_REG_DR0:
m_Context->Dr0 = val;
break;
case CV_REG_DR1:
m_Context->Dr1 = val;
break;
case CV_REG_DR2:
m_Context->Dr2 = val;
break;
case CV_REG_DR3:
m_Context->Dr3 = val;
break;
case CV_REG_DR6:
m_Context->Dr6 = val;
break;
case CV_REG_DR7:
m_Context->Dr7 = val;
break;
// segment registers
case CV_REG_GS:
m_Context->SegGs = val;
break;
case CV_REG_FS:
m_Context->SegFs = val;
break;
case CV_REG_ES:
m_Context->SegEs = val;
break;
case CV_REG_DS:
m_Context->SegDs = val;
break;
// integer registers
case CV_REG_EDI:
m_Context->Edi = val;
break;
case CV_REG_ESI:
m_Context->Esi = val;
break;
case CV_REG_EBX:
m_Context->Ebx = val;
break;
case CV_REG_EDX:
m_Context->Edx = val;
break;
case CV_REG_ECX:
m_Context->Ecx = val;
break;
case CV_REG_EAX:
m_Context->Eax = val;
break;
// control registers
case CV_REG_EBP:
m_Context->Ebp = val;
m_EbpSet = TRUE;
break;
case CV_REG_EIP:
m_Context->Eip = val;
break;
case CV_REG_CS:
m_Context->SegCs = val;
break;
case CV_REG_EFLAGS:
m_Context->EFlags = val;
break;
case CV_REG_ESP:
m_Context->Esp = val;
break;
case CV_REG_SS:
m_Context->SegSs = val;
break;
case CV_ALLREG_LOCALS:
m_Locals = val;
break;
case CV_ALLREG_PARAMS:
m_Params = val;
break;
case CV_ALLREG_VFRAME:
m_VirtFrame = val;
break;
default:
return E_FAIL;
}
return S_OK;
}
STDMETHODIMP
X86WalkFrame::readMemory(ULONGLONG va, DWORD cbData,
DWORD* pcbData, BYTE* data)
{
return m_ReadMemory( m_Process, va, data, cbData, pcbData ) != 0 ?
S_OK : E_FAIL;
}
STDMETHODIMP
X86WalkFrame::searchForReturnAddress(IDiaFrameData* frame,
ULONGLONG* pResult)
{
HRESULT Status;
DWORD LenLocals, LenRegs;
if ((Status = frame->get_lengthLocals(&LenLocals)) != S_OK ||
(Status = frame->get_lengthSavedRegisters(&LenRegs)) != S_OK) {
return Status;
}
return searchForReturnAddressStart(frame,
EXTEND64(m_Context->Esp +
LenLocals + LenRegs),
pResult);
}
STDMETHODIMP
X86WalkFrame::searchForReturnAddressStart(IDiaFrameData* DiaFrame,
ULONGLONG StartAddress,
ULONGLONG* Result)
{
HRESULT Status;
BOOL HasSeh, IsFuncStart;
IDiaFrameData* OrigFrame = DiaFrame;
IDiaFrameData* NextFrame;
DWORD LenLocals, LenRegs, LenParams = 0;
if (m_PreviousFpo &&
m_PreviousFpo->cbFrame != FRAME_TRAP &&
m_PreviousFpo->cbFrame != FRAME_TSS) {
//
// if the previous frame had an fpo record, we can account
// for its parameters
//
LenParams = m_PreviousFpo->cdwParams * STACK_SIZE;
}
if ((Status = DiaFrame->get_lengthLocals(&LenLocals)) != S_OK ||
(Status = DiaFrame->get_lengthSavedRegisters(&LenRegs)) != S_OK ||
(Status = DiaFrame->get_systemExceptionHandling(&HasSeh)) != S_OK ||
(Status = DiaFrame->get_functionStart(&IsFuncStart)) != S_OK) {
return Status;
}
if ((!HasSeh || IsFuncStart) &&
m_Context->Esp + LenLocals + LenRegs + LenParams >
(ULONG) StartAddress) {
StartAddress =
EXTEND64(m_Context->Esp + LenLocals + LenRegs + LenParams);
}
//
// This frame data may be a subsidiary descriptor. Move up
// the parent chain to the true function start.
//
while (DiaFrame->get_functionParent(&NextFrame) == S_OK) {
if (DiaFrame != OrigFrame) {
DiaFrame->Release();
}
DiaFrame = NextFrame;
}
ULONGLONG FuncStart;
DWORD LenFunc;
if ((Status = DiaFrame->get_virtualAddress(&FuncStart)) == S_OK) {
Status = DiaFrame->get_lengthBlock(&LenFunc);
}
if (DiaFrame != OrigFrame) {
DiaFrame->Release();
}
if (Status != S_OK) {
return Status;
}
*Result = SearchForReturnAddress(m_Process,
StartAddress,
FuncStart,
LenFunc,
m_ReadMemory,
m_GetModuleBase,
TRUE);
return *Result != 0 ? S_OK : E_FAIL;
}
//----------------------------------------------------------------------------
//
// Walk functions.
//
//----------------------------------------------------------------------------
BOOL
WalkX86(
HANDLE Process,
HANDLE Thread,
LPSTACKFRAME64 StackFrame,
PVOID ContextRecord,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccess,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress,
DWORD flags
)
{
BOOL rval;
WDB((2, "WalkX86 in: PC %X, SP %X, FP %X, RA %X\n",
(ULONG)StackFrame->AddrPC.Offset,
(ULONG)StackFrame->AddrStack.Offset,
(ULONG)StackFrame->AddrFrame.Offset,
(ULONG)StackFrame->AddrReturn.Offset));
if (StackFrame->Virtual) {
rval = WalkX86Next( Process,
Thread,
StackFrame,
(PX86_CONTEXT)ContextRecord,
ReadMemory,
FunctionTableAccess,
GetModuleBase,
TranslateAddress
);
} else {
rval = WalkX86Init( Process,
Thread,
StackFrame,
(PX86_CONTEXT)ContextRecord,
ReadMemory,
FunctionTableAccess,
GetModuleBase,
TranslateAddress
);
}
WDB((2, "WalkX86 out: PC %X, SP %X, FP %X, RA %X\n",
(ULONG)StackFrame->AddrPC.Offset,
(ULONG)StackFrame->AddrStack.Offset,
(ULONG)StackFrame->AddrFrame.Offset,
(ULONG)StackFrame->AddrReturn.Offset));
// This hack fixes the fpo stack when ebp wasn't used.
// Don't put this fix into StackWalk() or it will break MSDEV.
#if 0
if (rval && (flags & WALK_FIX_FPO_EBP)) {
PFPO_DATA pFpo = (PFPO_DATA)StackFrame->FuncTableEntry;
if (pFpo && !pFpo->fUseBP) {
StackFrame->AddrFrame.Offset += 4;
}
}
#endif
return rval;
}
BOOL
ReadMemoryInternal(
HANDLE Process,
HANDLE Thread,
LPADDRESS64 lpBaseAddress,
LPVOID lpBuffer,
DWORD nSize,
LPDWORD lpNumberOfBytesRead,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress,
BOOL MustReadAll
)
{
ADDRESS64 addr;
DWORD LocalBytesRead = 0;
BOOL Succ;
addr = *lpBaseAddress;
if (addr.Mode != AddrModeFlat) {
TranslateAddress( Process, Thread, &addr );
}
Succ = ReadMemory( Process,
addr.Offset,
lpBuffer,
nSize,
&LocalBytesRead
);
if (lpNumberOfBytesRead) {
*lpNumberOfBytesRead = LocalBytesRead;
}
return (Succ && MustReadAll) ? (LocalBytesRead == nSize) : Succ;
}
DWORD64
SearchForReturnAddress(
HANDLE Process,
DWORD64 uoffStack,
DWORD64 funcAddr,
DWORD funcSize,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase,
BOOL AcceptUnreadableCallSite
)
{
DWORD64 uoffRet;
DWORD64 uoffBestGuess = 0;
DWORD cdwIndex;
DWORD cdwIndexMax;
INT cbIndex;
INT cbLimit;
DWORD cBytes;
DWORD cJmpChain = 0;
DWORD64 uoffT;
DWORD cb;
BYTE jmpBuffer[ sizeof(WORD) + sizeof(DWORD) ];
LPWORD lpwJmp = (LPWORD)&jmpBuffer[0];
BYTE code[MAX_CALL];
DWORD stack [ MAX_STACK_SEARCH ];
BOPINSTR BopInstr;
WDB((1, " SearchForReturnAddress: start %X\n", (ULONG)uoffStack));
//
// this function is necessary for 4 reasons:
//
// 1) random compiler bugs where regs are saved on the
// stack but the fpo data does not account for them
//
// 2) inline asm code that does a push
//
// 3) any random code that does a push and it isn't
// accounted for in the fpo data
//
// 4) non-void non-fpo functions
// *** This case is not neccessary when the compiler
// emits FPO records for non-FPO funtions. Unfortunately
// only the NT group uses this feature.
//
if (!ReadMemory(Process,
uoffStack,
stack,
sizeof(stack),
&cb)) {
WDB((1, " can't read stack\n"));
return 0;
}
cdwIndexMax = cb / STACK_SIZE;
if ( !cdwIndexMax ) {
WDB((1, " can't read stack\n"));
return 0;
}
for ( cdwIndex=0; cdwIndex<cdwIndexMax; cdwIndex++,uoffStack+=STACK_SIZE ) {
uoffRet = (DWORD64)(LONG64)(LONG)stack[cdwIndex];
//
// Don't try looking for Code in the first 64K of an NT app.
//
if ( uoffRet < 0x00010000 ) {
continue;
}
//
// if it isn't part of any known address space it must be bogus
//
if (GetModuleBase( Process, uoffRet ) == 0) {
continue;
}
//
// Check for a BOP instruction.
//
if (ReadMemory(Process,
uoffRet - sizeof(BOPINSTR),
&BopInstr,
sizeof(BOPINSTR),
&cb)) {
if (cb == sizeof(BOPINSTR) &&
BopInstr.Instr1 == 0xc4 && BopInstr.Instr2 == 0xc4) {
WDB((1, " BOP, use %X\n", (ULONG)uoffStack));
return uoffStack;
}
}
//
// Read the maximum number of bytes a call could be from the istream
//
cBytes = MAX_CALL;
if (!ReadMemory(Process,
uoffRet - cBytes,
code,
cBytes,
&cb)) {
//
// if page is not present, we will ALWAYS mess up by
// continuing to search. If alloca was used also, we
// are toast. Too Bad.
//
if (cdwIndex == 0 && AcceptUnreadableCallSite) {
WDB((1, " unreadable call site, use %X\n",
(ULONG)uoffStack));
return uoffStack;
} else {
continue;
}
}
//
// With 32bit code that isn't FAR:32 we don't have to worry about
// intersegment calls. Check here to see if we had a call within
// segment. If it is we can later check it's full diplacement if
// necessary and see if it calls the FPO function. We will also have
// to check for thunks and see if maybe it called a JMP indirect which
// called the FPO function. We will fail to find the caller if it was
// a case of tail recursion where one function doesn't actually call
// another but rather jumps to it. This will only happen when a
// function who's parameter list is void calls another function who's
// parameter list is void and the call is made as the last statement
// in the first function. If the call to the first function was an
// 0xE8 call we will fail to find it here because it didn't call the
// FPO function but rather the FPO functions caller. If we don't get
// specific about our 0xE8 checks we will potentially see things that
// look like return addresses but aren't.
//
if (( cBytes >= 5 ) && ( code[ 2 ] == 0xE8 )) {
// We do math on 32 bit so we can ignore carry, and then sign extended
uoffT = EXTEND64((DWORD)uoffRet + *( (UNALIGNED DWORD *) &code[3] ));
//
// See if it calls the function directly, or into the function
//
if (( uoffT >= funcAddr) && ( uoffT < (funcAddr + funcSize) ) ) {
WDB((1, " found function, use %X\n", (ULONG)uoffStack));
return uoffStack;
}
while ( cJmpChain < MAX_JMP_CHAIN ) {
if (!ReadMemory(Process,
uoffT,
jmpBuffer,
sizeof(jmpBuffer),
&cb)) {
break;
}
if (cb != sizeof(jmpBuffer)) {
break;
}
//
// Now we are going to check if it is a call to a JMP, that may
// jump to the function
//
// If it is a relative JMP then calculate the destination
// and save it in uoffT. If it is an indirect JMP then read
// the destination from where the JMP is inderecting through.
//
if ( *(LPBYTE)lpwJmp == 0xE9 ) {
// We do math on 32 bit so we can ignore carry, and then
// sign extended
uoffT = EXTEND64 ((ULONG)uoffT +
*(UNALIGNED DWORD *)( jmpBuffer + sizeof(BYTE) ) + 5);
} else if ( *lpwJmp == 0x25FF ) {
if ((!ReadMemory(Process,
EXTEND64 (
*(UNALIGNED DWORD *)
((LPBYTE)lpwJmp+sizeof(WORD))),
&uoffT,
sizeof(DWORD),
&cb)) || (cb != sizeof(DWORD))) {
uoffT = 0;
break;
}
uoffT = EXTEND64(uoffT);
} else {
break;
}
//
// If the destination is to the FPO function then we have
// found the return address and thus the vEBP
//
if ( uoffT == funcAddr ) {
WDB((1, " exact function, use %X\n",
(ULONG)uoffStack));
return uoffStack;
}
cJmpChain++;
}
//
// We cache away the first 0xE8 call or 0xE9 jmp that we find in
// the event we cant find anything else that looks like a return
// address. This is meant to protect us in the tail recursion case.
//
if ( !uoffBestGuess ) {
uoffBestGuess = uoffStack;
}
}
//
// Now loop backward through the bytes read checking for a multi
// byte call type from Grp5. If we find an 0xFF then we need to
// check the byte after that to make sure that the nnn bits of
// the mod/rm byte tell us that it is a call. It it is a call
// then we will assume that this one called us because we can
// no longer accurately determine for sure whether this did
// in fact call the FPO function. Since 0xFF calls are a guess
// as well we will not check them if we already have an earlier guess.
// It is more likely that the first 0xE8 called the function than
// something higher up the stack that might be an 0xFF call.
//
if ( !uoffBestGuess && cBytes >= MIN_CALL ) {
cbLimit = MAX_CALL - (INT)cBytes;
for (cbIndex = MAX_CALL - MIN_CALL;
cbIndex >= cbLimit; //MAX_CALL - (INT)cBytes;
cbIndex--) {
if ( ( code [ cbIndex ] == 0xFF ) &&
( ( code [ cbIndex + 1 ] & 0x30 ) == 0x10 )){
WDB((1, " found call, use %X\n", (ULONG)uoffStack));
return uoffStack;
}
}
}
}
//
// we found nothing that was 100% definite so we'll return the best guess
//
WDB((1, " best guess is %X\n", (ULONG)uoffBestGuess));
return uoffBestGuess;
}
#define MRM_MOD(Mrm) (((Mrm) >> 6) & 3)
#define MRM_REGOP(Mrm) (((Mrm) >> 3) & 7)
#define MRM_RM(Mrm) (((Mrm) >> 0) & 7)
#define SIB_SCALE(Sib) (((Sib) >> 6) & 3)
#define SIB_INDEX(Sib) (((Sib) >> 3) & 7)
#define SIB_BASE(Sib) (((Sib) >> 0) & 7)
DWORD
ModRmLen(BYTE ModRm)
{
BYTE Mod, Rm;
Mod = MRM_MOD(ModRm);
Rm = MRM_RM(ModRm);
switch(Mod)
{
case 0:
if (Rm == 4)
{
return 1;
}
else if (Rm == 5)
{
return 4;
}
break;
case 1:
return 1 + (Rm == 4 ? 1 : 0);
case 2:
return 4 + (Rm == 4 ? 1 : 0);
}
// No extra bytes.
return 0;
}
BOOL
GetEspRelModRm(BYTE* CodeMrm, ULONG Esp, PULONG EspRel)
{
BYTE Mrm, Sib;
Mrm = CodeMrm[0];
if (MRM_MOD(Mrm) == 3)
{
// Register-only form. Only handle
// the case of an ESP reference.
if (MRM_RM(Mrm) == 4)
{
*EspRel = Esp;
return TRUE;
}
else
{
return FALSE;
}
}
// Look for any ESP-relative R/M.
if (MRM_RM(Mrm) != 4)
{
return FALSE;
}
Sib = CodeMrm[1];
// Only simple displacements from ESP are supported.
if (SIB_INDEX(Sib) != 4 ||
SIB_BASE(Sib) != 4)
{
return FALSE;
}
switch(MRM_MOD(Mrm))
{
case 0:
// [esp]
*EspRel = Esp;
break;
case 1:
// disp8[esp]
*EspRel = Esp + (signed char)CodeMrm[2];
break;
case 2:
// disp32[esp]
*EspRel = Esp + *(ULONG UNALIGNED *)&CodeMrm[2];
break;
default:
// Should never get here, MOD == 3 is handled above.
return FALSE;
}
return TRUE;
}
DWORD64
SearchForFramePointer(
HANDLE Process,
DWORD64 RegSaveAddr,
DWORD64 RetEspAddr,
DWORD NumRegs,
DWORD64 FuncAddr,
DWORD FuncSize,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory
)
{
BYTE Code[MAX_FUNC_PROLOGUE];
DWORD CodeLen;
DWORD i;
DWORD Depth;
DWORD64 DefAddr;
DWORD Esp = (ULONG)RetEspAddr;
BOOL EspValid = TRUE;
BYTE Mrm;
WDB((1, " SearchForFramePointer: regs %X, ret ESP %X, numregs %d\n",
(ULONG)RegSaveAddr, (ULONG)RetEspAddr, NumRegs));
// RetEspAddr is the first address beyond the end of
// the frame, so it hopefully is the address of the return
// address for the call. We don't really care about that
// and are more interested in what the first push slot might
// be, which is directly beneath the return address.
RetEspAddr -= STACK_SIZE;
//
// The compiler does not push registers in a consistent
// order and FPO information only indicates the total
// number of registers pushed, not their order. This
// function searches the stack locations where registers
// are stored and tries to find which one is EBP.
// It searches the function code for pushes and
// tries to use that information to help the stack
// analysis.
//
// If this routine fails it just returns the base
// of the register save area. If the routine pushes
// no registers, return the first possible push slot.
//
DefAddr = NumRegs ? RegSaveAddr : RetEspAddr;
// Read the beginning of the function for code analysis.
if (sizeof(Code) < FuncSize)
{
CodeLen = sizeof(Code);
}
else
{
CodeLen = FuncSize;
}
if (!ReadMemory(Process, FuncAddr, Code, CodeLen, &CodeLen))
{
WDB((1, " unable to read code, use %X\n", (ULONG)DefAddr));
return DefAddr;
}
// Scan the code for normal prologue operations like
// sub esp, push reg and mov reg. This code only
// handles a very limited set of instructions.
Depth = 0;
for (i = 0; i < CodeLen; i++)
{
WDB((4, " %08X: Opcode %02X - ",
(ULONG)FuncAddr + i, Code[i]));
if (Code[i] == 0x83 && i + 3 <= CodeLen && Code[i + 1] == 0xec)
{
// sub esp, signed imm8
Esp -= (signed char)Code[i + 2];
WDB((4 | SDB_NO_PREFIX, "sub esp,0x%x, ESP %X (%s)\n",
(signed char)Code[i + 2], Esp,
EspValid ? "valid" : "invalid"));
// Loop increment adds one.
i += 2;
}
else if (Code[i] == 0x81 && i + 6 <= CodeLen && Code[i + 1] == 0xec)
{
// sub esp, imm32
Esp -= *(ULONG UNALIGNED *)&Code[i + 2];
WDB((4 | SDB_NO_PREFIX, "sub esp,0x%x, ESP %X (%s)\n",
*(ULONG UNALIGNED *)&Code[i + 2], Esp,
EspValid ? "valid" : "invalid"));
// Loop increment adds one.
i += 5;
}
else if (Code[i] == 0x89 && i + 2 <= CodeLen)
{
// mov r/m32, reg32
Mrm = Code[i + 1];
switch(MRM_REGOP(Mrm))
{
case 5:
if (GetEspRelModRm(Code + 1, Esp, &Esp))
{
// mov [esp+offs], ebp
WDB((4 | SDB_NO_PREFIX, "mov [%X],ebp\n", Esp));
WDB((1, " moved ebp to stack at %X\n", Esp));
return EXTEND64(Esp);
}
break;
}
WDB((4 | SDB_NO_PREFIX, "mov r/m32,reg32, skipped\n"));
i += ModRmLen(Mrm) + 1;
}
else if (Code[i] == 0x8b && i + 2 <= CodeLen)
{
// mov reg32, r/m32
Mrm = Code[i + 1];
if (MRM_REGOP(Mrm) == 4)
{
// ESP was modified in a way we can't emulate.
WDB((4 | SDB_NO_PREFIX, "ESP lost\n"));
EspValid = FALSE;
}
else
{
WDB((4 | SDB_NO_PREFIX, "mov reg32,r/m32, skipped\n"));
}
i += ModRmLen(Mrm) + 1;
}
else if (Code[i] == 0x8d && i + 2 <= CodeLen)
{
// lea reg32, r/m32
Mrm = Code[i + 1];
switch(MRM_REGOP(Mrm))
{
case 4:
if (GetEspRelModRm(Code + 1, Esp, &Esp))
{
WDB((4 | SDB_NO_PREFIX, "lea esp,[%X]\n", Esp));
}
else
{
// ESP was modified in a way we can't emulate.
WDB((4 | SDB_NO_PREFIX, "ESP lost\n"));
EspValid = FALSE;
}
break;
default:
WDB((4 | SDB_NO_PREFIX, "lea reg32,r/m32, skipped\n"));
break;
}
i += ModRmLen(Mrm) + 1;
}
else if (Code[i] >= 0x50 && Code[i] <= 0x57)
{
// push rd
Esp -= STACK_SIZE;
WDB((4 | SDB_NO_PREFIX, "push <reg>, ESP %X (%s)\n", Esp,
EspValid ? "valid" : "invalid"));
if (Code[i] == 0x55)
{
// push ebp
// Found it. If we trust the ESP we've
// been tracking just return it.
// Otherwise, if it's the first instruction
// of the routine then we should return the
// frame address, otherwise return the
// proper location in the register store area.
// If there is no register store area then
// just return the default address.
if (EspValid)
{
WDB((1, " push ebp at esp %X\n", Esp));
return EXTEND64(Esp);
}
else if (!NumRegs)
{
WDB((1, " found ebp but no regarea, return %X\n",
(ULONG)DefAddr));
return DefAddr;
}
else
{
RegSaveAddr += (NumRegs - Depth - 1) * STACK_SIZE;
WDB((1, " guess ebp at %X\n", (ULONG)RegSaveAddr));
return RegSaveAddr;
}
}
Depth++;
}
else
{
// Unhandled code, fail.
WDB((4 | SDB_NO_PREFIX, "unknown\n"));
WDB((1, " unknown code sequence %02X at %X\n",
Code[i], (ULONG)FuncAddr + i));
return DefAddr;
}
}
// Didn't find a push ebp, fail.
WDB((1, " no ebp, use %X\n", (ULONG)DefAddr));
return DefAddr;
}
BOOL
GetFpoFrameBase(
HANDLE Process,
LPSTACKFRAME64 StackFrame,
PFPO_DATA pFpoData,
PFPO_DATA PreviousFpoData,
BOOL fFirstFrame,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase
)
{
DWORD Addr32;
X86_KTRAP_FRAME TrapFrame;
DWORD64 OldFrameAddr;
DWORD64 FrameAddr;
DWORD64 StackAddr;
DWORD64 ModuleBase;
DWORD64 FuncAddr;
DWORD cb;
DWORD64 StoredEbp;
//
// calculate the address of the beginning of the function
//
ModuleBase = GetModuleBase( Process, StackFrame->AddrPC.Offset );
if (!ModuleBase) {
return FALSE;
}
FuncAddr = ModuleBase+pFpoData->ulOffStart;
WDB((1, " GetFpoFrameBase: PC %X, Func %X, first %d, FPO %p [%d,%d,%d]\n",
(ULONG)StackFrame->AddrPC.Offset, (ULONG)FuncAddr,
fFirstFrame, pFpoData, pFpoData->cdwParams, pFpoData->cdwLocals,
pFpoData->cbRegs));
//
// If this isn't the first/current frame then we can add back the count
// bytes of locals and register pushed before beginning to search for
// EBP. If we are beyond prolog we can add back the count bytes of locals
// and registers pushed as well. If it is the first frame and EIP is
// greater than the address of the function then the SUB for locals has
// been done so we can add them back before beginning the search. If we
// are right on the function then we will need to start our search at ESP.
//
if ( !fFirstFrame ) {
OldFrameAddr = StackFrame->AddrFrame.Offset;
FrameAddr = 0;
//
// if this is a non-fpo or trap frame, get the frame base now:
//
if (pFpoData->cbFrame != FRAME_FPO) {
if (!PreviousFpoData || PreviousFpoData->cbFrame == FRAME_NONFPO) {
//
// previous frame base is ebp and points to this frame's ebp
//
if (!ReadMemory(Process,
OldFrameAddr,
&Addr32,
sizeof(DWORD),
&cb) ||
cb != sizeof(DWORD)) {
FrameAddr = 0;
} else {
FrameAddr = (DWORD64)(LONG64)(LONG)Addr32;
}
}
//
// if that didn't work, try for a saved ebp
//
if (!FrameAddr && IS_EBP_SAVED(StackFrame) &&
(OldFrameAddr <= SAVE_EBP(StackFrame))) {
FrameAddr = SAVE_EBP(StackFrame);
WDB((1, " non-FPO using %X\n", (ULONG)FrameAddr));
}
//
// this is not an FPO frame, so the saved EBP can only have come
// from this or a lower frame.
//
SAVE_EBP(StackFrame) = 0;
}
//
// still no frame base - either this frame is fpo, or we couldn't
// follow the ebp chain.
//
if (FrameAddr == 0) {
FrameAddr = OldFrameAddr;
//
// skip over return address from prev frame
//
FrameAddr += FRAME_SIZE;
//
// skip over this frame's locals and saved regs
//
FrameAddr += ( pFpoData->cdwLocals * STACK_SIZE );
FrameAddr += ( pFpoData->cbRegs * STACK_SIZE );
if (PreviousFpoData) {
//
// if the previous frame had an fpo record, we can account
// for its parameters
//
FrameAddr += PreviousFpoData->cdwParams * STACK_SIZE;
}
}
//
// if this is an FPO frame
// and the previous frame was non-fpo,
// and this frame passed the inherited ebp to the previous frame,
// save its ebp
//
// (if this frame used ebp, SAVE_EBP will be set after verifying
// the frame base)
//
if (pFpoData->cbFrame == FRAME_FPO &&
(!PreviousFpoData || PreviousFpoData->cbFrame == FRAME_NONFPO) &&
!pFpoData->fUseBP) {
SAVE_EBP(StackFrame) = 0;
if (ReadMemory(Process,
OldFrameAddr,
&Addr32,
sizeof(DWORD),
&cb) &&
cb == sizeof(DWORD)) {
SAVE_EBP(StackFrame) = (DWORD64)(LONG64)(LONG)Addr32;
WDB((1, " pass-through FP %X\n", Addr32));
} else {
WDB((1, " clear ebp\n"));
}
}
} else {
OldFrameAddr = StackFrame->AddrFrame.Offset;
if (pFpoData->cbFrame == FRAME_FPO && !pFpoData->fUseBP) {
//
// this frame didn't use EBP, so it actually belongs
// to a non-FPO frame further up the stack. Stash
// it in the save area for the next frame.
//
SAVE_EBP(StackFrame) = StackFrame->AddrFrame.Offset;
WDB((1, " first non-ebp save %X\n", (ULONG)SAVE_EBP(StackFrame)));
}
if (pFpoData->cbFrame == FRAME_TRAP ||
pFpoData->cbFrame == FRAME_TSS) {
FrameAddr = StackFrame->AddrFrame.Offset;
} else if (StackFrame->AddrPC.Offset == FuncAddr) {
FrameAddr = StackFrame->AddrStack.Offset;
} else if (StackFrame->AddrPC.Offset >= FuncAddr+pFpoData->cbProlog) {
FrameAddr = StackFrame->AddrStack.Offset +
( pFpoData->cdwLocals * STACK_SIZE ) +
( pFpoData->cbRegs * STACK_SIZE );
} else {
FrameAddr = StackFrame->AddrStack.Offset +
( pFpoData->cdwLocals * STACK_SIZE );
}
}
if (pFpoData->cbFrame == FRAME_TRAP) {
//
// read a kernel mode trap frame from the stack
//
if (!ReadTrapFrame( Process,
FrameAddr,
&TrapFrame,
ReadMemory )) {
return FALSE;
}
SAVE_TRAP(StackFrame) = FrameAddr;
TRAP_EDITED(StackFrame) = TrapFrame.SegCs & X86_FRAME_EDITED;
StackFrame->AddrReturn.Offset = (DWORD64)(LONG64)(LONG)(TrapFrame.Eip);
StackFrame->AddrReturn.Mode = AddrModeFlat;
StackFrame->AddrReturn.Segment = 0;
return TRUE;
}
if (pFpoData->cbFrame == FRAME_TSS) {
//
// translate a tss to a kernel mode trap frame
//
StackAddr = FrameAddr;
if (!TaskGate2TrapFrame( Process, X86_KGDT_TSS, &TrapFrame,
&StackAddr, ReadMemory )) {
return FALSE;
}
TRAP_TSS(StackFrame) = X86_KGDT_TSS;
SAVE_TRAP(StackFrame) = StackAddr;
StackFrame->AddrReturn.Offset = (DWORD64)(LONG64)(LONG)(TrapFrame.Eip);
StackFrame->AddrReturn.Mode = AddrModeFlat;
StackFrame->AddrReturn.Segment = 0;
return TRUE;
}
if ((pFpoData->cbFrame != FRAME_FPO) &&
(pFpoData->cbFrame != FRAME_NONFPO) ) {
//
// we either have a compiler or linker problem, or possibly
// just simple data corruption.
//
return FALSE;
}
//
// go look for a return address. this is done because, even though
// we have subtracted all that we can from the frame pointer it is
// possible that there is other unknown data on the stack. by
// searching for the return address we are able to find the base of
// the fpo frame.
//
FrameAddr = SearchForReturnAddress( Process,
FrameAddr,
FuncAddr,
pFpoData->cbProcSize,
ReadMemory,
GetModuleBase,
PreviousFpoData != NULL
);
if (!FrameAddr) {
return FALSE;
}
if (pFpoData->fUseBP && pFpoData->cbFrame == FRAME_FPO) {
//
// this function used ebp as a general purpose register, but
// before doing so it saved ebp on the stack.
//
// we must retrieve this ebp and save it for possible later
// use if we encounter a non-fpo frame
//
if (fFirstFrame && StackFrame->AddrPC.Offset < FuncAddr+pFpoData->cbProlog) {
SAVE_EBP(StackFrame) = OldFrameAddr;
WDB((1, " first use save FP %X\n", (ULONG)OldFrameAddr));
} else {
SAVE_EBP(StackFrame) = 0;
// FPO information doesn't indicate which of the saved
// registers is EBP and the compiler doesn't push in a
// consistent way. Scan the register slots of the
// stack for something that looks OK.
StackAddr = FrameAddr -
( ( pFpoData->cbRegs + pFpoData->cdwLocals ) * STACK_SIZE );
StackAddr = SearchForFramePointer( Process,
StackAddr,
FrameAddr,
pFpoData->cbRegs,
FuncAddr,
pFpoData->cbProcSize,
ReadMemory
);
if (StackAddr &&
ReadMemory(Process,
StackAddr,
&Addr32,
sizeof(DWORD),
&cb) &&
cb == sizeof(DWORD)) {
SAVE_EBP(StackFrame) = (DWORD64)(LONG64)(LONG)Addr32;
WDB((1, " use search save %X from %X\n", Addr32,
(ULONG)StackAddr));
} else {
WDB((1, " use clear ebp\n"));
}
}
}
//
// subtract the size for an ebp register if one had
// been pushed. this is done because the frames that
// are virtualized need to appear as close to a real frame
// as possible.
//
StackFrame->AddrFrame.Offset = FrameAddr - STACK_SIZE;
return TRUE;
}
BOOL
ReadTrapFrame(
HANDLE Process,
DWORD64 TrapFrameAddress,
PX86_KTRAP_FRAME TrapFrame,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory
)
{
DWORD cb;
if (!ReadMemory(Process,
TrapFrameAddress,
TrapFrame,
sizeof(*TrapFrame),
&cb)) {
return FALSE;
}
if (cb < sizeof(*TrapFrame)) {
if (cb < sizeof(*TrapFrame) - 20) {
//
// shorter then the smallest possible frame type
//
return FALSE;
}
if ((TrapFrame->SegCs & 1) && cb < sizeof(*TrapFrame) - 16 ) {
//
// too small for inter-ring frame
//
return FALSE;
}
if (TrapFrame->EFlags & X86_EFLAGS_V86_MASK) {
//
// too small for V86 frame
//
return FALSE;
}
}
return TRUE;
}
BOOL
GetSelector(
HANDLE Process,
USHORT Processor,
PX86_DESCRIPTOR_TABLE_ENTRY pDescriptorTableEntry,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory
)
{
ULONG_PTR Address;
PVOID TableBase;
USHORT TableLimit;
ULONG Index;
X86_LDT_ENTRY Descriptor;
ULONG bytesread;
//
// Fetch the address and limit of the GDT
//
Address = (ULONG_PTR)&(((PX86_KSPECIAL_REGISTERS)0)->Gdtr.Base);
ReadMemory( Process, Address, &TableBase, sizeof(TableBase), (LPDWORD)-1 );
Address = (ULONG_PTR)&(((PX86_KSPECIAL_REGISTERS)0)->Gdtr.Limit);
ReadMemory( Process, Address, &TableLimit, sizeof(TableLimit), (LPDWORD)-1 );
//
// Find out whether this is a GDT or LDT selector
//
if (pDescriptorTableEntry->Selector & 0x4) {
//
// This is an LDT selector, so we reload the TableBase and TableLimit
// with the LDT's Base & Limit by loading the descriptor for the
// LDT selector.
//
if (!ReadMemory(Process,
(ULONG64)TableBase+X86_KGDT_LDT,
&Descriptor,
sizeof(Descriptor),
&bytesread)) {
return FALSE;
}
TableBase = (PVOID)(DWORD_PTR)((ULONG)Descriptor.BaseLow + // Sundown: zero-extension from ULONG to PVOID.
((ULONG)Descriptor.HighWord.Bits.BaseMid << 16) +
((ULONG)Descriptor.HighWord.Bytes.BaseHi << 24));
TableLimit = Descriptor.LimitLow; // LDT can't be > 64k
if(Descriptor.HighWord.Bits.Granularity) {
//
// I suppose it's possible, to have an
// LDT with page granularity.
//
TableLimit <<= X86_PAGE_SHIFT;
}
}
Index = (USHORT)(pDescriptorTableEntry->Selector) & ~0x7;
// Irrelevant bits
//
// Check to make sure that the selector is within the table bounds
//
if (Index >= TableLimit) {
//
// Selector is out of table's bounds
//
return FALSE;
}
if (!ReadMemory(Process,
(ULONG64)TableBase+Index,
&(pDescriptorTableEntry->Descriptor),
sizeof(pDescriptorTableEntry->Descriptor),
&bytesread)) {
return FALSE;
}
return TRUE;
}
BOOL
TaskGate2TrapFrame(
HANDLE Process,
USHORT TaskRegister,
PX86_KTRAP_FRAME TrapFrame,
PULONG64 off,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory
)
{
X86_DESCRIPTOR_TABLE_ENTRY desc;
ULONG bytesread;
struct {
ULONG r1[8];
ULONG Eip;
ULONG EFlags;
ULONG Eax;
ULONG Ecx;
ULONG Edx;
ULONG Ebx;
ULONG Esp;
ULONG Ebp;
ULONG Esi;
ULONG Edi;
ULONG Es;
ULONG Cs;
ULONG Ss;
ULONG Ds;
ULONG Fs;
ULONG Gs;
} TaskState;
//
// Get the task register
//
desc.Selector = TaskRegister;
if (!GetSelector(Process, 0, &desc, ReadMemory)) {
return FALSE;
}
if (desc.Descriptor.HighWord.Bits.Type != 9 &&
desc.Descriptor.HighWord.Bits.Type != 0xb) {
//
// not a 32bit task descriptor
//
return FALSE;
}
//
// Read in Task State Segment
//
*off = ((ULONG)desc.Descriptor.BaseLow +
((ULONG)desc.Descriptor.HighWord.Bytes.BaseMid << 16) +
((ULONG)desc.Descriptor.HighWord.Bytes.BaseHi << 24) );
if (!ReadMemory(Process,
EXTEND64(*off),
&TaskState,
sizeof(TaskState),
&bytesread)) {
return FALSE;
}
//
// Move fields from Task State Segment to TrapFrame
//
ZeroMemory( TrapFrame, sizeof(*TrapFrame) );
TrapFrame->Eip = TaskState.Eip;
TrapFrame->EFlags = TaskState.EFlags;
TrapFrame->Eax = TaskState.Eax;
TrapFrame->Ecx = TaskState.Ecx;
TrapFrame->Edx = TaskState.Edx;
TrapFrame->Ebx = TaskState.Ebx;
TrapFrame->Ebp = TaskState.Ebp;
TrapFrame->Esi = TaskState.Esi;
TrapFrame->Edi = TaskState.Edi;
TrapFrame->SegEs = TaskState.Es;
TrapFrame->SegCs = TaskState.Cs;
TrapFrame->SegDs = TaskState.Ds;
TrapFrame->SegFs = TaskState.Fs;
TrapFrame->SegGs = TaskState.Gs;
TrapFrame->HardwareEsp = TaskState.Esp;
TrapFrame->HardwareSegSs = TaskState.Ss;
return TRUE;
}
BOOL
ProcessTrapFrame(
HANDLE Process,
LPSTACKFRAME64 StackFrame,
PFPO_DATA pFpoData,
PFPO_DATA PreviousFpoData,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccess
)
{
X86_KTRAP_FRAME TrapFrame;
DWORD64 StackAddr;
if (PreviousFpoData->cbFrame == FRAME_TSS) {
StackAddr = SAVE_TRAP(StackFrame);
TaskGate2TrapFrame( Process, X86_KGDT_TSS, &TrapFrame, &StackAddr, ReadMemory );
} else {
if (!ReadTrapFrame( Process,
SAVE_TRAP(StackFrame),
&TrapFrame,
ReadMemory)) {
SAVE_TRAP(StackFrame) = 0;
return FALSE;
}
}
pFpoData = (PFPO_DATA)
FunctionTableAccess(Process,
(DWORD64)(LONG64)(LONG)TrapFrame.Eip);
#if 0
// Remove this check since we are not using pFpoData anyway
if (!pFpoData) {
StackFrame->AddrFrame.Offset = (DWORD64)(LONG64)(LONG)TrapFrame.Ebp;
SAVE_EBP(StackFrame) = 0;
} else
#endif //0
{
if ((TrapFrame.SegCs & X86_MODE_MASK) ||
(TrapFrame.EFlags & X86_EFLAGS_V86_MASK)) {
//
// User-mode frame, real value of Esp is in HardwareEsp
//
StackFrame->AddrFrame.Offset = (DWORD64)(LONG64)(LONG)(TrapFrame.HardwareEsp - STACK_SIZE);
StackFrame->AddrStack.Offset = (DWORD64)(LONG64)(LONG)TrapFrame.HardwareEsp;
} else {
//
// We ignore if Esp has been edited for now, and we will print a
// separate line indicating this later.
//
// Calculate kernel Esp
//
if (PreviousFpoData->cbFrame == FRAME_TRAP) {
//
// plain trap frame
//
if ((TrapFrame.SegCs & X86_FRAME_EDITED) == 0) {
StackFrame->AddrStack.Offset = EXTEND64(TrapFrame.TempEsp);
} else {
StackFrame->AddrStack.Offset = EXTEND64(SAVE_TRAP(StackFrame))+
FIELD_OFFSET(X86_KTRAP_FRAME, HardwareEsp);
}
} else {
//
// tss converted to trap frame
//
StackFrame->AddrStack.Offset = EXTEND64(TrapFrame.HardwareEsp);
}
}
}
StackFrame->AddrFrame.Offset = EXTEND64(TrapFrame.Ebp);
StackFrame->AddrPC.Offset = EXTEND64(TrapFrame.Eip);
SAVE_TRAP(StackFrame) = 0;
StackFrame->FuncTableEntry = pFpoData;
return TRUE;
}
BOOL
IsFarCall(
HANDLE Process,
HANDLE Thread,
LPSTACKFRAME64 StackFrame,
BOOL *Ok,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
)
{
BOOL fFar = FALSE;
ULONG cb;
ADDRESS64 Addr;
*Ok = TRUE;
if (StackFrame->AddrFrame.Mode == AddrModeFlat) {
DWORD dwStk[ 3 ];
//
// If we are working with 32 bit offset stack pointers, we
// will say that the return address if far if the address
// treated as a FAR pointer makes any sense, if not then
// it must be a near return
//
if (StackFrame->AddrFrame.Offset &&
DoMemoryReadAll( &StackFrame->AddrFrame, dwStk, sizeof(dwStk) )) {
//
// See if segment makes sense
//
Addr.Offset = (DWORD64)(LONG64)(LONG)(dwStk[1]);
Addr.Segment = (WORD)dwStk[2];
Addr.Mode = AddrModeFlat;
if (TranslateAddress( Process, Thread, &Addr ) && Addr.Offset) {
fFar = TRUE;
}
} else {
*Ok = FALSE;
}
} else {
WORD wStk[ 3 ];
//
// For 16 bit (i.e. windows WOW code) we do the following tests
// to check to see if an address is a far return value.
//
// 1. if the saved BP register is odd then it is a far
// return values
// 2. if the address treated as a far return value makes sense
// then it is a far return value
// 3. else it is a near return value
//
if (StackFrame->AddrFrame.Offset &&
DoMemoryReadAll( &StackFrame->AddrFrame, wStk, 6 )) {
if ( wStk[0] & 0x0001 ) {
fFar = TRUE;
} else {
//
// See if segment makes sense
//
Addr.Offset = wStk[1];
Addr.Segment = wStk[2];
Addr.Mode = AddrModeFlat;
if (TranslateAddress( Process, Thread, &Addr ) && Addr.Offset) {
fFar = TRUE;
}
}
} else {
*Ok = FALSE;
}
}
return fFar;
}
BOOL
SetNonOff32FrameAddress(
HANDLE Process,
HANDLE Thread,
LPSTACKFRAME64 StackFrame,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccess,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
)
{
BOOL fFar;
WORD Stk[ 3 ];
ULONG cb;
BOOL Ok;
fFar = IsFarCall( Process, Thread, StackFrame, &Ok, ReadMemory, TranslateAddress );
if (!Ok) {
return FALSE;
}
if (!DoMemoryReadAll( &StackFrame->AddrFrame, Stk, (DWORD)(fFar ? FRAME_SIZE1632 : FRAME_SIZE16) )) {
return FALSE;
}
if (IS_EBP_SAVED(StackFrame) && (SAVE_EBP(StackFrame) > 0)) {
StackFrame->AddrFrame.Offset = SAVE_EBP(StackFrame) & 0xffff;
StackFrame->AddrPC.Offset = Stk[1];
if (fFar) {
StackFrame->AddrPC.Segment = Stk[2];
}
SAVE_EBP(StackFrame) = 0;
} else {
if (Stk[1] == 0) {
return FALSE;
} else {
StackFrame->AddrFrame.Offset = Stk[0];
StackFrame->AddrFrame.Offset &= 0xFFFFFFFE;
StackFrame->AddrPC.Offset = Stk[1];
if (fFar) {
StackFrame->AddrPC.Segment = Stk[2];
}
}
}
return TRUE;
}
VOID
X86ReadFunctionParameters(
HANDLE Process,
ULONG64 Offset,
LPSTACKFRAME64 Frame,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory
)
{
DWORD Params[4];
DWORD Done;
if (!ReadMemory(Process, Offset, Params, sizeof(Params), &Done)) {
Done = 0;
}
if (Done < sizeof(Params)) {
ZeroMemory((PUCHAR)Params + Done, sizeof(Params) - Done);
}
Frame->Params[0] = (DWORD64)(LONG64)(LONG)(Params[0]);
Frame->Params[1] = (DWORD64)(LONG64)(LONG)(Params[1]);
Frame->Params[2] = (DWORD64)(LONG64)(LONG)(Params[2]);
Frame->Params[3] = (DWORD64)(LONG64)(LONG)(Params[3]);
}
VOID
GetFunctionParameters(
HANDLE Process,
HANDLE Thread,
LPSTACKFRAME64 StackFrame,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
)
{
BOOL Ok;
ADDRESS64 ParmsAddr;
ParmsAddr = StackFrame->AddrFrame;
//
// calculate the frame size
//
if (StackFrame->AddrPC.Mode == AddrModeFlat) {
ParmsAddr.Offset += FRAME_SIZE;
} else
if ( IsFarCall( Process, Thread, StackFrame, &Ok,
ReadMemory, TranslateAddress ) ) {
StackFrame->Far = TRUE;
ParmsAddr.Offset += FRAME_SIZE1632;
} else {
StackFrame->Far = FALSE;
ParmsAddr.Offset += STACK_SIZE;
}
//
// read the memory
//
if (ParmsAddr.Mode != AddrModeFlat) {
TranslateAddress( Process, Thread, &ParmsAddr );
}
X86ReadFunctionParameters(Process, ParmsAddr.Offset, StackFrame,
ReadMemory);
}
VOID
GetReturnAddress(
HANDLE Process,
HANDLE Thread,
LPSTACKFRAME64 StackFrame,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress,
PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccess
)
{
ULONG cb;
DWORD stack[1];
if (SAVE_TRAP(StackFrame)) {
//
// if a trap frame was encountered then
// the return address was already calculated
//
return;
}
WDB((1, " GetReturnAddress: SP %X, FP %X\n",
(ULONG)StackFrame->AddrStack.Offset,
(ULONG)StackFrame->AddrFrame.Offset));
if (StackFrame->AddrPC.Mode == AddrModeFlat) {
ULONG64 CallOffset;
PFPO_DATA CallFpo;
ADDRESS64 FrameRet;
FPO_DATA SaveCallFpo;
PFPO_DATA RetFpo;
//
// read the frame from the process's memory
//
FrameRet = StackFrame->AddrFrame;
FrameRet.Offset += STACK_SIZE;
FrameRet.Offset = EXTEND64(FrameRet.Offset);
if (!DoMemoryRead( &FrameRet, stack, STACK_SIZE, &cb ) ||
cb < STACK_SIZE) {
//
// if we could not read the memory then set
// the return address to zero so that the stack trace
// will terminate
//
stack[0] = 0;
}
StackFrame->AddrReturn.Offset = (DWORD64)(LONG64)(LONG)(stack[0]);
WDB((1, " read %X\n", stack[0]));
//
// Calls of __declspec(noreturn) functions may not have any
// code after them to return to since the compiler knows
// that the function will not return. This can confuse
// stack traces because the return address will lie outside
// of the function's address range and FPO data will not
// be looked up correctly. Check and see if the return
// address falls outside of the calling function and, if so,
// adjust the return address back by one byte. It'd be
// better to adjust it back to the call itself so that
// the return address points to valid code but
// backing up in X86 assembly is more or less impossible.
//
CallOffset = StackFrame->AddrReturn.Offset - 1;
CallFpo = (PFPO_DATA)FunctionTableAccess(Process, CallOffset);
if (CallFpo != NULL) {
SaveCallFpo = *CallFpo;
}
RetFpo = (PFPO_DATA)
FunctionTableAccess(Process, StackFrame->AddrReturn.Offset);
if (CallFpo != NULL) {
if (RetFpo == NULL ||
memcmp(&SaveCallFpo, RetFpo, sizeof(SaveCallFpo))) {
StackFrame->AddrReturn.Offset = CallOffset;
}
} else if (RetFpo != NULL) {
StackFrame->AddrReturn.Offset = CallOffset;
}
} else {
StackFrame->AddrReturn.Offset = StackFrame->AddrPC.Offset;
StackFrame->AddrReturn.Segment = StackFrame->AddrPC.Segment;
}
}
BOOL
WalkX86_Fpo_Fpo(
HANDLE Process,
HANDLE Thread,
PFPO_DATA pFpoData,
PFPO_DATA PreviousFpoData,
LPSTACKFRAME64 StackFrame,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccess,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
)
{
BOOL rval;
WDB((1, " WalkFF:\n"));
rval = GetFpoFrameBase( Process,
StackFrame,
pFpoData,
PreviousFpoData,
FALSE,
ReadMemory,
GetModuleBase );
StackFrame->FuncTableEntry = pFpoData;
return rval;
}
BOOL
WalkX86_Fpo_NonFpo(
HANDLE Process,
HANDLE Thread,
PFPO_DATA pFpoData,
PFPO_DATA PreviousFpoData,
LPSTACKFRAME64 StackFrame,
PX86_CONTEXT ContextRecord,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccess,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
)
{
DWORD stack[FRAME_SIZE+STACK_SIZE];
DWORD cb;
DWORD64 FrameAddr;
DWORD64 FuncAddr;
DWORD FuncSize;
BOOL AcceptUnreadableCallsite = FALSE;
WDB((1, " WalkFN:\n"));
//
// if the previous frame was an SEH frame then we must
// retrieve the "real" frame pointer for this frame.
// the SEH function pushed the frame pointer last.
//
if (PreviousFpoData->fHasSEH) {
if (DoMemoryReadAll( &StackFrame->AddrFrame, stack, FRAME_SIZE+STACK_SIZE )) {
StackFrame->AddrFrame.Offset = (DWORD64)(LONG64)(LONG)(stack[2]);
StackFrame->AddrStack.Offset = (DWORD64)(LONG64)(LONG)(stack[2]);
WalkX86Init(Process,
Thread,
StackFrame,
ContextRecord,
ReadMemory,
FunctionTableAccess,
GetModuleBase,
TranslateAddress);
return TRUE;
}
}
//
// If a prior frame has stored this frame's EBP, just use it.
// Do sanity check if the saved ebp looks like a valid ebp for current stack
//
if (IS_EBP_SAVED(StackFrame) &&
(StackFrame->AddrFrame.Offset <= SAVE_EBP(StackFrame)) &&
(StackFrame->AddrFrame.Offset + 0x4000 >= SAVE_EBP(StackFrame))) {
StackFrame->AddrFrame.Offset = SAVE_EBP(StackFrame);
FrameAddr = StackFrame->AddrFrame.Offset + 4;
AcceptUnreadableCallsite = TRUE;
WDB((1, " use %X\n", (ULONG)FrameAddr));
} else {
//
// Skip past the FPO frame base and parameters.
//
StackFrame->AddrFrame.Offset +=
(FRAME_SIZE + (PreviousFpoData->cdwParams * 4));
//
// Now this is pointing to the bottom of the non-FPO frame.
// If the frame has an fpo record, use it:
//
if (pFpoData) {
FrameAddr = StackFrame->AddrFrame.Offset +
4* (pFpoData->cbRegs + pFpoData->cdwLocals);
AcceptUnreadableCallsite = TRUE;
} else {
//
// We don't know if the non-fpo frame has any locals, but
// skip past the EBP anyway.
//
FrameAddr = StackFrame->AddrFrame.Offset + 4;
}
WDB((1, " compute %X\n", (ULONG)FrameAddr));
}
//
// at this point we may not be sitting at the base of the frame
// so we now search for the return address and then subtract the
// size of the frame pointer and use that address as the new base.
//
if (pFpoData) {
FuncAddr = GetModuleBase(Process,StackFrame->AddrPC.Offset) + pFpoData->ulOffStart;
FuncSize = pFpoData->cbProcSize;
} else {
FuncAddr = StackFrame->AddrPC.Offset - MAX_CALL;
FuncSize = MAX_CALL;
}
FrameAddr = SearchForReturnAddress( Process,
FrameAddr,
FuncAddr,
FuncSize,
ReadMemory,
GetModuleBase,
AcceptUnreadableCallsite
);
if (FrameAddr) {
StackFrame->AddrFrame.Offset = FrameAddr - STACK_SIZE;
}
if (!DoMemoryReadAll( &StackFrame->AddrFrame, stack, FRAME_SIZE )) {
//
// a failure means that we likely have a bad address.
// returning zero will terminate that stack trace.
//
stack[0] = 0;
}
SAVE_EBP(StackFrame) = (DWORD64)(LONG64)(LONG)(stack[0]);
WDB((1, " save %X\n", stack[0]));
StackFrame->FuncTableEntry = pFpoData;
return TRUE;
}
BOOL
WalkX86_NonFpo_Fpo(
HANDLE Process,
HANDLE Thread,
PFPO_DATA pFpoData,
PFPO_DATA PreviousFpoData,
LPSTACKFRAME64 StackFrame,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccess,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
)
{
BOOL rval;
WDB((1, " WalkNF:\n"));
rval = GetFpoFrameBase( Process,
StackFrame,
pFpoData,
PreviousFpoData,
FALSE,
ReadMemory,
GetModuleBase );
StackFrame->FuncTableEntry = pFpoData;
return rval;
}
BOOL
WalkX86_NonFpo_NonFpo(
HANDLE Process,
HANDLE Thread,
PFPO_DATA pFpoData,
PFPO_DATA PreviousFpoData,
LPSTACKFRAME64 StackFrame,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccess,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
)
{
DWORD stack[FRAME_SIZE*4];
DWORD cb;
WDB((1, " WalkNN:\n"));
//
// a previous function in the call stack was a fpo function that used ebp as
// a general purpose register. ul contains the ebp value that was good before
// that function executed. it is that ebp that we want, not what was just read
// from the stack. what was just read from the stack is totally bogus.
//
if (IS_EBP_SAVED(StackFrame) &&
(StackFrame->AddrFrame.Offset <= SAVE_EBP(StackFrame))) {
StackFrame->AddrFrame.Offset = SAVE_EBP(StackFrame);
SAVE_EBP(StackFrame) = 0;
} else {
//
// read the first dword off the stack
//
if (!DoMemoryReadAll( &StackFrame->AddrFrame, stack, STACK_SIZE )) {
return FALSE;
}
StackFrame->AddrFrame.Offset = (DWORD64)(LONG64)(LONG)(stack[0]);
}
StackFrame->FuncTableEntry = pFpoData;
return TRUE;
}
BOOL
X86ApplyFrameData(
HANDLE Process,
LPSTACKFRAME64 StackFrame,
PX86_CONTEXT ContextRecord,
PFPO_DATA PreviousFpoData,
BOOL FirstFrame,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase
)
{
IDiaFrameData* DiaFrame;
BOOL Succ = FALSE;
// If we can get VC7-style frame data just execute
// the frame data program to unwind the stack.
// If weren't given a context record we cannot use
// the new VC7 unwind information as we have nowhere
// to save intermediate context values.
if (StackFrame->AddrPC.Mode != AddrModeFlat ||
!g_vc7fpo ||
!ContextRecord ||
!diaGetFrameData(Process, StackFrame->AddrPC.Offset, &DiaFrame))
{
return FALSE;
}
if (FirstFrame)
{
ContextRecord->Ebp = (ULONG)StackFrame->AddrFrame.Offset;
ContextRecord->Esp = (ULONG)StackFrame->AddrStack.Offset;
ContextRecord->Eip = (ULONG)StackFrame->AddrPC.Offset;
}
WDB((1, " Applying frame data program for PC %X SP %X FP %X\n",
ContextRecord->Eip, ContextRecord->Esp, ContextRecord->Ebp));
//
// execute() does not currently work when the PC is
// within the function prologue. This should only
// happen on calls from WalkX86Init, in which case the
// normal failure path here where the non-frame-data
// code will be executed is correct as that will handle
// normal prologue code.
//
X86WalkFrame WalkFrame(Process, ContextRecord,
ReadMemory, GetModuleBase,
PreviousFpoData);
Succ = DiaFrame->execute(&WalkFrame) == S_OK;
if (Succ) {
WDB((1, " Result PC %X SP %X FP %X\n",
ContextRecord->Eip, ContextRecord->Esp, ContextRecord->Ebp));
StackFrame->AddrStack.Mode = AddrModeFlat;
StackFrame->AddrStack.Offset = EXTEND64(ContextRecord->Esp);
StackFrame->AddrFrame.Mode = AddrModeFlat;
// The frame value we want to return is the frame value
// used for the function that was just unwound, not
// the current value of EBP. After the unwind the current
// value of EBP is the caller's EBP, not the callee's
// frame. Instead we always set the callee's frame to
// the offset beyond where the return address would be
// as that's where the frame will be in a normal non-FPO
// function and where we fake it as being for FPO functions.
//
// Separately, we save the true EBP away for future frame use.
// According to VinitD there's a compiler case where it
// doesn't generate proper unwind instructions for restoring
// EBP, so there are some times where EBP is not restored
// to a good value after the execute and we have to fall
// back on searching. If EBP wasn't set during the execute
// we do not save its value.
StackFrame->AddrFrame.Offset =
StackFrame->AddrStack.Offset - FRAME_SIZE;
StackFrame->AddrReturn.Offset = EXTEND64(ContextRecord->Eip);
// XXX drewb - This is causing some failures in the regression
// tests so don't enable it until we fully understand it.
#if 0
if (WalkFrame.WasEbpSet()) {
SAVE_EBP(StackFrame) = EXTEND64(ContextRecord->Ebp);
} else {
WDB((1, " * EBP not recovered\n"));
}
#else
SAVE_EBP(StackFrame) = EXTEND64(ContextRecord->Ebp);
#endif
// Caller may need to allocate this to allow alternate stackwalk with dbghelp code
StackFrame->FuncTableEntry = NULL;
X86ReadFunctionParameters(Process, StackFrame->AddrStack.Offset,
StackFrame, ReadMemory);
} else {
WDB((1, " Apply failed\n"));
}
DiaFrame->Release();
return Succ;
}
VOID
X86UpdateContextFromFrame(
HANDLE Process,
LPSTACKFRAME64 StackFrame,
PX86_CONTEXT ContextRecord,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory
)
{
ULONG Ebp;
ULONG Done;
if (StackFrame->AddrPC.Mode != AddrModeFlat ||
!ContextRecord) {
return;
}
ContextRecord->Esp = (ULONG)StackFrame->AddrFrame.Offset + FRAME_SIZE;
ContextRecord->Eip = (ULONG)StackFrame->AddrReturn.Offset;
if (IS_EBP_SAVED(StackFrame)) {
ContextRecord->Ebp = (ULONG)SAVE_EBP(StackFrame);
} else {
if (ReadMemory(Process, StackFrame->AddrFrame.Offset,
&Ebp, sizeof(Ebp), &Done) &&
Done == sizeof(Ebp)) {
ContextRecord->Ebp = Ebp;
}
}
if (StackFrame->FuncTableEntry) {
if (!IS_EBP_SAVED(StackFrame)) {
// Don't change Ebp
SAVE_EBP(StackFrame) = ((ULONG) StackFrame->AddrFrame.Offset + STACK_SIZE) +
0xEB00000000; // Add this tag to top 32 bits for marking this as a frame value
// rather than FPO saved EBP
}
}
}
BOOL
WalkX86Next(
HANDLE Process,
HANDLE Thread,
LPSTACKFRAME64 StackFrame,
PX86_CONTEXT ContextRecord,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccess,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
)
{
PFPO_DATA pFpoData = NULL;
PFPO_DATA PrevFpoData = NULL;
FPO_DATA PrevFpoBuffer;
BOOL rVal = TRUE;
DWORD64 Address;
DWORD cb;
DWORD64 ThisPC;
DWORD64 ModuleBase;
DWORD64 SystemRangeStart;
WDB((1, "WalkNext: PC %X, SP %X, FP %X\n",
(ULONG)StackFrame->AddrReturn.Offset,
(ULONG)StackFrame->AddrStack.Offset,
(ULONG)StackFrame->AddrFrame.Offset));
StackFrame->AddrStack.Offset = EXTEND64(StackFrame->AddrStack.Offset);
StackFrame->AddrFrame.Offset = EXTEND64(StackFrame->AddrFrame.Offset);
// FunctionTableAccess often returns pointers to static
// data that gets overwritten on every call. Preserve
// the data of any previous FPO record for the duration
// of this routine so that FunctionTableAccess calls can
// be made without destroying previous FPO data.
if (StackFrame->FuncTableEntry) {
PrevFpoBuffer = *(PFPO_DATA)StackFrame->FuncTableEntry;
PrevFpoData = &PrevFpoBuffer;
}
if (g.AppVersion.Revision >= 6) {
SystemRangeStart = EXTEND64(SYSTEM_RANGE_START(StackFrame));
} else {
//
// This might not really work right with old debuggers, but it keeps
// us from looking off the end of the structure anyway.
//
SystemRangeStart = 0xFFFFFFFF80000000;
}
ThisPC = StackFrame->AddrPC.Offset;
//
// the previous frame's return address is this frame's pc
//
StackFrame->AddrPC = StackFrame->AddrReturn;
if (StackFrame->AddrPC.Mode != AddrModeFlat) {
//
// the call stack is from either WOW or a DOS app
//
SetNonOff32FrameAddress( Process,
Thread,
StackFrame,
ReadMemory,
FunctionTableAccess,
GetModuleBase,
TranslateAddress
);
goto exit;
}
//
// if the last frame was the usermode callback dispatcher,
// switch over to the kernel stack:
//
ModuleBase = GetModuleBase(Process, ThisPC);
if ((g.AppVersion.Revision >= 4) &&
(CALLBACK_STACK(StackFrame) != 0) &&
(pFpoData = PrevFpoData) &&
(CALLBACK_DISPATCHER(StackFrame) ==
ModuleBase + PrevFpoData->ulOffStart) ) {
NextCallback:
rVal = FALSE;
//
// find callout frame
//
if (EXTEND64(CALLBACK_STACK(StackFrame)) >= SystemRangeStart) {
//
// it is the pointer to the stack frame that we want,
// or -1.
Address = EXTEND64(CALLBACK_STACK(StackFrame));
} else {
//
// if it is below SystemRangeStart, it is the offset to
// the address in the thread.
// Look up the pointer:
//
rVal = ReadMemory(Process,
(CALLBACK_THREAD(StackFrame) +
CALLBACK_STACK(StackFrame)),
&Address,
sizeof(DWORD),
&cb);
Address = EXTEND64(Address);
if (!rVal || cb != sizeof(DWORD) || Address == 0) {
Address = 0xffffffff;
CALLBACK_STACK(StackFrame) = 0xffffffff;
}
}
if ((Address == 0xffffffff) ||
!(pFpoData = (PFPO_DATA)
FunctionTableAccess( Process, CALLBACK_FUNC(StackFrame))) ) {
rVal = FALSE;
} else {
StackFrame->FuncTableEntry = pFpoData;
StackFrame->AddrPC.Offset = CALLBACK_FUNC(StackFrame) +
pFpoData->cbProlog;
StackFrame->AddrStack.Offset = Address;
if (!ReadMemory(Process,
Address + CALLBACK_FP(StackFrame),
&StackFrame->AddrFrame.Offset,
sizeof(DWORD),
&cb) ||
cb != sizeof(DWORD)) {
return FALSE;
}
StackFrame->AddrFrame.Offset =
EXTEND64(StackFrame->AddrFrame.Offset);
if (!ReadMemory(Process,
Address + CALLBACK_NEXT(StackFrame),
&CALLBACK_STACK(StackFrame),
sizeof(DWORD),
&cb) ||
cb != sizeof(DWORD))
{
return FALSE;
}
SAVE_TRAP(StackFrame) = 0;
rVal = WalkX86Init(
Process,
Thread,
StackFrame,
ContextRecord,
ReadMemory,
FunctionTableAccess,
GetModuleBase,
TranslateAddress
);
}
return rVal;
}
//
// if there is a trap frame then handle it
//
if (SAVE_TRAP(StackFrame)) {
rVal = ProcessTrapFrame(
Process,
StackFrame,
pFpoData,
PrevFpoData,
ReadMemory,
FunctionTableAccess
);
if (!rVal) {
return rVal;
}
rVal = WalkX86Init(
Process,
Thread,
StackFrame,
ContextRecord,
ReadMemory,
FunctionTableAccess,
GetModuleBase,
TranslateAddress
);
return rVal;
}
//
// if the PC address is zero then we're at the end of the stack
//
//if (GetModuleBase(Process, StackFrame->AddrPC.Offset) == 0)
if (StackFrame->AddrPC.Offset < 65536) {
//
// if we ran out of stack, check to see if there is
// a callback stack chain
//
if (g.AppVersion.Revision >= 4 && CALLBACK_STACK(StackFrame) != 0) {
goto NextCallback;
}
return FALSE;
}
//
// If the frame, pc and return address are all identical, then we are
// at the top of the idle loop
//
if ((StackFrame->AddrPC.Offset == StackFrame->AddrReturn.Offset) &&
(StackFrame->AddrPC.Offset == StackFrame->AddrFrame.Offset))
{
return FALSE;
}
if (X86ApplyFrameData(Process, StackFrame, ContextRecord,
PrevFpoData, FALSE,
ReadMemory, GetModuleBase)) {
// copy FPO_DATA to allow alternating between dbghelp and DIA stackwalk
StackFrame->FuncTableEntry = FunctionTableAccess(Process, StackFrame->AddrPC.Offset);
return TRUE;
}
//
// check to see if the current frame is an fpo frame
//
pFpoData = (PFPO_DATA) FunctionTableAccess(Process, StackFrame->AddrPC.Offset);
if (pFpoData && pFpoData->cbFrame != FRAME_NONFPO) {
if (PrevFpoData && PrevFpoData->cbFrame != FRAME_NONFPO) {
rVal = WalkX86_Fpo_Fpo( Process,
Thread,
pFpoData,
PrevFpoData,
StackFrame,
ReadMemory,
FunctionTableAccess,
GetModuleBase,
TranslateAddress
);
} else {
rVal = WalkX86_NonFpo_Fpo( Process,
Thread,
pFpoData,
PrevFpoData,
StackFrame,
ReadMemory,
FunctionTableAccess,
GetModuleBase,
TranslateAddress
);
}
} else {
if (PrevFpoData && PrevFpoData->cbFrame != FRAME_NONFPO) {
rVal = WalkX86_Fpo_NonFpo( Process,
Thread,
pFpoData,
PrevFpoData,
StackFrame,
ContextRecord,
ReadMemory,
FunctionTableAccess,
GetModuleBase,
TranslateAddress
);
} else {
rVal = WalkX86_NonFpo_NonFpo( Process,
Thread,
pFpoData,
PrevFpoData,
StackFrame,
ReadMemory,
FunctionTableAccess,
GetModuleBase,
TranslateAddress
);
}
}
exit:
StackFrame->AddrFrame.Mode = StackFrame->AddrPC.Mode;
StackFrame->AddrReturn.Mode = StackFrame->AddrPC.Mode;
GetFunctionParameters( Process, Thread, StackFrame,
ReadMemory, GetModuleBase, TranslateAddress );
GetReturnAddress( Process, Thread, StackFrame,
ReadMemory, GetModuleBase, TranslateAddress,
FunctionTableAccess );
X86UpdateContextFromFrame(Process, StackFrame, ContextRecord, ReadMemory);
return rVal;
}
BOOL
WalkX86Init(
HANDLE Process,
HANDLE Thread,
LPSTACKFRAME64 StackFrame,
PX86_CONTEXT ContextRecord,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemory,
PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccess,
PGET_MODULE_BASE_ROUTINE64 GetModuleBase,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
)
{
UCHAR code[3];
DWORD stack[FRAME_SIZE*4];
PFPO_DATA pFpoData = NULL;
ULONG cb;
ULONG64 ModBase;
StackFrame->Virtual = TRUE;
StackFrame->Reserved[0] =
StackFrame->Reserved[1] =
StackFrame->Reserved[2] = 0;
StackFrame->AddrReturn = StackFrame->AddrPC;
if (StackFrame->AddrPC.Mode != AddrModeFlat) {
goto exit;
}
WDB((1, "WalkInit: PC %X, SP %X, FP %X\n",
(ULONG)StackFrame->AddrPC.Offset, (ULONG)StackFrame->AddrStack.Offset,
(ULONG)StackFrame->AddrFrame.Offset));
if (X86ApplyFrameData(Process, StackFrame, ContextRecord, NULL, TRUE,
ReadMemory, GetModuleBase)) {
// copy FPO_DATA to allow alternating between dbghelp and DIA stackwalk
StackFrame->FuncTableEntry = FunctionTableAccess(Process, StackFrame->AddrPC.Offset);
return TRUE;
}
StackFrame->FuncTableEntry = pFpoData = (PFPO_DATA)
FunctionTableAccess(Process, StackFrame->AddrPC.Offset);
if (pFpoData && pFpoData->cbFrame != FRAME_NONFPO) {
GetFpoFrameBase( Process,
StackFrame,
pFpoData,
pFpoData,
TRUE,
ReadMemory,
GetModuleBase );
goto exit;
} else if (!pFpoData &&
((ModBase = GetModuleBase(Process, StackFrame->AddrPC.Offset)) == 0 ||
ModBase == MM_SHARED_USER_DATA_VA)) {
//
// We have no FPO data and the current IP isn't in
// any known module or the module is debuggers' madeup
// "shareduserdata" module. We'll assume this is a call
// to a bad address, so we expect that the return
// address should be the first DWORD on the stack.
//
if (DoMemoryReadAll( &StackFrame->AddrStack, stack, STACK_SIZE ) &&
GetModuleBase(Process, EXTEND64(stack[0]))) {
// The first DWORD is a code address. We probably
// found a call to a bad location.
SAVE_EBP(StackFrame) = StackFrame->AddrFrame.Offset;
StackFrame->AddrFrame.Offset =
StackFrame->AddrStack.Offset - STACK_SIZE;
goto exit;
}
}
//
// We couldn't figure out anything about the code at
// the current IP so we just assume it's a traditional
// EBP-framed routine.
//
// First check whether eip is in the function prolog
//
memset(code, 0xcc, sizeof(code));
if (!DoMemoryRead( &StackFrame->AddrPC, code, 3, &cb )) {
//
// Assume a call to a bad address if the memory read fails.
//
code[0] = PUSHBP;
}
if ((code[0] == PUSHBP) || (*(LPWORD)&code[0] == MOVBPSP)) {
SAVE_EBP(StackFrame) = StackFrame->AddrFrame.Offset;
StackFrame->AddrFrame.Offset = StackFrame->AddrStack.Offset;
if (StackFrame->AddrPC.Mode != AddrModeFlat) {
StackFrame->AddrFrame.Offset &= 0xffff;
}
if (code[0] == PUSHBP) {
if (StackFrame->AddrPC.Mode == AddrModeFlat) {
StackFrame->AddrFrame.Offset -= STACK_SIZE;
} else {
StackFrame->AddrFrame.Offset -= STACK_SIZE16;
}
}
} else {
//
// We're not in a prologue so assume we're in the middle
// of an EBP-framed function. Read the first dword off
// the stack at EBP and assume that it's the pushed EBP.
//
if (DoMemoryReadAll( &StackFrame->AddrFrame, stack, STACK_SIZE )) {
SAVE_EBP(StackFrame) = EXTEND64(stack[0]);
}
if (StackFrame->AddrPC.Mode != AddrModeFlat) {
StackFrame->AddrFrame.Offset &= 0x0000FFFF;
}
}
exit:
StackFrame->AddrFrame.Mode = StackFrame->AddrPC.Mode;
GetFunctionParameters( Process, Thread, StackFrame,
ReadMemory, GetModuleBase, TranslateAddress );
GetReturnAddress( Process, Thread, StackFrame,
ReadMemory, GetModuleBase, TranslateAddress,
FunctionTableAccess );
X86UpdateContextFromFrame(Process, StackFrame, ContextRecord, ReadMemory);
return TRUE;
}
| 31.442743 | 118 | 0.496919 |
ce9ed96e588e8fbbf39a9de9470f0c25cf085d01
| 615 |
kt
|
Kotlin
|
presentation/src/main/java/com/test/grability/view/activity/MainActivity.kt
|
andresbelt/MarvelExample
|
8d805d195481cb19179d272186c307e18369ea76
|
[
"MIT"
] | null | null | null |
presentation/src/main/java/com/test/grability/view/activity/MainActivity.kt
|
andresbelt/MarvelExample
|
8d805d195481cb19179d272186c307e18369ea76
|
[
"MIT"
] | null | null | null |
presentation/src/main/java/com/test/grability/view/activity/MainActivity.kt
|
andresbelt/MarvelExample
|
8d805d195481cb19179d272186c307e18369ea76
|
[
"MIT"
] | null | null | null |
package com.test.grability.view.activity
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.test.grability.R
import com.test.grability.base.BaseActivity
import com.test.grability.databinding.ActivityLoginBinding
import com.test.grability.databinding.ActivityMainBinding
class MainActivity : BaseActivity() {
private lateinit var binding: ActivityMainBinding
override fun observeViewModel() {
}
override fun initViewBinding() {
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
}
}
| 23.653846 | 61 | 0.770732 |
9c4f88fff83ae3228c24372d92b027f713b9c59b
| 753 |
js
|
JavaScript
|
components/Expbar/styles.js
|
jose-garzon/masterpath
|
cb2a8136b0e2afe620867c3b4baf4e07c70636c3
|
[
"MIT"
] | null | null | null |
components/Expbar/styles.js
|
jose-garzon/masterpath
|
cb2a8136b0e2afe620867c3b4baf4e07c70636c3
|
[
"MIT"
] | 28 |
2020-12-18T03:31:25.000Z
|
2020-12-19T23:00:46.000Z
|
components/Expbar/styles.js
|
hack-learning/masterpath_frontend
|
8d1b8a0dd4fae4c5998dbd67ef955530ff26fc14
|
[
"MIT"
] | null | null | null |
// import Libraries
import styled from 'styled-components';
// import variables
import { colors, border } from '../../globalStyles/stylesVariables';
// ---------- COMPONENTS ---------- //
export const Bar = styled.main`
position: relative;
padding: 5px 40px;
text-align: center;
color: ${colors.white};
background-color: ${colors.second};
border-radius: ${border.borderRadiusBig};
border: 2px solid ${colors.main};
transform: translateY(-50%);
overflow: hidden;
&:after {
position: absolute;
content: '';
top: -1px;
left: -1px;
bottom: -1px;
width: ${(props) => `${props.XP}%`};
z-index: -1;
border-radius: ${border.borderRadiusBig};
background-color: ${colors.main};
transition: 0.3s;
}
p {
font-weight: bold;
}
`;
| 22.147059 | 68 | 0.64409 |
dd09a3ab7bfd50f6e89d71abca726c05ff28a45a
| 340 |
asm
|
Assembly
|
src/chips/UPD7759.asm
|
sharksym/vgmplay-sharksym
|
d7763b87a379da4e6dadcc55026969d310957952
|
[
"BSD-2-Clause"
] | 6 |
2020-04-21T17:26:27.000Z
|
2021-09-25T18:41:01.000Z
|
src/chips/UPD7759.asm
|
sharksym/vgmplay-sharksym
|
d7763b87a379da4e6dadcc55026969d310957952
|
[
"BSD-2-Clause"
] | null | null | null |
src/chips/UPD7759.asm
|
sharksym/vgmplay-sharksym
|
d7763b87a379da4e6dadcc55026969d310957952
|
[
"BSD-2-Clause"
] | null | null | null |
;
; VGM UPD7759 chip
;
UPD7759: MACRO
super: Chip UPD7759_name, Header.uPD7759Clock, System_Return
ENDM
; ix = this
; iy = header
UPD7759_Construct: equ Chip_Construct
; jp Chip_Construct
; ix = this
UPD7759_Destruct: equ Chip_Destruct
; jp Chip_Destruct
;
SECTION RAM
UPD7759_instance: UPD7759
ENDS
UPD7759_name:
db "uPD7759",0
| 13.076923 | 61 | 0.758824 |
67c5a27ba2b47f268716d1b1f229e9562da3363b
| 2,996 |
lua
|
Lua
|
src/mod/noafindskitten/data/map_template.lua
|
Ruin0x11/OpenNefia
|
548f1a1442eca704bb1c16b1a1591d982a34919f
|
[
"MIT"
] | 109 |
2020-04-07T16:56:38.000Z
|
2022-02-17T04:05:40.000Z
|
src/mod/noafindskitten/data/map_template.lua
|
Ruin0x11/OpenNefia
|
548f1a1442eca704bb1c16b1a1591d982a34919f
|
[
"MIT"
] | 243 |
2020-04-07T08:25:15.000Z
|
2021-10-30T07:22:10.000Z
|
src/mod/noafindskitten/data/map_template.lua
|
Ruin0x11/OpenNefia
|
548f1a1442eca704bb1c16b1a1591d982a34919f
|
[
"MIT"
] | 15 |
2020-04-25T12:28:55.000Z
|
2022-02-23T03:20:43.000Z
|
local InstancedMap = require("api.InstancedMap")
local Pos = require("api.Pos")
local Gui = require("api.Gui")
local I18N = require("api.I18N")
local Feat = require("api.Feat")
local Rand = require("api.Rand")
local Input = require("api.Input")
local Anim = require("mod.elona_sys.api.Anim")
local Color = require("mod.extlibs.api.Color")
local Quest = require("mod.elona_sys.api.Quest")
local MapEntrance = require("mod.elona_sys.api.MapEntrance")
local ElonaQuest = require("mod.elona.api.ElonaQuest")
data:add {
_type = "base.chip",
_id = "object",
image = "mod/noafindskitten/graphic/object.png"
}
data:add {
_type = "base.feat",
_id = "object",
params = {
is_kitten = { type = types.boolean, default = false },
description = { type = types.string }
},
image = "noafindskitten.object",
is_solid = true,
is_opaque = false,
shadow_type = "normal",
on_bumped_into = function(self, params)
if self.params.is_kitten then
local anim = Anim.load("elona.anim_smoke", self.x, self.y)
Gui.start_draw_callback(anim)
self.image = "elona.chara_stray_cat"
self.color = {255, 255, 255}
Gui.update_screen()
Gui.mes("noafindskitten.kitten_found", "Green")
Input.query_more()
local quest = assert(Quest.get_immediate_quest())
quest.state = "completed"
ElonaQuest.travel_to_previous_map()
else
Gui.play_sound("base.chat")
Gui.mes_c(self.params.description)
end
return "turn_end"
end,
on_bash = function(self)
if not self.params.is_kitten then
Gui.play_sound("base.bash1")
self:remove_ownership()
return "turn_end"
end
end,
events = {}
}
local quest_noafindskitten = {
_type = "base.map_archetype",
_id = "quest_noafindskitten",
starting_pos = MapEntrance.center,
properties = {
music = "elona.ruin",
types = { "quest" },
level = 1,
is_indoor = true,
max_crowd_density = 0,
reveals_fog = true,
is_temporary = true
},
}
function quest_noafindskitten.on_generate_map(area, floor, params)
local map = InstancedMap:new(40, 40)
map:clear("elona.cobble")
for _, x, y in Pos.iter_border(0, 0, map:width() - 1, map:height() - 1) do
map:set_tile(x, y, "elona.wall_brick_top")
end
-- NOTE: we'd want to ensure there's a clear path to kitten, so the player doesn't get blocked.
local count = math.floor(map:width() * map:height() / 40)
for _=1, count do
local object = Feat.create("noafindskitten.object", nil, nil, {params={description=I18N.get("noafindskitten.nki")}}, map)
if object then
object.color = {Color:new_hsl(Rand.rnd(360), 1, 0.8):to_rgb()}
end
end
Rand.choice(Feat.iter(map):filter(function(i) return i._id == "noafindskitten.object" end)).params.is_kitten = true
return map, "noafindskitten.noafindskitten"
end
data:add(quest_noafindskitten)
| 29.087379 | 127 | 0.646862 |
cb6fd862b26f5701a798f84fb660860482ce746c
| 3,921 |
go
|
Go
|
server/udp/session.go
|
millken/tcpwder
|
b6e34bad5919a930bd73e9e90b460984436273ed
|
[
"MIT"
] | 3 |
2019-03-08T14:14:08.000Z
|
2022-02-09T09:23:39.000Z
|
server/udp/session.go
|
millken/tcpwder
|
b6e34bad5919a930bd73e9e90b460984436273ed
|
[
"MIT"
] | null | null | null |
server/udp/session.go
|
millken/tcpwder
|
b6e34bad5919a930bd73e9e90b460984436273ed
|
[
"MIT"
] | 6 |
2017-08-23T13:49:39.000Z
|
2022-02-09T09:23:42.000Z
|
/**
* session.go - udp "session"
*
* @author Illarion Kovalchuk <illarion.kovalchuk@gmail.com>
* @author Yaroslav Pogrebnyak <yyyaroslav@gmail.com>
*/
package udp
import (
"log"
"net"
"sync/atomic"
"time"
"github.com/millken/tcpwder/core"
"github.com/millken/tcpwder/server/scheduler"
)
/**
* Emulates UDP "session"
*/
type session struct {
/* timeout for new data from client */
clientIdleTimeout time.Duration
/* timeout for new data from backend */
backendIdleTimeout time.Duration
/* max number of client requests */
maxRequests uint64
/* actually sent client requests */
_sentRequests uint64
/* max number of backend responses */
maxResponses uint64
/* scheduler */
scheduler scheduler.Scheduler
/* connection to send responses to client with */
serverConn *net.UDPConn
/* client address */
clientAddr net.UDPAddr
/* Session backend */
backend *core.Backend
/* connection to previously elected backend */
backendConn *net.UDPConn
/* activity channel */
clientActivityC chan bool
clientLastActivity time.Time
/* stop channel */
stopC chan bool
/* function to call to notify server that session is closed and should be removed */
notifyClosed func()
}
/**
* Start session
*/
func (s *session) start() error {
s.stopC = make(chan bool)
s.clientActivityC = make(chan bool)
s.clientLastActivity = time.Now()
backendAddr, err := net.ResolveUDPAddr("udp", s.backend.Target.String())
if err != nil {
log.Printf("[ERROR] ResolveUDPAddr: %s", err)
return err
}
backendConn, err := net.DialUDP("udp", nil, backendAddr)
if err != nil {
log.Printf("[DEBUG] Error connecting to backend: %s", err)
return err
}
s.backendConn = backendConn
/**
* Update time and wait for stop
*/
var t *time.Ticker
var tC <-chan time.Time
if s.clientIdleTimeout > 0 {
log.Printf("[DEBUG] Starting new ticker for client %s%s%s", s.clientAddr, " ", s.clientIdleTimeout)
t = time.NewTicker(s.clientIdleTimeout)
tC = t.C
}
stopped := false
go func() {
for {
select {
case now := <-tC:
if s.clientLastActivity.Add(s.clientIdleTimeout).Before(now) {
log.Printf("[DEBUG] Client %s%s%s", s.clientAddr, " was idle for more than ", s.clientIdleTimeout)
go func() {
s.stopC <- true
}()
}
case <-s.stopC:
stopped = true
log.Printf("[DEBUG] Closing client session: %s", s.clientAddr.String())
s.backendConn.Close()
s.notifyClosed()
if t != nil {
t.Stop()
}
return
case <-s.clientActivityC:
s.clientLastActivity = time.Now()
}
}
}()
/**
* Proxy data from backend to client
*/
go func() {
buf := make([]byte, UDP_PACKET_SIZE)
var responses uint64
for {
if s.backendIdleTimeout > 0 {
err := s.backendConn.SetReadDeadline(time.Now().Add(s.backendIdleTimeout))
if err != nil {
log.Printf("[ERROR] Unable to set timeout for backend connection, closing. Error: %s", err)
s.stop()
return
}
}
n, _, err := s.backendConn.ReadFromUDP(buf)
if err != nil {
if !err.(*net.OpError).Timeout() && !stopped {
log.Printf("[ERROR] reading from backend %s", err)
}
s.stop()
return
}
s.scheduler.IncrementRx(*s.backend, uint(n))
s.serverConn.WriteToUDP(buf[0:n], &s.clientAddr)
if s.maxResponses > 0 {
responses++
if responses >= s.maxResponses {
s.stop()
return
}
}
}
}()
return nil
}
/**
* Writes data to session backend
*/
func (s *session) send(buf []byte) error {
select {
case s.clientActivityC <- true:
default:
}
_, err := s.backendConn.Write(buf)
if err != nil {
return err
}
s.scheduler.IncrementTx(*s.backend, uint(len(buf)))
if s.maxRequests > 0 {
if atomic.AddUint64(&s._sentRequests, 1) >= s.maxRequests {
s.stop()
}
}
return nil
}
/**
* Stops session
*/
func (c *session) stop() {
select {
case c.stopC <- true:
default:
}
}
| 19.033981 | 103 | 0.646009 |
afdd2f892950fa953e4cb95977aba47fb8acfb28
| 5,764 |
kt
|
Kotlin
|
platform/elevation/daemon/src/com/intellij/execution/process/mediator/daemon/ProcessManager.kt
|
anatawa12/intellij-community
|
d2557a13699986aa174a8969952711130718e7a1
|
[
"Apache-2.0"
] | null | null | null |
platform/elevation/daemon/src/com/intellij/execution/process/mediator/daemon/ProcessManager.kt
|
anatawa12/intellij-community
|
d2557a13699986aa174a8969952711130718e7a1
|
[
"Apache-2.0"
] | null | null | null |
platform/elevation/daemon/src/com/intellij/execution/process/mediator/daemon/ProcessManager.kt
|
anatawa12/intellij-community
|
d2557a13699986aa174a8969952711130718e7a1
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.process.mediator.daemon
import com.google.protobuf.ByteString
import com.intellij.execution.process.mediator.daemon.FdConstants.STDERR
import com.intellij.execution.process.mediator.daemon.FdConstants.STDIN
import com.intellij.execution.process.mediator.daemon.FdConstants.STDOUT
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.future.await
import java.io.Closeable
import java.io.File
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong
typealias Pid = Long
internal class ProcessManager : Closeable {
private val handleIdCounter = AtomicLong()
private val handleMap = ConcurrentHashMap<Pid, Handle>()
fun openHandle(coroutineScope: CoroutineScope): Handle {
val handleId = handleIdCounter.incrementAndGet()
return Handle(handleId, coroutineScope).also { handle ->
handleMap[handleId] = handle
handle.lifetimeJob.invokeOnCompletion {
handleMap.remove(handleId) // may not be there when called from ProcessManager.close()
}
}
}
suspend fun createProcess(handleId: Long,
command: List<String>, workingDir: File, environVars: Map<String, String>,
inFile: File?, outFile: File?, errFile: File?): Pid {
val handle = getHandle(handleId)
val processBuilder = ProcessBuilder().apply {
command(command)
directory(workingDir)
environment().run {
clear()
putAll(environVars)
}
inFile?.let { redirectInput(it) }
outFile?.let { redirectOutput(it) }
errFile?.let { redirectError(it) }
}
val process = handle.startProcess(processBuilder)
return process.pid()
}
fun destroyProcess(handleId: Long, force: Boolean, destroyGroup: Boolean) {
val handle = getHandle(handleId)
val process = handle.process
val processHandle = process.toHandle()
if (destroyGroup) {
processHandle.doDestroyRecursively(force)
}
else {
processHandle.doDestroy(force)
}
}
private fun ProcessHandle.doDestroyRecursively(force: Boolean) {
for (child in children()) {
child.doDestroyRecursively(force)
}
doDestroy(force)
}
private fun ProcessHandle.doDestroy(force: Boolean) {
if (force) {
destroyForcibly()
}
else {
destroy()
}
}
suspend fun awaitTermination(handleId: Long): Int {
val handle = getHandle(handleId)
val process = handle.process
return process.onExit().await().exitValue()
}
fun readStream(handleId: Long, fd: Int): Flow<ByteString> {
val handle = getHandle(handleId)
val process = handle.process
val inputStream = when (fd) {
STDOUT -> process.inputStream
STDERR -> process.errorStream
else -> throw IllegalArgumentException("Unknown process output FD $fd for PID $handleId")
}
val buffer = ByteArray(8192)
@Suppress("BlockingMethodInNonBlockingContext", "EXPERIMENTAL_API_USAGE") // note the .flowOn(Dispatchers.IO) below
return flow<ByteString> {
while (true) {
val n = inputStream.read(buffer)
if (n < 0) break
val chunk = ByteString.copyFrom(buffer, 0, n)
emit(chunk)
}
}.onCompletion {
inputStream.close()
}.flowOn(Dispatchers.IO)
}
suspend fun writeStream(handleId: Long, fd: Int, chunkFlow: Flow<ByteString>, ackChannel: SendChannel<Unit>?) {
val handle = getHandle(handleId)
val process = handle.process
val outputStream = when (fd) {
STDIN -> process.outputStream
else -> throw IllegalArgumentException("Unknown process input FD $fd for PID $handleId")
}
@Suppress("BlockingMethodInNonBlockingContext")
withContext(Dispatchers.IO) {
outputStream.use { outputStream ->
with(currentCoroutineContext()) {
process.onExit().whenComplete { _, _ ->
job.cancel("Process exited")
}
}
@Suppress("EXPERIMENTAL_API_USAGE")
chunkFlow.onCompletion {
ackChannel?.close(it)
}.collect { chunk ->
val buffer = chunk.toByteArray()
outputStream.write(buffer)
outputStream.flush()
ackChannel?.send(Unit)
}
}
}
}
private fun getHandle(handleId: Long): Handle {
val handle = handleMap[handleId]
return requireNotNull(handle) { "Unknown handle ID $handleId" }
}
override fun close() {
while (true) {
val handleId = handleMap.keys.firstOrNull() ?: break
val handle = handleMap.remove(handleId) ?: continue
handle.lifetimeJob.cancel("closed")
}
}
class Handle(val handleId: Long, coroutineScope: CoroutineScope) {
val lifetimeJob: Job = Job(coroutineScope.coroutineContext.job).also {
it.ensureActive()
}
val process: Process
get() = checkNotNull(_process) { "Process has not been created yet" }
@Volatile
private var _process: Process? = null
suspend fun startProcess(processBuilder: ProcessBuilder): Process {
check(_process == null) { "Process has already been initialized" }
withContext(Dispatchers.IO) {
synchronized(this) {
check(_process == null) { "Process has already been initialized" }
lifetimeJob.ensureActive()
@Suppress("BlockingMethodInNonBlockingContext")
_process = processBuilder.start()
}
}
return process
}
}
}
private object FdConstants {
const val STDIN = 0
const val STDOUT = 1
const val STDERR = 2
}
| 31.497268 | 140 | 0.671929 |
9c76f906bbd794932320fe81ebbaf419020bf820
| 659 |
js
|
JavaScript
|
src/_11ty/shortcodes/imgix.js
|
ddemaree/dd11ty
|
43fc43574ac189f06b9d2783d691cea21be69bb1
|
[
"MIT"
] | null | null | null |
src/_11ty/shortcodes/imgix.js
|
ddemaree/dd11ty
|
43fc43574ac189f06b9d2783d691cea21be69bb1
|
[
"MIT"
] | 3 |
2021-06-09T15:14:20.000Z
|
2021-06-22T02:47:05.000Z
|
src/_11ty/shortcodes/imgix.js
|
ddemaree/website
|
43fc43574ac189f06b9d2783d691cea21be69bb1
|
[
"MIT"
] | null | null | null |
const _ = require('lodash');
const imgixClient = require('../imgixClient')
module.exports = (path, width=null, height=null, alt="Image for post") => {
let attrs = {}
const src = imgixClient.buildURL(path, {
w: width,
h: height
})
const srcset = imgixClient.buildSrcSet(
path,
{},
{
minWidth: 300,
maxWidth: 2400,
widthTolerance: 0.1
}
)
attrs = _.pickBy({
src,
srcset,
height,
width,
alt,
class: "lazyload",
sizes: "(max-width: 675px) 100vw, 1200px"
})
const attrsString = _.entries(attrs).map(([k, v]) => `${k}="${v}"`).join(' ')
return `<img ${attrsString}>`;
}
| 18.828571 | 79 | 0.559939 |
8b88a3eb0c9be43f32691a05c6a6d74412bb4dcd
| 565 |
sql
|
SQL
|
kata-files/lesson2/postgresql/expected/MYLARGESCHEMA/function/func430.sql
|
goldmansachs/obevo-kata
|
5596ff44ad560d89d183ac0941b727db1a2a7346
|
[
"Apache-2.0"
] | 22 |
2017-09-28T21:35:04.000Z
|
2022-02-12T06:24:28.000Z
|
kata-files/lesson2/postgresql/expected/MYLARGESCHEMA/function/func430.sql
|
goldmansachs/obevo-kata
|
5596ff44ad560d89d183ac0941b727db1a2a7346
|
[
"Apache-2.0"
] | 6 |
2017-07-01T13:52:34.000Z
|
2018-09-13T15:43:47.000Z
|
kata-files/lesson2/postgresql/expected/MYLARGESCHEMA/function/func430.sql
|
goldmansachs/obevo-kata
|
5596ff44ad560d89d183ac0941b727db1a2a7346
|
[
"Apache-2.0"
] | 11 |
2017-04-30T18:39:09.000Z
|
2021-08-22T16:21:11.000Z
|
CREATE FUNCTION func430() RETURNS integer
LANGUAGE plpgsql
AS $$ DECLARE val INTEGER; BEGIN val:=(SELECT COUNT(*)INTO MYCOUNT FROM MYLARGESCHEMA.TABLE160);val:=(SELECT COUNT(*)INTO MYCOUNT FROM MYLARGESCHEMA.TABLE371);val:=(SELECT COUNT(*)INTO MYCOUNT FROM MYLARGESCHEMA.TABLE457);val:=(SELECT COUNT(*)INTO MYCOUNT FROM MYLARGESCHEMA.VIEW26);val:=(SELECT COUNT(*)INTO MYCOUNT FROM MYLARGESCHEMA.VIEW66);val:=(SELECT COUNT(*)INTO MYCOUNT FROM MYLARGESCHEMA.VIEW55);CALL FUNC538(MYVAR);CALL FUNC462(MYVAR);CALL FUNC295(MYVAR);CALL FUNC751(MYVAR);END $$;
GO
| 80.714286 | 496 | 0.773451 |
c3a1ef30209b0a842ecbd13219a25b8e2839af3d
| 86 |
sql
|
SQL
|
gcp-test/tests/gcp_compute_address/test-list-query.sql
|
xanonid/steampipe-plugin-gcp
|
f0e6a76233c367d227e4b80f142035f174ff4e46
|
[
"Apache-2.0"
] | 10 |
2021-01-21T19:06:58.000Z
|
2022-03-14T06:25:51.000Z
|
gcp-test/tests/gcp_compute_address/test-list-query.sql
|
Leectan/steampipe-plugin-gcp
|
c000c1e234fd53e2c52243a44f64d0856bf6f60f
|
[
"Apache-2.0"
] | 191 |
2021-01-22T07:14:32.000Z
|
2022-03-30T15:44:33.000Z
|
gcp-test/tests/gcp_compute_address/test-list-query.sql
|
Leectan/steampipe-plugin-gcp
|
c000c1e234fd53e2c52243a44f64d0856bf6f60f
|
[
"Apache-2.0"
] | 6 |
2021-05-04T21:29:31.000Z
|
2021-11-11T20:21:03.000Z
|
select name, description
from gcp.gcp_compute_address
where title = '{{resourceName}}'
| 28.666667 | 32 | 0.802326 |
ce667b4f3c12c57557ffb88b08c140040f2ac337
| 902 |
asm
|
Assembly
|
programs/oeis/027/A027659.asm
|
neoneye/loda
|
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
|
[
"Apache-2.0"
] | 22 |
2018-02-06T19:19:31.000Z
|
2022-01-17T21:53:31.000Z
|
programs/oeis/027/A027659.asm
|
neoneye/loda
|
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
|
[
"Apache-2.0"
] | 41 |
2021-02-22T19:00:34.000Z
|
2021-08-28T10:47:47.000Z
|
programs/oeis/027/A027659.asm
|
neoneye/loda
|
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
|
[
"Apache-2.0"
] | 5 |
2021-02-24T21:14:16.000Z
|
2021-08-09T19:48:05.000Z
|
; A027659: a(n) = binomial(n+2,2) + binomial(n+3,3) + binomial(n+4,4) + binomial(n+5,5).
; 4,18,52,121,246,455,784,1278,1992,2992,4356,6175,8554,11613,15488,20332,26316,33630,42484,53109,65758,80707,98256,118730,142480,169884,201348,237307,278226,324601,376960,435864,501908,575722,657972,749361,850630,962559,1085968,1221718,1370712,1533896,1712260,1906839,2118714,2349013,2598912,2869636,3162460,3478710,3819764,4187053,4582062,5006331,5461456,5949090,6470944,7028788,7624452,8259827,8936866,9657585,10424064,11238448,12102948,13019842,13991476,15020265,16108694,17259319,18474768,19757742,21111016,22537440,24039940,25621519,27285258,29034317,30871936,32801436,34826220,36949774,39175668,41507557,43949182,46504371,49177040,51971194,54890928,57940428,61123972,64445931,67910770,71523049,75287424,79208648,83291572,87541146,91962420,96560545
mov $1,6
add $1,$0
bin $1,5
sub $1,$0
sub $1,2
mov $0,$1
| 90.2 | 754 | 0.815965 |
e8e29b7b8972a06149daa7c111affc519cbc1ff4
| 629 |
py
|
Python
|
FormulaAccordingPrint.py
|
FreeBirdsCrew/Brainstorming_Codes
|
9d06216cd0772ce56586acff2c240a210b94ba1f
|
[
"Apache-2.0"
] | 1 |
2020-12-11T10:24:08.000Z
|
2020-12-11T10:24:08.000Z
|
FormulaAccordingPrint.py
|
FreeBirdsCrew/Brainstorming_Codes
|
9d06216cd0772ce56586acff2c240a210b94ba1f
|
[
"Apache-2.0"
] | null | null | null |
FormulaAccordingPrint.py
|
FreeBirdsCrew/Brainstorming_Codes
|
9d06216cd0772ce56586acff2c240a210b94ba1f
|
[
"Apache-2.0"
] | null | null | null |
"""
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.
Example
Let us assume the following comma separated input sequence is given to the program:
100,150,180
The output of the program should be:
18,22,24
"""
import math
c=50
h=30
value = []
items=[x for x in raw_input().split(',')]
for d in items:
value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))
print ','.join(value)
| 28.590909 | 94 | 0.694754 |
f5c8d5b28c1cabb40471ee36053b2cf3cb8e06f1
| 478 |
lua
|
Lua
|
db.lua
|
minetest-mods/turtle
|
bd7d49f1843c7e35a0e6647ef19bb6b7cae61f3c
|
[
"MIT"
] | 9 |
2016-03-15T05:11:35.000Z
|
2022-02-06T04:13:03.000Z
|
db.lua
|
minetest-mods/turtle
|
bd7d49f1843c7e35a0e6647ef19bb6b7cae61f3c
|
[
"MIT"
] | 1 |
2016-01-31T02:43:55.000Z
|
2016-01-31T14:13:10.000Z
|
db.lua
|
Novatux/turtle
|
bd7d49f1843c7e35a0e6647ef19bb6b7cae61f3c
|
[
"MIT"
] | 2 |
2016-01-26T21:04:28.000Z
|
2022-03-05T16:47:32.000Z
|
db = {}
local worldpath = minetest.get_worldpath() .. "/"
function db.read_file(filename)
local file = io.open(worldpath .. filename, "r")
if file == nil then
return {}
end
local contents = file:read("*all")
file:close()
if contents == "" or contents == nil then
return {}
end
return minetest.deserialize(contents)
end
function db.write_file(filename, data)
local file = io.open(worldpath .. filename, "w")
file:write(minetest.serialize(data))
file:close()
end
| 21.727273 | 49 | 0.692469 |
bef82410ebdce954f037259d9ca00e36eb6cf26a
| 220 |
html
|
HTML
|
src/app/components/surface/surface.component.html
|
hamzakilic/wjimg
|
d2960c1bd23e0f4366299cc183168a764e1cc9fe
|
[
"Apache-2.0"
] | 2 |
2018-04-16T17:34:12.000Z
|
2018-12-03T01:03:27.000Z
|
src/app/components/surface/surface.component.html
|
hamzakilic/photoedit_app
|
d2960c1bd23e0f4366299cc183168a764e1cc9fe
|
[
"Apache-2.0"
] | 12 |
2017-04-15T19:30:39.000Z
|
2018-01-02T15:06:42.000Z
|
src/app/components/surface/surface.component.html
|
hamzakilic/wjimg
|
d2960c1bd23e0f4366299cc183168a764e1cc9fe
|
[
"Apache-2.0"
] | null | null | null |
<canvas #renderCanvas class="canvas"
[(attr.width)]="surface.width" [(style.width.px)]="surface.width*surface.scale"
[(attr.height)]="surface.height" [(style.height.px)]="surface.height*surface.scale" >
</canvas>
| 24.444444 | 86 | 0.695455 |
fef2f39b4029c211a794b38e85c932ee09087162
| 902 |
html
|
HTML
|
Pulicat/_vti_cnf/action.html
|
vu2ow/vu2ow.github.io
|
bae8f04a89ebfe0c5ad9953e6962f8b11db7227e
|
[
"Unlicense"
] | null | null | null |
Pulicat/_vti_cnf/action.html
|
vu2ow/vu2ow.github.io
|
bae8f04a89ebfe0c5ad9953e6962f8b11db7227e
|
[
"Unlicense"
] | null | null | null |
Pulicat/_vti_cnf/action.html
|
vu2ow/vu2ow.github.io
|
bae8f04a89ebfe0c5ad9953e6962f8b11db7227e
|
[
"Unlicense"
] | null | null | null |
vti_encoding:SR|utf8-nl
vti_timelastmodified:TR|31 Jul 2015 14:50:44 -0000
vti_extenderversion:SR|12.0.0.0
vti_author:SR|VU3RGK\\kc2kb
vti_modifiedby:SR|VU3RGK\\kc2kb
vti_timecreated:TR|31 Jul 2015 14:50:44 -0000
vti_cacheddtm:TX|31 Jul 2015 14:50:44 -0000
vti_filesize:IR|1813
vti_cachedtitle:SR|Untitled 1
vti_cachedbodystyle:SR|<body>
vti_cachedlinkinfo:VX|S|Images/top_pic1.jpg H|VU3RGK\\ pictures H|index.html H|vu6p_station.html H|photos.html
vti_cachedsvcrellinks:VX|FSUS|VU3RGK/Pulicat/Images/top_pic1.jpg NHUS|VU3RGK/Pulicat/VU3RGK\\ pictures NHUS|VU3RGK/Pulicat/index.html FHUS|VU3RGK/Pulicat/vu6p_station.html NHUS|VU3RGK/Pulicat/photos.html
vti_cachedneedsrewrite:BR|false
vti_cachedhasbots:BR|false
vti_cachedhastheme:BR|false
vti_cachedhasborder:BR|false
vti_metatags:VR|HTTP-EQUIV=Content-Type text/html;\\ charset=utf-8
vti_charset:SR|utf-8
vti_title:SR|Untitled 1
vti_backlinkinfo:VX|
| 42.952381 | 203 | 0.834812 |
0033860216a5b2d31a5b0555aff2ebb229b3f111
| 136 |
swift
|
Swift
|
Examples/Example-iOS/Sources/Common/UITableViewExtension.swift
|
swaromik/Carbon
|
9dd7d8ba046010cc33a9d685661c26ade49b76fe
|
[
"Apache-2.0"
] | 1 |
2019-07-22T17:33:46.000Z
|
2019-07-22T17:33:46.000Z
|
Examples/Example-iOS/Sources/Common/UITableViewExtension.swift
|
swaromik/Carbon
|
9dd7d8ba046010cc33a9d685661c26ade49b76fe
|
[
"Apache-2.0"
] | null | null | null |
Examples/Example-iOS/Sources/Common/UITableViewExtension.swift
|
swaromik/Carbon
|
9dd7d8ba046010cc33a9d685661c26ade49b76fe
|
[
"Apache-2.0"
] | null | null | null |
import UIKit
extension UITableView {
open override func touchesShouldCancel(in view: UIView) -> Bool {
return true
}
}
| 17 | 69 | 0.676471 |
2bb495fa1d8ce642bcba8593e5419ddcb34efca6
| 662 |
asm
|
Assembly
|
programs/oeis/034/A034108.asm
|
neoneye/loda
|
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
|
[
"Apache-2.0"
] | 22 |
2018-02-06T19:19:31.000Z
|
2022-01-17T21:53:31.000Z
|
programs/oeis/034/A034108.asm
|
neoneye/loda
|
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
|
[
"Apache-2.0"
] | 41 |
2021-02-22T19:00:34.000Z
|
2021-08-28T10:47:47.000Z
|
programs/oeis/034/A034108.asm
|
neoneye/loda
|
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
|
[
"Apache-2.0"
] | 5 |
2021-02-24T21:14:16.000Z
|
2021-08-09T19:48:05.000Z
|
; A034108: Fractional part of square root of a(n) starts with 2: first term of runs.
; 5,18,28,39,52,68,85,105,126,149,175,202,232,263,296,332,369,409,450,493,539,586,636,687,740,796,853,913,974,1037,1103,1170,1240,1311,1384,1460,1537,1617,1698,1781,1867,1954,2044,2135,2228,2324,2421,2521,2622
mov $7,$0
mul $0,2
mov $3,6
lpb $0
sub $0,1
add $1,1
sub $3,1
add $0,$3
add $6,$5
add $5,6
sub $5,$6
sub $0,$5
add $0,3
trn $0,4
trn $1,6
add $1,6
mov $3,4
mov $6,0
lpe
add $1,5
mov $2,6
mov $8,$7
lpb $2
add $1,$8
sub $2,1
lpe
mov $4,$7
lpb $4
sub $4,1
add $9,$8
lpe
mov $2,1
mov $8,$9
lpb $2
add $1,$8
sub $2,1
lpe
mov $0,$1
| 15.761905 | 209 | 0.60423 |
6b4bc973a026a487da4c77d811af7630b3524a27
| 7,615 |
h
|
C
|
third_party/gecko-16/win32/include/nsIScreen.h
|
bwp/SeleniumWebDriver
|
58221fbe59fcbbde9d9a033a95d45d576b422747
|
[
"Apache-2.0"
] | 1 |
2018-02-05T04:23:18.000Z
|
2018-02-05T04:23:18.000Z
|
third_party/gecko-16/win32/include/nsIScreen.h
|
bwp/SeleniumWebDriver
|
58221fbe59fcbbde9d9a033a95d45d576b422747
|
[
"Apache-2.0"
] | null | null | null |
third_party/gecko-16/win32/include/nsIScreen.h
|
bwp/SeleniumWebDriver
|
58221fbe59fcbbde9d9a033a95d45d576b422747
|
[
"Apache-2.0"
] | null | null | null |
/*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/widget/nsIScreen.idl
*/
#ifndef __gen_nsIScreen_h__
#define __gen_nsIScreen_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIScreen */
#define NS_ISCREEN_IID_STR "d961f76e-8437-4bc6-9ada-a1c98ace9560"
#define NS_ISCREEN_IID \
{0xd961f76e, 0x8437, 0x4bc6, \
{ 0x9a, 0xda, 0xa1, 0xc9, 0x8a, 0xce, 0x95, 0x60 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIScreen : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISCREEN_IID)
enum {
BRIGHTNESS_DIM = 0U,
BRIGHTNESS_FULL = 1U,
BRIGHTNESS_LEVELS = 2U,
ROTATION_0_DEG = 0U,
ROTATION_90_DEG = 1U,
ROTATION_180_DEG = 2U,
ROTATION_270_DEG = 3U
};
/* void GetRect (out long left, out long top, out long width, out long height); */
NS_SCRIPTABLE NS_IMETHOD GetRect(PRInt32 *left NS_OUTPARAM, PRInt32 *top NS_OUTPARAM, PRInt32 *width NS_OUTPARAM, PRInt32 *height NS_OUTPARAM) = 0;
/* void GetAvailRect (out long left, out long top, out long width, out long height); */
NS_SCRIPTABLE NS_IMETHOD GetAvailRect(PRInt32 *left NS_OUTPARAM, PRInt32 *top NS_OUTPARAM, PRInt32 *width NS_OUTPARAM, PRInt32 *height NS_OUTPARAM) = 0;
/* void lockMinimumBrightness (in unsigned long brightness); */
NS_SCRIPTABLE NS_IMETHOD LockMinimumBrightness(PRUint32 brightness) = 0;
/* void unlockMinimumBrightness (in unsigned long brightness); */
NS_SCRIPTABLE NS_IMETHOD UnlockMinimumBrightness(PRUint32 brightness) = 0;
/* readonly attribute long pixelDepth; */
NS_SCRIPTABLE NS_IMETHOD GetPixelDepth(PRInt32 *aPixelDepth) = 0;
/* readonly attribute long colorDepth; */
NS_SCRIPTABLE NS_IMETHOD GetColorDepth(PRInt32 *aColorDepth) = 0;
/* attribute unsigned long rotation; */
NS_SCRIPTABLE NS_IMETHOD GetRotation(PRUint32 *aRotation) = 0;
NS_SCRIPTABLE NS_IMETHOD SetRotation(PRUint32 aRotation) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIScreen, NS_ISCREEN_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSISCREEN \
NS_SCRIPTABLE NS_IMETHOD GetRect(PRInt32 *left NS_OUTPARAM, PRInt32 *top NS_OUTPARAM, PRInt32 *width NS_OUTPARAM, PRInt32 *height NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD GetAvailRect(PRInt32 *left NS_OUTPARAM, PRInt32 *top NS_OUTPARAM, PRInt32 *width NS_OUTPARAM, PRInt32 *height NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD LockMinimumBrightness(PRUint32 brightness); \
NS_SCRIPTABLE NS_IMETHOD UnlockMinimumBrightness(PRUint32 brightness); \
NS_SCRIPTABLE NS_IMETHOD GetPixelDepth(PRInt32 *aPixelDepth); \
NS_SCRIPTABLE NS_IMETHOD GetColorDepth(PRInt32 *aColorDepth); \
NS_SCRIPTABLE NS_IMETHOD GetRotation(PRUint32 *aRotation); \
NS_SCRIPTABLE NS_IMETHOD SetRotation(PRUint32 aRotation);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSISCREEN(_to) \
NS_SCRIPTABLE NS_IMETHOD GetRect(PRInt32 *left NS_OUTPARAM, PRInt32 *top NS_OUTPARAM, PRInt32 *width NS_OUTPARAM, PRInt32 *height NS_OUTPARAM) { return _to GetRect(left, top, width, height); } \
NS_SCRIPTABLE NS_IMETHOD GetAvailRect(PRInt32 *left NS_OUTPARAM, PRInt32 *top NS_OUTPARAM, PRInt32 *width NS_OUTPARAM, PRInt32 *height NS_OUTPARAM) { return _to GetAvailRect(left, top, width, height); } \
NS_SCRIPTABLE NS_IMETHOD LockMinimumBrightness(PRUint32 brightness) { return _to LockMinimumBrightness(brightness); } \
NS_SCRIPTABLE NS_IMETHOD UnlockMinimumBrightness(PRUint32 brightness) { return _to UnlockMinimumBrightness(brightness); } \
NS_SCRIPTABLE NS_IMETHOD GetPixelDepth(PRInt32 *aPixelDepth) { return _to GetPixelDepth(aPixelDepth); } \
NS_SCRIPTABLE NS_IMETHOD GetColorDepth(PRInt32 *aColorDepth) { return _to GetColorDepth(aColorDepth); } \
NS_SCRIPTABLE NS_IMETHOD GetRotation(PRUint32 *aRotation) { return _to GetRotation(aRotation); } \
NS_SCRIPTABLE NS_IMETHOD SetRotation(PRUint32 aRotation) { return _to SetRotation(aRotation); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSISCREEN(_to) \
NS_SCRIPTABLE NS_IMETHOD GetRect(PRInt32 *left NS_OUTPARAM, PRInt32 *top NS_OUTPARAM, PRInt32 *width NS_OUTPARAM, PRInt32 *height NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetRect(left, top, width, height); } \
NS_SCRIPTABLE NS_IMETHOD GetAvailRect(PRInt32 *left NS_OUTPARAM, PRInt32 *top NS_OUTPARAM, PRInt32 *width NS_OUTPARAM, PRInt32 *height NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAvailRect(left, top, width, height); } \
NS_SCRIPTABLE NS_IMETHOD LockMinimumBrightness(PRUint32 brightness) { return !_to ? NS_ERROR_NULL_POINTER : _to->LockMinimumBrightness(brightness); } \
NS_SCRIPTABLE NS_IMETHOD UnlockMinimumBrightness(PRUint32 brightness) { return !_to ? NS_ERROR_NULL_POINTER : _to->UnlockMinimumBrightness(brightness); } \
NS_SCRIPTABLE NS_IMETHOD GetPixelDepth(PRInt32 *aPixelDepth) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPixelDepth(aPixelDepth); } \
NS_SCRIPTABLE NS_IMETHOD GetColorDepth(PRInt32 *aColorDepth) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetColorDepth(aColorDepth); } \
NS_SCRIPTABLE NS_IMETHOD GetRotation(PRUint32 *aRotation) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetRotation(aRotation); } \
NS_SCRIPTABLE NS_IMETHOD SetRotation(PRUint32 aRotation) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetRotation(aRotation); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsScreen : public nsIScreen
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISCREEN
nsScreen();
private:
~nsScreen();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsScreen, nsIScreen)
nsScreen::nsScreen()
{
/* member initializers and constructor code */
}
nsScreen::~nsScreen()
{
/* destructor code */
}
/* void GetRect (out long left, out long top, out long width, out long height); */
NS_IMETHODIMP nsScreen::GetRect(PRInt32 *left NS_OUTPARAM, PRInt32 *top NS_OUTPARAM, PRInt32 *width NS_OUTPARAM, PRInt32 *height NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void GetAvailRect (out long left, out long top, out long width, out long height); */
NS_IMETHODIMP nsScreen::GetAvailRect(PRInt32 *left NS_OUTPARAM, PRInt32 *top NS_OUTPARAM, PRInt32 *width NS_OUTPARAM, PRInt32 *height NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void lockMinimumBrightness (in unsigned long brightness); */
NS_IMETHODIMP nsScreen::LockMinimumBrightness(PRUint32 brightness)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void unlockMinimumBrightness (in unsigned long brightness); */
NS_IMETHODIMP nsScreen::UnlockMinimumBrightness(PRUint32 brightness)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute long pixelDepth; */
NS_IMETHODIMP nsScreen::GetPixelDepth(PRInt32 *aPixelDepth)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute long colorDepth; */
NS_IMETHODIMP nsScreen::GetColorDepth(PRInt32 *aColorDepth)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute unsigned long rotation; */
NS_IMETHODIMP nsScreen::GetRotation(PRUint32 *aRotation)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsScreen::SetRotation(PRUint32 aRotation)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIScreen_h__ */
| 41.840659 | 238 | 0.778726 |
3be187b0b4e7933536a1ad9b827b103021d8fe34
| 2,973 |
kt
|
Kotlin
|
plugins/api/src/main/kotlin/org/rsmod/plugins/api/protocol/codec/js5/Js5Decoder.kt
|
Rune-Server/rsmod-1
|
533909dbcf2153b472714beb52b3eb3238850a48
|
[
"0BSD"
] | null | null | null |
plugins/api/src/main/kotlin/org/rsmod/plugins/api/protocol/codec/js5/Js5Decoder.kt
|
Rune-Server/rsmod-1
|
533909dbcf2153b472714beb52b3eb3238850a48
|
[
"0BSD"
] | null | null | null |
plugins/api/src/main/kotlin/org/rsmod/plugins/api/protocol/codec/js5/Js5Decoder.kt
|
Rune-Server/rsmod-1
|
533909dbcf2153b472714beb52b3eb3238850a48
|
[
"0BSD"
] | null | null | null |
package org.rsmod.plugins.api.protocol.codec.js5
import com.github.michaelbull.logging.InlineLogger
import io.netty.buffer.ByteBuf
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.ByteToMessageDecoder
import org.rsmod.plugins.api.protocol.codec.ResponseType
import org.rsmod.plugins.api.protocol.codec.writeAcceptedResponse
import org.rsmod.plugins.api.protocol.codec.writeErrResponse
private val logger = InlineLogger()
sealed class Js5Stage {
object Handshake : Js5Stage()
object Request : Js5Stage()
}
class Js5Decoder(
private val revision: Int,
private var stage: Js5Stage = Js5Stage.Handshake
) : ByteToMessageDecoder() {
override fun decode(
ctx: ChannelHandlerContext,
buf: ByteBuf,
out: MutableList<Any>
) {
logger.trace { "Decode JS5 message (stage=$stage, channel=${ctx.channel()})" }
when (stage) {
Js5Stage.Handshake -> ctx.channel().readHandshake(buf)
Js5Stage.Request -> ctx.channel().readFileRequest(buf, out)
}
}
private fun Channel.readHandshake(buf: ByteBuf) {
val clientRevision = buf.readInt()
if (clientRevision < revision) {
logger.info {
"Handshake revision out-of-date " +
"(clientMajor=$clientRevision, serverMajor=$revision, channel=$this)"
}
writeErrResponse(ResponseType.JS5_OUT_OF_DATE)
return
}
logger.trace { "Handshake accepted (channel=$this)" }
stage = Js5Stage.Request
writeAcceptedResponse()
}
private fun Channel.readFileRequest(
buf: ByteBuf,
out: MutableList<Any>
) {
buf.markReaderIndex()
when (val opcode = buf.readByte().toInt()) {
NORMAL_FILE_REQUEST -> buf.readFileRequest(out, urgent = false)
URGENT_FILE_REQUEST -> buf.readFileRequest(out, urgent = true)
CLIENT_INIT_GAME,
CLIENT_LOAD_SCREEN,
CLIENT_INIT_OPCODE -> buf.skipBytes(3)
else -> {
logger.error { "Unhandled file request (opcode=$opcode, channel=$this)" }
buf.skipBytes(buf.readableBytes())
}
}
}
private fun ByteBuf.readFileRequest(
out: MutableList<Any>,
urgent: Boolean
) {
if (readableBytes() < Byte.SIZE_BYTES + Short.SIZE_BYTES) {
resetReaderIndex()
return
}
val archive = readUnsignedByte().toInt()
val group = readUnsignedShort()
val request = Js5Request(archive, group, urgent)
out.add(request)
}
private companion object {
private const val NORMAL_FILE_REQUEST = 0
private const val URGENT_FILE_REQUEST = 1
private const val CLIENT_INIT_GAME = 2
private const val CLIENT_LOAD_SCREEN = 3
private const val CLIENT_INIT_OPCODE = 6
}
}
| 32.67033 | 89 | 0.635049 |
23022c89b531b74add6d9f3c3659ad04541aafcb
| 1,561 |
kt
|
Kotlin
|
src/main/kotlin/com/sergeysav/voxel/client/screen/loading/LoadingUI.kt
|
SergeySave/Voxel
|
446f91f11661f1b87e1fb7b2f533f9e24b45704e
|
[
"MIT"
] | null | null | null |
src/main/kotlin/com/sergeysav/voxel/client/screen/loading/LoadingUI.kt
|
SergeySave/Voxel
|
446f91f11661f1b87e1fb7b2f533f9e24b45704e
|
[
"MIT"
] | null | null | null |
src/main/kotlin/com/sergeysav/voxel/client/screen/loading/LoadingUI.kt
|
SergeySave/Voxel
|
446f91f11661f1b87e1fb7b2f533f9e24b45704e
|
[
"MIT"
] | null | null | null |
package com.sergeysav.voxel.client.screen.loading
import com.sergeysav.voxel.client.nuklear.Gui
import com.sergeysav.voxel.client.nuklear.GuiWindow
import com.sergeysav.voxel.client.nuklear.HAlign
import com.sergeysav.voxel.common.Voxel
import org.lwjgl.nuklear.Nuklear
/**
* @author sergeys
*
* @constructor Creates a new LoadingUI
*/
class LoadingUI : GuiWindow("Loading") {
fun layout(gui: Gui, width: Float, height: Float) {
nkEditing(gui) {
window.background.hidden {
window(0f, 0f, width, height,
Nuklear.NK_WINDOW_NO_INPUT or
Nuklear.NK_WINDOW_ROM or
Nuklear.NK_WINDOW_NO_SCROLLBAR) {
dynamicRow(1, (height - LOADING_TEXT_HEIGHT/* - LOADING_BAR_HEIGHT - LOADING_REASON_HEIGHT*/) / 2f) {}
dynamicRow(1, LOADING_TEXT_HEIGHT) {
label("Loading...", HAlign.CENTER)
}
// dynamicRow(1, LOADING_BAR_HEIGHT) {
// progressBar(Voxel.getCurrentLoadAmount(), Voxel.getMaxLoadAmount(), false)
// }
// dynamicRow(1, LOADING_REASON_HEIGHT) {
// label(Voxel.getCurrentLoadStatus(), HAlign.CENTER)
// }
}
}
}
}
companion object {
private const val LOADING_TEXT_HEIGHT = 20f
// private const val LOADING_BAR_HEIGHT = 20f
// private const val LOADING_REASON_HEIGHT = 20f
}
}
| 36.302326 | 122 | 0.574632 |
f5a2e263d25e7c6612696fc01c9bb197b7040dcf
| 1,349 |
rs
|
Rust
|
src/libstd/sys/vxworks/fast_thread_local.rs
|
MOZGIII/rust
|
e3976fff44e6ce14c2f92252e6a807800b9aa7c0
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 15 |
2015-12-17T18:20:31.000Z
|
2019-12-10T20:07:24.000Z
|
src/libstd/sys/vxworks/fast_thread_local.rs
|
MOZGIII/rust
|
e3976fff44e6ce14c2f92252e6a807800b9aa7c0
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 8 |
2017-03-16T17:51:46.000Z
|
2017-07-18T01:47:29.000Z
|
src/libstd/sys/vxworks/fast_thread_local.rs
|
MOZGIII/rust
|
e3976fff44e6ce14c2f92252e6a807800b9aa7c0
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 10 |
2016-12-13T07:07:21.000Z
|
2022-03-20T06:08:58.000Z
|
#![cfg(target_thread_local)]
#![unstable(feature = "thread_local_internals", issue = "0")]
// Since what appears to be glibc 2.18 this symbol has been shipped which
// GCC and clang both use to invoke destructors in thread_local globals, so
// let's do the same!
//
// Note, however, that we run on lots older linuxes, as well as cross
// compiling from a newer linux to an older linux, so we also have a
// fallback implementation to use as well.
//
// Due to rust-lang/rust#18804, make sure this is not generic!
pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
use crate::mem;
use crate::sys_common::thread_local::register_dtor_fallback;
extern {
#[linkage = "extern_weak"]
static __dso_handle: *mut u8;
#[linkage = "extern_weak"]
static __cxa_thread_atexit_impl: *const libc::c_void;
}
if !__cxa_thread_atexit_impl.is_null() {
type F = unsafe extern fn(dtor: unsafe extern fn(*mut u8),
arg: *mut u8,
dso_handle: *mut u8) -> libc::c_int;
mem::transmute::<*const libc::c_void, F>(__cxa_thread_atexit_impl)
(dtor, t, &__dso_handle as *const _ as *mut _);
return
}
register_dtor_fallback(t, dtor);
}
pub fn requires_move_before_drop() -> bool {
false
}
| 36.459459 | 75 | 0.640474 |
bb994ed8b18b232e424dbc14be5372160507fcfd
| 5,174 |
rs
|
Rust
|
src/rust/iced-x86/src/decoder/handlers_fpu.rs
|
Ralith/iced
|
76f4101c5eb19e190d21a8d0c8d1e615636f0753
|
[
"MIT"
] | 1 |
2021-01-13T07:21:32.000Z
|
2021-01-13T07:21:32.000Z
|
src/rust/iced-x86/src/decoder/handlers_fpu.rs
|
Ralith/iced
|
76f4101c5eb19e190d21a8d0c8d1e615636f0753
|
[
"MIT"
] | null | null | null |
src/rust/iced-x86/src/decoder/handlers_fpu.rs
|
Ralith/iced
|
76f4101c5eb19e190d21a8d0c8d1e615636f0753
|
[
"MIT"
] | null | null | null |
/*
Copyright (C) 2018-2019 de4dot@gmail.com
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use super::handlers::*;
use super::*;
#[allow(non_camel_case_types)]
#[repr(C)]
pub(super) struct OpCodeHandler_ST_STi {
decode: OpCodeHandlerDecodeFn,
has_modrm: bool,
code: u32,
}
impl OpCodeHandler_ST_STi {
pub(super) fn new(code: u32) -> Self {
Self { decode: OpCodeHandler_ST_STi::decode, has_modrm: true, code }
}
fn decode(self_ptr: *const OpCodeHandler, decoder: &mut Decoder, instruction: &mut Instruction) {
let this = unsafe { &*(self_ptr as *const Self) };
debug_assert_eq!(EncodingKind::Legacy, decoder.state.encoding());
super::instruction_internal::internal_set_code_u32(instruction, this.code);
const_assert_eq!(0, OpKind::Register as u32);
//super::instruction_internal::internal_set_op0_kind(instruction, OpKind::Register);
super::instruction_internal::internal_set_op0_register_u32(instruction, Register::ST0 as u32);
const_assert_eq!(0, OpKind::Register as u32);
//super::instruction_internal::internal_set_op1_kind(instruction, OpKind::Register);
super::instruction_internal::internal_set_op1_register_u32(instruction, Register::ST0 as u32 + decoder.state.rm);
}
}
#[allow(non_camel_case_types)]
#[repr(C)]
pub(super) struct OpCodeHandler_STi_ST {
decode: OpCodeHandlerDecodeFn,
has_modrm: bool,
code: u32,
}
impl OpCodeHandler_STi_ST {
pub(super) fn new(code: u32) -> Self {
Self { decode: OpCodeHandler_STi_ST::decode, has_modrm: true, code }
}
fn decode(self_ptr: *const OpCodeHandler, decoder: &mut Decoder, instruction: &mut Instruction) {
let this = unsafe { &*(self_ptr as *const Self) };
debug_assert_eq!(EncodingKind::Legacy, decoder.state.encoding());
super::instruction_internal::internal_set_code_u32(instruction, this.code);
const_assert_eq!(0, OpKind::Register as u32);
//super::instruction_internal::internal_set_op0_kind(instruction, OpKind::Register);
super::instruction_internal::internal_set_op0_register_u32(instruction, Register::ST0 as u32 + decoder.state.rm);
const_assert_eq!(0, OpKind::Register as u32);
//super::instruction_internal::internal_set_op1_kind(instruction, OpKind::Register);
super::instruction_internal::internal_set_op1_register_u32(instruction, Register::ST0 as u32);
}
}
#[allow(non_camel_case_types)]
#[repr(C)]
pub(super) struct OpCodeHandler_STi {
decode: OpCodeHandlerDecodeFn,
has_modrm: bool,
code: u32,
}
impl OpCodeHandler_STi {
pub(super) fn new(code: u32) -> Self {
Self { decode: OpCodeHandler_STi::decode, has_modrm: true, code }
}
fn decode(self_ptr: *const OpCodeHandler, decoder: &mut Decoder, instruction: &mut Instruction) {
let this = unsafe { &*(self_ptr as *const Self) };
debug_assert_eq!(EncodingKind::Legacy, decoder.state.encoding());
super::instruction_internal::internal_set_code_u32(instruction, this.code);
const_assert_eq!(0, OpKind::Register as u32);
//super::instruction_internal::internal_set_op0_kind(instruction, OpKind::Register);
super::instruction_internal::internal_set_op0_register_u32(instruction, Register::ST0 as u32 + decoder.state.rm);
}
}
#[allow(non_camel_case_types)]
#[repr(C)]
pub(super) struct OpCodeHandler_Mf {
decode: OpCodeHandlerDecodeFn,
has_modrm: bool,
code16: u32,
code32: u32,
}
impl OpCodeHandler_Mf {
pub(super) fn new(code: u32) -> Self {
Self { decode: OpCodeHandler_Mf::decode, has_modrm: true, code16: code, code32: code }
}
pub(super) fn new1(code16: u32, code32: u32) -> Self {
Self { decode: OpCodeHandler_Mf::decode, has_modrm: true, code16, code32 }
}
fn decode(self_ptr: *const OpCodeHandler, decoder: &mut Decoder, instruction: &mut Instruction) {
let this = unsafe { &*(self_ptr as *const Self) };
debug_assert_eq!(EncodingKind::Legacy, decoder.state.encoding());
if decoder.state.operand_size != OpSize::Size16 {
super::instruction_internal::internal_set_code_u32(instruction, this.code32);
} else {
super::instruction_internal::internal_set_code_u32(instruction, this.code16);
}
debug_assert_ne!(3, decoder.state.mod_);
super::instruction_internal::internal_set_op0_kind(instruction, OpKind::Memory);
decoder.read_op_mem(instruction);
}
}
| 38.902256 | 115 | 0.763626 |
7a917740e05f6c6e3675b06eaccb07ffe2e2a859
| 703 |
rs
|
Rust
|
src/efuse/efuse_int_raw.rs
|
ducktec/esp32c3
|
64b9547e200a3ee7e6587d81178be8732e99bee9
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
src/efuse/efuse_int_raw.rs
|
ducktec/esp32c3
|
64b9547e200a3ee7e6587d81178be8732e99bee9
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
src/efuse/efuse_int_raw.rs
|
ducktec/esp32c3
|
64b9547e200a3ee7e6587d81178be8732e99bee9
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
#[doc = "Reader of register EFUSE_INT_RAW"]
pub type R = crate::R<u32, super::EFUSE_INT_RAW>;
#[doc = "Reader of field `EFUSE_PGM_DONE_INT_RAW`"]
pub type EFUSE_PGM_DONE_INT_RAW_R = crate::R<bool, bool>;
#[doc = "Reader of field `EFUSE_READ_DONE_INT_RAW`"]
pub type EFUSE_READ_DONE_INT_RAW_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 1"]
#[inline(always)]
pub fn efuse_pgm_done_int_raw(&self) -> EFUSE_PGM_DONE_INT_RAW_R {
EFUSE_PGM_DONE_INT_RAW_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0"]
#[inline(always)]
pub fn efuse_read_done_int_raw(&self) -> EFUSE_READ_DONE_INT_RAW_R {
EFUSE_READ_DONE_INT_RAW_R::new((self.bits & 0x01) != 0)
}
}
| 37 | 72 | 0.671408 |
8c94df4da911d834988f60373b47f3960029885a
| 627 |
asm
|
Assembly
|
oeis/100/A100178.asm
|
neoneye/loda-programs
|
84790877f8e6c2e821b183d2e334d612045d29c0
|
[
"Apache-2.0"
] | 11 |
2021-08-22T19:44:55.000Z
|
2022-03-20T16:47:57.000Z
|
oeis/100/A100178.asm
|
neoneye/loda-programs
|
84790877f8e6c2e821b183d2e334d612045d29c0
|
[
"Apache-2.0"
] | 9 |
2021-08-29T13:15:54.000Z
|
2022-03-09T19:52:31.000Z
|
oeis/100/A100178.asm
|
neoneye/loda-programs
|
84790877f8e6c2e821b183d2e334d612045d29c0
|
[
"Apache-2.0"
] | 3 |
2021-08-22T20:56:47.000Z
|
2021-09-29T06:26:12.000Z
|
; A100178: Structured hexagonal diamond numbers (vertex structure 5).
; 1,8,29,72,145,256,413,624,897,1240,1661,2168,2769,3472,4285,5216,6273,7464,8797,10280,11921,13728,15709,17872,20225,22776,25533,28504,31697,35120,38781,42688,46849,51272,55965,60936,66193,71744,77597,83760,90241,97048,104189,111672,119505,127696,136253,145184,154497,164200,174301,184808,195729,207072,218845,231056,243713,256824,270397,284440,298961,313968,329469,345472,361985,379016,396573,414664,433297,452480,472221,492528,513409,534872,556925,579576,602833,626704,651197,676320,702081,728488
mul $0,4
add $0,4
mov $1,$0
bin $0,3
add $0,$1
div $0,8
| 62.7 | 499 | 0.800638 |
b5dc99cc56bd473ab3ff07ca7c25a3bfdc9fc207
| 2,616 |
asm
|
Assembly
|
3-Assemble(80x86)/lab-1/lab1.asm
|
ftxj/4th-Semester
|
1d5c7e7e028176524bdafc64078775d42b73b51c
|
[
"MIT"
] | null | null | null |
3-Assemble(80x86)/lab-1/lab1.asm
|
ftxj/4th-Semester
|
1d5c7e7e028176524bdafc64078775d42b73b51c
|
[
"MIT"
] | null | null | null |
3-Assemble(80x86)/lab-1/lab1.asm
|
ftxj/4th-Semester
|
1d5c7e7e028176524bdafc64078775d42b73b51c
|
[
"MIT"
] | null | null | null |
;.386
STACK SEGMENT ;USE16 STACK
DB 300 DUP(0)
STACK ENDS
DATA SEGMENT; USE16
N EQU 30
POIN DW 0
BUF DB 'zhangsan', 0, 0
DB 100, 85, 80, ?
DB 'lisi', 6 DUP(0)
DB 80, 100, 70, ?
DB 'B',0,0,0,0,0,0,0,0,0
DB 10, 20, 12, ?
DB N-4 DUP('TempValue',0, 80, 90, 95, ?)
DB 'xinjie', 0, 0, 0, 0
DB 100, 100, 100, ?
IN_NAME DB 11
DB 0
DB 11 DUP(0)
CRLF DB 0DH, 0AH, '$'
MSG1 DB 0AH, 0DH, 'Please Input Your Name :$'
MSG2 DB 0AH, 0DH, 'Not Find This Student!:$'
MSGA DB 0AH, 0DH, 'A!$'
MSGB DB 0AH, 0DH, 'B!$'
MSGC DB 0AH, 0DH, 'C!$'
MSGD DB 0AH, 0DH, 'D!$'
DATA ENDS
CODE SEGMENT ;USE16
ASSUME DS:DATA, CS:CODE, SS:STACK
START:
MOV AX, DATA
MOV DS, AX
CALL SET_AVERANGE_GRADE
INPUT:
MOV DX, OFFSET MSG1
MOV AH, 9
INT 21H ;功能一一小题
LEA DX, IN_NAME
MOV AH, 10
INT 21H ;功能一二小题
MOV BL, IN_NAME + 1
MOV BH, IN_NAME + 2
CMP BL, 0
JE INPUT
CMP BH, 'q'
JE DIE ;功能一 三小题
MOV BH, 0
FIND:
MOV CX, N
MOV DI, 0
FIND_S:
MOV SI, 0
PUSH CX
MOV CX, BX
CALL EQUAL
POP CX
CMP SI, BX
JE SUCCESS_FIND
CONTINUE_FIND:
CMP CX, 1
JE NOT_FIND
ADD DI, 14
LOOP FIND_S
DIE:
MOV AH, 4CH
INT 21H
NOT_FIND:
MOV DX, OFFSET MSG2
MOV AH, 9
INT 21H
JMP INPUT
SUCCESS_FIND:
ADD SI, DI
CMP [BUF + SI], 0
JNE CONTINUE_FIND
SUB SI, DI
MOV WORD PTR [POIN], OFFSET BUF + 10
ADD WORD PTR [POIN], DI
CALL G_ABCD
JMP INPUT
;使用寄存器 AX,SI
;需要传入参数 SI = 0
EQUAL:
MOV AL, [IN_NAME + SI + 2]
ADD SI, DI
CMP AL, [BUF + SI]
JNE NOT_EQUAL
SUB SI, DI
INC SI
LOOP EQUAL
NOT_EQUAL:
RET
G_ABCD:
PUSH AX
PUSH DX
PUSH SI
MOV DX, OFFSET CRLF
MOV AH, 9
INT 21H
MOV SI, [POIN]
ADD SI, 3
MOV AX, [SI]
MOV AH, 0
SUB AL, 90
JS G_BCD
MOV DL, 'A'
JMP SCREEN
G_BCD:
MOV AX, [SI]
MOV AH, 0
SUB AL, 80
JS G_CD
MOV DL, 'B'
JMP SCREEN
G_CD:
MOV AX, [SI]
MOV AH, 0
SUB AL, 70
JS G_D
MOV DL, 'C'
JMP SCREEN
G_D:
MOV DL, 'D'
JMP SCREEN
SCREEN:
MOV AH, 2
INT 21H
POP SI
POP DX
POP AX
RET
SET_AVERANGE_GRADE:
PUSH SI
PUSH AX
PUSH BX
PUSH CX
PUSH DX
MOV SI, 10
MOV CX, N
MATH:
MOV AX, 0
MOV BX, 0
MOV DX, 0
MOV AL, [BUF + SI]
MOV AH, 2
MUL AH ;AX IS CHINESE * 2 <= 200 16 IS ENOUGH
MOV BL, [BUF + SI + 1] ;MATH GRADE
MOV BH, 0
ADD BX, AX
MOV AL, [BUF + SI + 2] ;ENGLISH
MOV AH, 0
MOV DL, 2
DIV DL
ADD BX, AX
MOV AX, 2
MUL BX
MOV BL, 7
DIV BL
MOV [BUF + SI + 3], AL
ADD SI, 14
LOOP MATH
POP DX
POP CX
POP BX
POP AX
POP SI
RET
CODE ENDS
END START
| 13.84127 | 49 | 0.570336 |
be8970cb3018c5498733a7e0c820cca277b6aea8
| 9,263 |
kt
|
Kotlin
|
datacapture/src/main/java/com/google/android/fhir/datacapture/QuestionnaireViewModel.kt
|
jingtang10/android-fhir
|
80a9de1813df8ba95c7413a2e13f96e73d41afb2
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
datacapture/src/main/java/com/google/android/fhir/datacapture/QuestionnaireViewModel.kt
|
jingtang10/android-fhir
|
80a9de1813df8ba95c7413a2e13f96e73d41afb2
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
datacapture/src/main/java/com/google/android/fhir/datacapture/QuestionnaireViewModel.kt
|
jingtang10/android-fhir
|
80a9de1813df8ba95c7413a2e13f96e73d41afb2
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.datacapture
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import ca.uhn.fhir.context.FhirContext
import com.google.android.fhir.datacapture.enablement.EnablementEvaluator
import com.google.android.fhir.datacapture.views.QuestionnaireItemViewItem
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.map
import org.hl7.fhir.r4.model.Questionnaire
import org.hl7.fhir.r4.model.QuestionnaireResponse
internal class QuestionnaireViewModel(state: SavedStateHandle) : ViewModel() {
/** The current questionnaire as questions are being answered. */
private val questionnaire: Questionnaire
init {
val questionnaireJson: String = state[QuestionnaireFragment.BUNDLE_KEY_QUESTIONNAIRE]!!
questionnaire =
FhirContext.forR4().newJsonParser().parseResource(questionnaireJson) as Questionnaire
}
/** The current questionnaire response as questions are being answered. */
private var questionnaireResponse: QuestionnaireResponse
init {
val questionnaireJsonResponseString: String? =
state[QuestionnaireFragment.BUNDLE_KEY_QUESTIONNAIRE_RESPONSE]
if (questionnaireJsonResponseString != null) {
questionnaireResponse =
FhirContext.forR4().newJsonParser().parseResource(questionnaireJsonResponseString) as
QuestionnaireResponse
validateQuestionniareResponseItems(questionnaire.item, questionnaireResponse.item)
} else {
questionnaireResponse =
QuestionnaireResponse().apply {
questionnaire = this@QuestionnaireViewModel.questionnaire.id
}
// Retain the hierarchy and order of items within the questionnaire as specified in the
// standard. See https://www.hl7.org/fhir/questionnaireresponse.html#notes.
questionnaire.item.forEach {
questionnaireResponse.addItem(it.createQuestionnaireResponseItem())
}
}
}
/** Map from link IDs to questionnaire response items. */
private val linkIdToQuestionnaireResponseItemMap =
createLinkIdToQuestionnaireResponseItemMap(questionnaireResponse.item)
/** Tracks modifications in order to update the UI. */
private val modificationCount = MutableStateFlow(0)
/** Callback function to update the UI. */
private val questionnaireResponseItemChangedCallback = { modificationCount.value += 1 }
internal val questionnaireItemViewItemList
get() = getQuestionnaireItemViewItemList(questionnaire.item, questionnaireResponse.item)
/** [QuestionnaireItemViewItem] s to be displayed in the UI. */
internal val questionnaireItemViewItemListFlow: Flow<List<QuestionnaireItemViewItem>> =
modificationCount.map { questionnaireItemViewItemList }
/** The current [QuestionnaireResponse] captured by the UI. */
fun getQuestionnaireResponse(): QuestionnaireResponse = questionnaireResponse
private fun createLinkIdToQuestionnaireResponseItemMap(
questionnaireResponseItemList: List<QuestionnaireResponse.QuestionnaireResponseItemComponent>
): Map<String, QuestionnaireResponse.QuestionnaireResponseItemComponent> {
val linkIdToQuestionnaireResponseItemMap =
questionnaireResponseItemList.map { it.linkId to it }.toMap().toMutableMap()
for (item in questionnaireResponseItemList) {
linkIdToQuestionnaireResponseItemMap.putAll(
createLinkIdToQuestionnaireResponseItemMap(item.item)
)
}
return linkIdToQuestionnaireResponseItemMap
}
/**
* Traverse (DFS) through the list of questionnaire items , the list of questionnaire response
* items and the list of items in the questionnaire response answer list and populate
* [questionnaireItemViewItemList] with matching pairs of questionnaire item and questionnaire
* response item.
*
* The traverse is carried out in the two lists in tandem. The two lists should be structurally
* identical.
*/
private fun getQuestionnaireItemViewItemList(
questionnaireItemList: List<Questionnaire.QuestionnaireItemComponent>,
questionnaireResponseItemList: List<QuestionnaireResponse.QuestionnaireResponseItemComponent>
): List<QuestionnaireItemViewItem> {
val questionnaireItemViewItemList = mutableListOf<QuestionnaireItemViewItem>()
val questionnaireItemListIterator = questionnaireItemList.iterator()
val questionnaireResponseItemListIterator = questionnaireResponseItemList.iterator()
while (questionnaireItemListIterator.hasNext() &&
questionnaireResponseItemListIterator.hasNext()) {
val questionnaireItem = questionnaireItemListIterator.next()
val questionnaireResponseItem = questionnaireResponseItemListIterator.next()
val enabled =
EnablementEvaluator.evaluate(questionnaireItem) {
(linkIdToQuestionnaireResponseItemMap[it] ?: return@evaluate null)
}
if (enabled) {
questionnaireItemViewItemList.add(
QuestionnaireItemViewItem(
questionnaireItem,
questionnaireResponseItem,
questionnaireResponseItemChangedCallback
)
)
questionnaireItemViewItemList.addAll(
getQuestionnaireItemViewItemList(questionnaireItem.item, questionnaireResponseItem.item)
)
if (!questionnaireItem.type.equals(Questionnaire.QuestionnaireItemType.GROUP)) {
questionnaireResponseItem.answer?.forEach {
if (it.item.size > 0) {
questionnaireItemViewItemList.addAll(
getQuestionnaireItemViewItemList(questionnaireItem.item, it.item)
)
}
}
}
}
}
return questionnaireItemViewItemList
}
}
/**
* Creates a [QuestionnaireResponse.QuestionnaireResponseItemComponent] from the provided
* [Questionnaire.QuestionnaireItemComponent].
*
* The hierarchy and order of child items will be retained as specified in the standard. See
* https://www.hl7.org/fhir/questionnaireresponse.html#notes for more details.
*/
private fun Questionnaire.QuestionnaireItemComponent.createQuestionnaireResponseItem():
QuestionnaireResponse.QuestionnaireResponseItemComponent {
return QuestionnaireResponse.QuestionnaireResponseItemComponent().apply {
linkId = this@createQuestionnaireResponseItem.linkId
this@createQuestionnaireResponseItem.item.forEach {
this.addItem(it.createQuestionnaireResponseItem())
}
}
}
/**
* Traverse (DFS) through the list of questionnaire items and the list of questionnaire response
* items and check if the linkid of the matching pairs of questionnaire item and questionnaire
* response item are equal. The traverse is carried out in the two lists in tandem. The two lists
* should be structurally identical.
*/
private fun validateQuestionniareResponseItems(
questionnaireItemList: List<Questionnaire.QuestionnaireItemComponent>,
questionnaireResponseItemList: List<QuestionnaireResponse.QuestionnaireResponseItemComponent>
) {
val questionnaireItemListIterator = questionnaireItemList.iterator()
val questionnaireResponseItemListIterator = questionnaireResponseItemList.iterator()
while (questionnaireItemListIterator.hasNext() &&
questionnaireResponseItemListIterator.hasNext()) {
// TODO: Validate type and item nesting within answers for repeated answers
// https://github.com/google/android-fhir/issues/286
val questionnaireItem = questionnaireItemListIterator.next()
val questionnaireResponseItem = questionnaireResponseItemListIterator.next()
if (!questionnaireItem.linkId.equals(questionnaireResponseItem.linkId))
throw IllegalArgumentException(
"Mismatching linkIds for questionnaire item ${questionnaireItem.linkId} and " +
"questionnaire response item ${questionnaireResponseItem.linkId}"
)
if (questionnaireItem.type.equals(Questionnaire.QuestionnaireItemType.GROUP)) {
validateQuestionniareResponseItems(questionnaireItem.item, questionnaireResponseItem.item)
} else {
validateQuestionniareResponseItems(
questionnaireItem.item,
questionnaireResponseItem.answer.first().item
)
}
}
if (questionnaireItemListIterator.hasNext() xor questionnaireResponseItemListIterator.hasNext()) {
if (questionnaireItemListIterator.hasNext()) {
throw IllegalArgumentException(
"No matching questionnaire response item for questionnaire item ${questionnaireItemListIterator.next().linkId}"
)
} else {
throw IllegalArgumentException(
"No matching questionnaire item for questionnaire response item ${questionnaireResponseItemListIterator.next().linkId}"
)
}
}
}
| 44.533654 | 127 | 0.768002 |
b8990a433ead2a2574955f31a541c7da37713840
| 4,107 |
rs
|
Rust
|
src/profile/messages/totals.rs
|
thegedge/fittle
|
350feef2faaac7d66985ab5eb2274c9d039ce22f
|
[
"MIT"
] | 2 |
2019-03-17T15:50:55.000Z
|
2019-03-18T05:27:34.000Z
|
src/profile/messages/totals.rs
|
thegedge/fittle
|
350feef2faaac7d66985ab5eb2274c9d039ce22f
|
[
"MIT"
] | null | null | null |
src/profile/messages/totals.rs
|
thegedge/fittle
|
350feef2faaac7d66985ab5eb2274c9d039ce22f
|
[
"MIT"
] | null | null | null |
// DO NOT EDIT -- generated code
use byteorder::{
ByteOrder,
ReadBytesExt
};
use serde::Serialize;
#[allow(unused_imports)]
use crate::bits::BitReader;
#[allow(unused_imports)]
use crate::fields::{
Field,
FieldContent,
FieldDefinition,
};
#[derive(Debug, Default, Serialize)]
pub struct Totals {
#[serde(skip_serializing_if = "Option::is_none")]
active_time: Option<crate::fields::Time>,
#[serde(skip_serializing_if = "Option::is_none")]
calories: Option<crate::fields::Energy>,
#[serde(skip_serializing_if = "Option::is_none")]
distance: Option<crate::fields::Length>,
#[serde(skip_serializing_if = "Option::is_none")]
elapsed_time: Option<crate::fields::Time>,
#[serde(skip_serializing_if = "Option::is_none")]
message_index: Option<crate::profile::enums::MessageIndex>,
#[serde(skip_serializing_if = "Option::is_none")]
sessions: Option<u16>,
#[serde(skip_serializing_if = "Option::is_none")]
sport: Option<crate::profile::enums::Sport>,
#[serde(skip_serializing_if = "Option::is_none")]
sport_index: Option<u8>,
#[serde(skip_serializing_if = "Option::is_none")]
timer_time: Option<crate::fields::Time>,
#[serde(skip_serializing_if = "Option::is_none")]
timestamp: Option<crate::fields::DateTime>,
}
impl Totals {
pub fn from_fields<Order, Reader>(reader: &mut Reader, field_defs: &Vec<FieldDefinition>)
-> Result<Self, std::io::Error>
where
Order: ByteOrder,
Reader: ReadBytesExt,
{
let mut msg: Self = Default::default();
for field_def in field_defs {
let (number, field) = field_def.content_from::<Order, Reader>(reader)?;
msg.from_content(number, field);
}
Ok(msg)
}
fn from_content(&mut self, number: u8, field: Field) {
match number {
0 => {
self.timer_time =field.one().map(|v| {
let value = u32::from(v);
(crate::fields::Time::new::<uom::si::time::second, u32>)(value)
})
},
1 => {
self.distance =field.one().map(|v| {
let value = u32::from(v);
(crate::fields::Length::new::<uom::si::length::meter, u32>)(value)
})
},
2 => {
self.calories =field.one().map(|v| {
let value = u32::from(v);
(crate::fields::Energy::new::<uom::si::energy::kilocalorie, u32>)(value)
})
},
3 => {
self.sport =field.one().map(|v| {
let value = crate::profile::enums::Sport::from(v);
value
})
},
4 => {
self.elapsed_time =field.one().map(|v| {
let value = u32::from(v);
(crate::fields::Time::new::<uom::si::time::second, u32>)(value)
})
},
5 => {
self.sessions =field.one().map(|v| {
let value = u16::from(v);
value
})
},
6 => {
self.active_time =field.one().map(|v| {
let value = u32::from(v);
(crate::fields::Time::new::<uom::si::time::second, u32>)(value)
})
},
9 => {
self.sport_index =field.one().map(|v| {
let value = u8::from(v);
value
})
},
253 => {
self.timestamp =field.one().map(|v| {
let value = crate::fields::DateTime::from(v);
value
})
},
254 => {
self.message_index =field.one().map(|v| {
let value = crate::profile::enums::MessageIndex::from(v);
value
})
},
_ => (),
}
}
}
| 28.324138 | 93 | 0.475043 |
bfcf6b6ddd6e7623fbc90a42affde0bf66769505
| 7,926 |
rs
|
Rust
|
src/lib.rs
|
ZenGo-X/kms-ed25519
|
702cf7f50bb5824be1ef1258db23678660555f9a
|
[
"MIT"
] | null | null | null |
src/lib.rs
|
ZenGo-X/kms-ed25519
|
702cf7f50bb5824be1ef1258db23678660555f9a
|
[
"MIT"
] | null | null | null |
src/lib.rs
|
ZenGo-X/kms-ed25519
|
702cf7f50bb5824be1ef1258db23678660555f9a
|
[
"MIT"
] | null | null | null |
//! # KMS-Edwards25519
//! The `kms-edwards25519` crate is intended to provide an HD-wallet functionality
//! working in a [BIP-32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki)
//! like fashion for [Ed25519](https://datatracker.ietf.org/doc/html/rfc8032) keys.
//!
//! **This crate supports only non-hardened derivation mode.**
//!
//! In BIP-32 non-hardened key derivation scheme, a private key $x$ can be used to derive a series of private keys
//! $x_1,x_2,...$. Similarly, $x$'s matching public key $Y=x\cdot B$ (for some bapoint $B$ of the curve) can
//! be used to derive a series of public keys $Y_1,Y_2,...$ such that $Y_i$ is $x_i$'s matching public key. (i.e. $Y_i=x_i \cdot B$ for all $i$)
//!
//! Given the private key $x$ any key $x_i$ can be computed as follows:
//! \\[ x_i = x + h((x\cdot B) || i) \\]
//!
//! Similarly, from the public key $Y$ each $Y_i$ can be computed as follows:
//! \\[ Y_i = Y + h(Y || i)\cdot B \\]
//!
//! Since this crate is expected to be used with ZenGo's MPC implementation[^impl_musig_link]
//! of MuSig2[^musig2_paper] we are not allows the derivation of the private key.
//!
//! [^impl_musig_link]: <https://github.com/ZenGo-X/two-party-musig2-eddsa>
//!
//! [^musig2_paper]: <https://eprint.iacr.org/2020/1261.pdf>
//!
//! # Why no private key derivation?
//! Ed25519, a signature scheme over Edwards25519 curve based on Schnorr's Zero-Knowledge protocol for the knowledge of a
//! discrete logarithm, yields a signature of the form $(R,s)$ for a message $M$ associated with key pair $(x,Y)$ such that:
//!
//! 1. $R = r \cdot B$ for some scalar $r$.
//! 2. $s = r + H(R||Y||M) \cdot x$
//!
//! Now, given keypair $(x,Y)$ say we want to sign a message $M$ using a derived key $(x_i,Y_i)$ derived in non-hardened mode.
//! The derived keys are:
//! \\[
//! \begin{aligned}
//! x_i &= x + \overbrace{h((x\cdot B) || i)}^{\delta_i} \\\\
//! Y_i &= Y + \overbrace{h(Y || i)}^{\delta_i}\cdot B
//! \end{aligned}
//! \\]
//! By denoting $\delta_i = h(Y || i)$ we can write the derived keys as follows:
//! \\[
//! \begin{aligned}
//! x_i &= x + \delta_i \\\\
//! Y_i &= Y + \delta_i\cdot B
//! \end{aligned}
//! \\]
//!
//! Assuming $Y$ is known to all signing parties (if only one party, it is true, in multiparty setting it may not
//! always be the case) then each signing party can compute $\delta_i$ locally from $Y$.
//!
//! A signature for $(x_i,Y_i)$ on message $M$ would therefore be $(R,s)$ such that:
//! - $R = r \cdot B$ for some scalar $r$.
//! - $s = r + H(R || Y_i || M)\cdot x_i$
//!
//! For convenience, let's denote the Fiat-Shamir challenge as $c = H(R || Y_i || M)$,
//! notice that just like $\delta_i$ each signing party can also compute locally $c$.
//! By giving a deeper look into $s$ we get:
//! \\[
//! \begin{aligned}
//! s &= r + c \cdot x_i \\\\
//! &= \underbrace{r + c \cdot x}_{A} + \underbrace{c \cdot \delta_i}_B \\\\
//! \end{aligned}
//! \\]
//!
//! Now, $A$ can be computed using any regular signature scheme using the **original** private key $x$ (without any derivation),
//! we just have to make sure the Fiat-Shamir challenge used to sign is computed using the derived public key $Y_i$
//! instead of the original public key $Y$.
//!
//! To the resulting value of $A$, we can add $B$ which can be computed by any party owning $Y$ since both $c$ and $\delta_i$
//! can be computed locally by and party owning $Y$.
//!
//! Therefore, we don't need to derive the private key in any point to sign a message for a derived key which is why this library doesn't export a function deriving a private key.
//!
//! # Compatability
//! Notice that no exact specification has been published for a standard HD key derivation for Ed25519.
//! Therefore, the derived keys are not expected to be compatible with any other existing library on the internet.
use blake2::{Blake2s256, Digest};
use curve25519_dalek::constants::ED25519_BASEPOINT_POINT;
use curve25519_dalek::edwards::EdwardsPoint;
use curve25519_dalek::scalar::Scalar;
fn compute_delta(p: &EdwardsPoint, i: u32) -> Scalar {
let mut hasher = Blake2s256::new();
hasher.update(p.compress().0);
hasher.update(i.to_be_bytes());
let hash_bits: [u8; 32] = hasher.finalize().try_into().unwrap();
// Despite BIP-32 parse_256 considers bytes as big endian.
// Ed25519 considers scalars as little endian so we will
// go with little endian here.
if hash_bits[0] & 240 == 0 {
Scalar::from_bits(hash_bits)
} else {
Scalar::from_bytes_mod_order(hash_bits)
}
}
fn derive_delta_and_public_key_from_path(
pk: &EdwardsPoint,
path: &[u32],
) -> (Scalar, EdwardsPoint) {
path.iter()
.fold((Scalar::zero(), *pk), |(delta_sum, pk_derived), &i| {
let delta = compute_delta(&pk_derived, i);
(
delta_sum + delta,
pk_derived + delta * ED25519_BASEPOINT_POINT,
)
})
}
/// Computes the delta of a derivation path given a path `path` and a public key `pk`.
///
/// # Arguments
///
/// * `pk` - The public key from which to make the derivation.
/// * `path` - The derivation path represented as a `u32` slice, each entry represents the next derivation level.
///
/// # Example
/// ```
/// use kms_edwards25519::derive_delta_path;
/// use curve25519_dalek::constants::ED25519_BASEPOINT_POINT;
/// use curve25519_dalek::scalar::Scalar;
///
/// let scalar_bytes = [1u8; 32];
/// let sk: Scalar = Scalar::from_bytes_mod_order(scalar_bytes);
/// let pk = sk * ED25519_BASEPOINT_POINT;
/// let path = [1,2];
/// let delta = derive_delta_path(&pk, &path);
/// let derived_private_key = sk + delta;
/// let derived_public_key = pk + delta * ED25519_BASEPOINT_POINT;
///
/// ```
pub fn derive_delta_path(pk: &EdwardsPoint, path: &[u32]) -> Scalar {
derive_delta_and_public_key_from_path(pk, path).0
}
/// Derives a public key from an existing public key and a derivation path.
///
/// # Arguments
///
/// - `pk` - A public key.
/// - `path` - The derivation path.
pub fn derive_public_path(pk: &EdwardsPoint, path: &[u32]) -> EdwardsPoint {
derive_delta_and_public_key_from_path(pk, path).1
}
#[cfg(test)]
mod tests {
use crate::{derive_delta_path, derive_public_path};
use curve25519_dalek::{constants::ED25519_BASEPOINT_POINT, scalar::Scalar};
use rand_xoshiro::{rand_core::RngCore, rand_core::SeedableRng, Xoshiro256PlusPlus};
use std::assert_eq;
fn sample_scalar(rng: &mut Xoshiro256PlusPlus) -> Scalar {
let mut bytes: [u8; 32] = [0u8; 32];
rng.fill_bytes(&mut bytes);
Scalar::from_bytes_mod_order(bytes)
}
#[test]
fn test_public_and_delta_sanity_empty_path() {
let mut rng = Xoshiro256PlusPlus::seed_from_u64(0);
let sk = sample_scalar(&mut rng);
let pk = sk * ED25519_BASEPOINT_POINT;
assert_eq!(derive_delta_path(&pk, &[]), Scalar::zero());
assert_eq!(derive_public_path(&pk, &[]), pk);
}
#[test]
fn test_public_and_delta_sanity_path_length_one() {
let mut rng = Xoshiro256PlusPlus::seed_from_u64(1);
let sk = sample_scalar(&mut rng);
let pk = sk * ED25519_BASEPOINT_POINT;
let path = [1];
let delta = derive_delta_path(&pk, &path);
let derived_pk = derive_public_path(&pk, &path);
assert_ne!(delta, Scalar::zero());
assert_eq!(derived_pk, pk + delta * ED25519_BASEPOINT_POINT);
}
#[test]
fn test_public_and_delta_sanity_path_length_two() {
let mut rng = Xoshiro256PlusPlus::seed_from_u64(1);
let sk = sample_scalar(&mut rng);
let pk = sk * ED25519_BASEPOINT_POINT;
let path = [1, u32::MAX];
let delta = derive_delta_path(&pk, &path);
let derived_pk = derive_public_path(&pk, &path);
assert_ne!(delta, Scalar::zero());
assert_eq!(derived_pk, pk + delta * ED25519_BASEPOINT_POINT);
}
}
| 41.28125 | 179 | 0.652031 |
7d861c26e354d18007669aabaa8aee8ac8615f3a
| 2,304 |
html
|
HTML
|
packages/300_template_src/_includes/themes/j1/modules/connectors/ad/google-adsense.html
|
jekyll-one-org/j1-template
|
48b71df38a06a5e6058370ccd703af3cb3b4d395
|
[
"MIT"
] | null | null | null |
packages/300_template_src/_includes/themes/j1/modules/connectors/ad/google-adsense.html
|
jekyll-one-org/j1-template
|
48b71df38a06a5e6058370ccd703af3cb3b4d395
|
[
"MIT"
] | 3 |
2020-06-17T08:52:10.000Z
|
2021-08-11T16:54:22.000Z
|
packages/300_template_src/_includes/themes/j1/modules/connectors/ad/google-adsense.html
|
jekyll-one-org/j1-template
|
48b71df38a06a5e6058370ccd703af3cb3b4d395
|
[
"MIT"
] | 1 |
2021-06-29T18:02:26.000Z
|
2021-06-29T18:02:26.000Z
|
{% comment %}
# -----------------------------------------------------------------------------
# ~/_includes/themes/j1/procedures/provider/ad/google-adsense.html
# Support of advertising provider Google Adsense for J1 Template
#
# Product/Info:
# http://jekyll.one
#
# Copyright (C) 2021 Juergen Adams
#
# J1 Template is licensed under the MIT License.
# See: https://github.com/jekyll-one-org/J1 Template/blob/master/LICENSE
# -----------------------------------------------------------------------------
# Test data:
# liquid_var: {{ liquid_var | debug }}
# -----------------------------------------------------------------------------
{% endcomment %}
{% comment %} Liquid procedures
-------------------------------------------------------------------------------- {% endcomment %}
{% comment %} Variables
-------------------------------------------------------------------------------- {% endcomment %}
{% assign publisher_id = site.data.j1_config.advertising.google.publisher_id %}
{% comment %} Main
-------------------------------------------------------------------------------- {% endcomment %}
<script data-ad-client="{{publisher_id}}"
$(document).ready(function() {
var dependencies_met_page_finished = setInterval (function () {
if (j1.getState() === 'finished') {
async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
clearInterval(dependencies_met_page_finished);
}
}, 25); // END dependencies_met_page_finished
</script>
{% comment %} to be checked
--------------------------------------------------------------------------------
<script data-ad-client="{{publisher_id}}"
async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>
-------------------------------------------------------------------------------- {% endcomment %}
{% comment %} Old Ads code
--------------------------------------------------------------------------------
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "{{publisher_id}}",
enable_page_level_ads: true
});
</script>
-------------------------------------------------------------------------------- {% endcomment %}
| 41.142857 | 97 | 0.447483 |
8ada68683c80f9bbace366712c2700f068e1482d
| 543 |
sql
|
SQL
|
hello-max-file-up/src/main/resources/sql/upload_file.sql
|
xiaoashuo/base
|
366e225251dd4c95c34dfa7bc33cebb59e7dbc3d
|
[
"Apache-2.0"
] | 1 |
2021-08-11T05:07:49.000Z
|
2021-08-11T05:07:49.000Z
|
hello-max-file-up/src/main/resources/sql/upload_file.sql
|
xiaoashuo/base
|
366e225251dd4c95c34dfa7bc33cebb59e7dbc3d
|
[
"Apache-2.0"
] | null | null | null |
hello-max-file-up/src/main/resources/sql/upload_file.sql
|
xiaoashuo/base
|
366e225251dd4c95c34dfa7bc33cebb59e7dbc3d
|
[
"Apache-2.0"
] | 10 |
2020-05-28T06:43:33.000Z
|
2021-11-03T01:32:37.000Z
|
CREATE TABLE `upload_file` (
`file_id` VARCHAR(32) NOT NULL,
`file_path` VARCHAR(128) NOT NULL COMMENT '文件存储路径',
`file_size` VARCHAR(32) NOT NULL COMMENT '文件大小',
`file_suffix` VARCHAR(25) NOT NULL COMMENT '文件后缀',
`file_name` VARCHAR(32) NOT NULL COMMENT '文件名',
`file_md5` VARCHAR(32) NOT NULL COMMENT '文件md5值',
`create_time` TIMESTAMP DEFAULT '0000-00-00 00:00:00',
`update_time` TIMESTAMP DEFAULT NOW() ON UPDATE NOW(),
`file_status` INT NOT NULL COMMENT '文件状态',
PRIMARY KEY (`file_id`)
)COMMENT '文件存储表';
| 41.769231 | 58 | 0.686924 |
7f242a3d0900d8e198a8441cba1e3c6e090196db
| 1,711 |
go
|
Go
|
config.go
|
minodisk/go-tree
|
4359fe8378dbd0dece75189226f653e5479054a6
|
[
"MIT"
] | null | null | null |
config.go
|
minodisk/go-tree
|
4359fe8378dbd0dece75189226f653e5479054a6
|
[
"MIT"
] | 1 |
2017-01-17T12:06:17.000Z
|
2017-01-17T12:06:17.000Z
|
config.go
|
minodisk/go-tree
|
4359fe8378dbd0dece75189226f653e5479054a6
|
[
"MIT"
] | null | null | null |
package tree
import (
"os/user"
"path/filepath"
"regexp"
)
var (
ConfigDefault = &Config{
Indent: " ",
PrefixDirOpened: "-",
PrefixDirClosed: "+",
PrefixFile: "|",
PrefixSelected: "*",
PostfixDir: "/",
RegexpProject: `^(?:\.git)$`,
}
)
func init() {
if err := func() error {
u, err := user.Current()
if err != nil {
return err
}
ConfigDefault.TrashDirname = filepath.Join(u.HomeDir, ".finder-trash")
return nil
}(); err != nil {
panic(err)
}
}
type Context struct {
Config *Config
Registry Operators
}
func (c *Context) Init() error {
if c.Config == nil {
c.Config = &Config{}
}
c.Config.FillWithDefault()
return c.Config.Compile()
}
type Config struct {
Indent string
PrefixDirOpened string
PrefixDirClosed string
PrefixFile string
PrefixSelected string
PostfixDir string
TrashDirname string
RegexpProject string
rProject *regexp.Regexp
}
func (c *Config) FillWithDefault() {
if c.Indent == "" {
c.Indent = ConfigDefault.Indent
}
if c.PrefixDirOpened == "" {
c.PrefixDirOpened = ConfigDefault.PrefixDirOpened
}
if c.PrefixDirClosed == "" {
c.PrefixDirClosed = ConfigDefault.PrefixDirClosed
}
if c.PrefixFile == "" {
c.PrefixFile = ConfigDefault.PrefixFile
}
if c.PrefixSelected == "" {
c.PrefixSelected = ConfigDefault.PrefixSelected
}
if c.PostfixDir == "" {
c.PostfixDir = ConfigDefault.PostfixDir
}
if c.TrashDirname == "" {
c.TrashDirname = ConfigDefault.TrashDirname
}
if c.RegexpProject == "" {
c.RegexpProject = ConfigDefault.RegexpProject
}
}
func (c *Config) Compile() error {
var err error
c.rProject, err = regexp.Compile(c.RegexpProject)
return err
}
| 18.597826 | 72 | 0.656926 |
d85d1fa41bdefa15ec09d62c6bf10684f6d1aa95
| 2,229 |
swift
|
Swift
|
Fokus/Focus/FocusController.swift
|
dnlggr/Fokus
|
7efba4c63fa963e8e3d3fd0d78638285e1b6c207
|
[
"MIT"
] | 3 |
2018-11-12T14:47:08.000Z
|
2019-08-06T18:21:53.000Z
|
Fokus/Focus/FocusController.swift
|
dnlggr/Fokus
|
7efba4c63fa963e8e3d3fd0d78638285e1b6c207
|
[
"MIT"
] | null | null | null |
Fokus/Focus/FocusController.swift
|
dnlggr/Fokus
|
7efba4c63fa963e8e3d3fd0d78638285e1b6c207
|
[
"MIT"
] | null | null | null |
//
// FocusController.swift
// Fokus
//
// Created by Daniel on 01.09.18.
// Copyright © 2018 Daniel Egger. All rights reserved.
//
import Cocoa
import WindowLayout
class FocusController {
// MARK: Initialization
init() { }
// MARK: API
func focusLeft() {
moveFocus(toward: .west)
}
func focusDown() {
moveFocus(toward: .south)
}
func focusUp() {
moveFocus(toward: .north)
}
func focusRight() {
moveFocus(toward: .east)
}
// MARK: Private Functions
private func moveFocus(toward direction: Direction) {
if let neighborWindow = neighborOfCurrentWindow(toward: direction) {
focus(window: neighborWindow)
}
}
private func neighborOfCurrentWindow(toward direction: Direction) -> Window? {
// Get all windows
let screen = Screen(windows: WindowInfo.all.map { Window(bounds: $0.bounds, title: $0.title) })
// Get current window
guard let currentWindowInfo = WindowInfo.current else { return nil }
let currentWindow = Window(bounds: currentWindowInfo.bounds, title: currentWindowInfo.title)
// Get neighbor window
return screen.neighbor(of: currentWindow, toward: direction)
}
private func focus(window: Window) {
// Get window's accessibility application
guard let pid = WindowInfo.foremost(with: window.bounds)?.ownerPID else { return }
let accessibilityApplication = Accessibility.application(for: pid)
// Get first accessibility window with same bounds and title as window as there seems
// to be no other way of matching windows with CGWindowInfo to Accessibility windows
let accessibilityWindow = accessibilityApplication.windows.first {
return $0.bounds == window.bounds && $0.title == window.title
}
if let accessibilityWindow = accessibilityWindow {
// Activate appliction
NSRunningApplication(processIdentifier: pid)?.activate(options: .activateIgnoringOtherApps)
// Raise correct window of application
AXUIElementPerformAction(accessibilityWindow, kAXRaiseAction as CFString)
}
}
}
| 29.328947 | 103 | 0.6559 |
9c144a128c2cfc04978db96c4592e52afc946dd4
| 891 |
js
|
JavaScript
|
sources/task/queries/tasksQueryHandler.spec.js
|
MichaelBorde/todo-list-api
|
67ea6e73fc2554c42b8b99b66e38310deb770b66
|
[
"MIT"
] | null | null | null |
sources/task/queries/tasksQueryHandler.spec.js
|
MichaelBorde/todo-list-api
|
67ea6e73fc2554c42b8b99b66e38310deb770b66
|
[
"MIT"
] | null | null | null |
sources/task/queries/tasksQueryHandler.spec.js
|
MichaelBorde/todo-list-api
|
67ea6e73fc2554c42b8b99b66e38310deb770b66
|
[
"MIT"
] | null | null | null |
'use strict';
require('chai').should();
var MemoryDatabase = require('@arpinum/backend').MemoryDatabase;
var TaskProjection = require('../projections/TaskProjection');
var tasksQueryHandler = require('./tasksQueryHandler');
describe('The tasks query handler', function () {
var handler;
var database;
beforeEach(function () {
database = new MemoryDatabase();
handler = tasksQueryHandler({task: new TaskProjection(database)});
});
it('should find tasks based on criteria', function () {
var tasks = [
{id: 1, text: 'text'},
{id: 2, text: 'another text'},
{id: 3, text: 'text'}
];
database.collections['tasks.projection'] = tasks;
var promise = handler({text: 'text'});
var expectedTasks = [
{id: 1, text: 'text'},
{id: 3, text: 'text'}
];
return promise.should.eventually.deep.equal(expectedTasks);
});
});
| 25.457143 | 70 | 0.634119 |
13ff2e351718ba8443d41424a3be15bb39a14bc7
| 304 |
kt
|
Kotlin
|
src/main/kotlin/com/github/breadmoirai/ttsexplorer/model/VectorLines.kt
|
BreadMoirai/TTSExplorer
|
975cd4dcdc3d1e206db8a1c92314fa1946ee8d81
|
[
"Apache-2.0"
] | null | null | null |
src/main/kotlin/com/github/breadmoirai/ttsexplorer/model/VectorLines.kt
|
BreadMoirai/TTSExplorer
|
975cd4dcdc3d1e206db8a1c92314fa1946ee8d81
|
[
"Apache-2.0"
] | null | null | null |
src/main/kotlin/com/github/breadmoirai/ttsexplorer/model/VectorLines.kt
|
BreadMoirai/TTSExplorer
|
975cd4dcdc3d1e206db8a1c92314fa1946ee8d81
|
[
"Apache-2.0"
] | null | null | null |
package com.github.breadmoirai.ttsexplorer.model
import com.squareup.moshi.Json
data class VectorLines(
@Json(name = "points3") val points3: List<Vector3>,
@Json(name = "color") val color: Color,
@Json(name = "thickness") val thickness: Double,
@Json(name = "loop") val loop: Boolean?
)
| 30.4 | 55 | 0.697368 |
9a542c3d53d6149d857f830bee1e2251b6bfceef
| 1,799 |
swift
|
Swift
|
Example/YahooWather/YahooWather/ViewController.swift
|
beekpr/EasyTheme
|
0ea47fd730517058fd0cf0bbe9acdeaf5c3c65fa
|
[
"MIT"
] | 217 |
2017-06-06T17:20:49.000Z
|
2020-01-23T04:05:05.000Z
|
Example/YahooWather/YahooWather/ViewController.swift
|
beekpr/EasyTheme
|
0ea47fd730517058fd0cf0bbe9acdeaf5c3c65fa
|
[
"MIT"
] | 6 |
2017-06-04T16:14:40.000Z
|
2019-07-22T16:34:04.000Z
|
Example/YahooWather/YahooWather/ViewController.swift
|
beekpr/EasyTheme
|
0ea47fd730517058fd0cf0bbe9acdeaf5c3c65fa
|
[
"MIT"
] | 21 |
2017-06-06T19:30:11.000Z
|
2020-01-01T04:20:50.000Z
|
import UIKit
import Themes
import DayNightSwitch
struct MyTheme: Theme {
let image: UIImage
let textColor: UIColor
init(image: UIImage, textColor: UIColor) {
self.image = image
self.textColor = textColor
}
}
struct ThemeList {
static let day = MyTheme(image: UIImage(named: "day")!, textColor: UIColor.darkGray)
static let night = MyTheme(image: UIImage(named: "night")!, textColor: UIColor.white)
}
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var degreeLabel: UILabel!
@IBOutlet weak var weatherLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
ThemeManager.currentTheme = ThemeList.day
let dayNightSwitch = DayNightSwitch(frame: CGRect(x: view.bounds.size.width - 120,
y: view.bounds.size.height - 70,
width: 100, height: 50))
view.addSubview(dayNightSwitch)
dayNightSwitch.on = true
use(MyTheme.self) { controller, theme in
UIView.transition(with: controller.imageView,
duration: 0.25,
options: .transitionCrossDissolve,
animations: {
controller.imageView.image = theme.image
}, completion: nil)
controller.cityLabel.textColor = theme.textColor
controller.timeLabel.textColor = theme.textColor
}
dayNightSwitch.changeAction = { on in
ThemeManager.currentTheme = on ? ThemeList.day : ThemeList.night
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 28.109375 | 87 | 0.648694 |
598ec75bbefdb667fda8699c075da902b9fd6d99
| 322 |
kt
|
Kotlin
|
mongokrypt-shared/src/main/kotlin/com/mongokrypt/shared/MongoKryptConstants.kt
|
JacobRhiel/mongo-krypt
|
91d52404f706ca5b8fb87cf9e8174f630bfab0db
|
[
"MIT"
] | null | null | null |
mongokrypt-shared/src/main/kotlin/com/mongokrypt/shared/MongoKryptConstants.kt
|
JacobRhiel/mongo-krypt
|
91d52404f706ca5b8fb87cf9e8174f630bfab0db
|
[
"MIT"
] | null | null | null |
mongokrypt-shared/src/main/kotlin/com/mongokrypt/shared/MongoKryptConstants.kt
|
JacobRhiel/mongo-krypt
|
91d52404f706ca5b8fb87cf9e8174f630bfab0db
|
[
"MIT"
] | null | null | null |
package com.mongokrypt.shared
import com.mongokrypt.shared.schema.algorithm.EncryptionAlgorithm
/**
* @author Jacob Rhiel <jacob.rhiel@gmail.com>
* @created Jul 16, 2021
*/
object MongoKryptConstants {
val possibleAlgorithms = setOf(EncryptionAlgorithm.Deterministic::class, EncryptionAlgorithm.Random::class)
}
| 24.769231 | 111 | 0.785714 |
decf3502048172c72f835a4d3a3233e13fdf8e71
| 182 |
rs
|
Rust
|
ref/7 Statements and expressions/7.2 Expressions/7.2.15 Lambda expressions/1 Mutable closures./lib.rs
|
Kha/rustabelle
|
bd4655d91ca65856fb8373637ce3e7b17ee3a190
|
[
"Apache-2.0"
] | 295 |
2016-06-29T03:43:22.000Z
|
2022-03-26T21:37:52.000Z
|
ref/7 Statements and expressions/7.2 Expressions/7.2.15 Lambda expressions/1 Mutable closures./lib.rs
|
Kha/rustabelle
|
bd4655d91ca65856fb8373637ce3e7b17ee3a190
|
[
"Apache-2.0"
] | 3 |
2016-09-16T14:19:27.000Z
|
2018-02-05T13:32:34.000Z
|
ref/7 Statements and expressions/7.2 Expressions/7.2.15 Lambda expressions/1 Mutable closures./lib.rs
|
Kha/rustabelle
|
bd4655d91ca65856fb8373637ce3e7b17ee3a190
|
[
"Apache-2.0"
] | 7 |
2016-07-23T19:32:02.000Z
|
2020-07-05T18:47:04.000Z
|
fn apply<T, F: FnMut(T) -> T>(mut f: F, x: T) -> T {
let y = f(x);
f(y)
}
fn foo(x: i32, mut y: i32) -> i32 {
apply(move |x| {
y += 1;
x + y
}, x)
}
| 15.166667 | 52 | 0.362637 |
0b72b6b59c7098297806590340d0f99c8c866547
| 426 |
py
|
Python
|
chartconvert/mpp.py
|
e-sailing/avnav
|
b3e8df4d6fa122b05309eee09197c716e29b64ec
|
[
"MIT"
] | null | null | null |
chartconvert/mpp.py
|
e-sailing/avnav
|
b3e8df4d6fa122b05309eee09197c716e29b64ec
|
[
"MIT"
] | null | null | null |
chartconvert/mpp.py
|
e-sailing/avnav
|
b3e8df4d6fa122b05309eee09197c716e29b64ec
|
[
"MIT"
] | null | null | null |
#! /usr/bin/env python
#
# vim: ts=2 sw=2 et
#
import sys
#from wx.py.crust import Display
inchpm=39.3700
dpi=100
if len(sys.argv) >1:
dpi=int(sys.argv[1])
displaympp=1/(float(dpi)*inchpm)
print "display mpp=%f"%(displaympp)
mpp= 20037508.342789244 * 2 / 256
print "Level : mpp \t\t: scale"
for i in range(0,31):
scale=mpp/displaympp
print "level(%02d):%07.4f:\t\t1:%5.2f"%(i,mpp,scale)
mpp=mpp/2
| 16.384615 | 54 | 0.638498 |
74df56df940ef4af46fce3b42e59aeb91278a604
| 50,122 |
js
|
JavaScript
|
app/assets/js/custom.js
|
cheenbabes/bbt-ngjs1
|
79a3a05b882bf7d22d2b7cdd9a4d8210d9cbdfb7
|
[
"MIT"
] | null | null | null |
app/assets/js/custom.js
|
cheenbabes/bbt-ngjs1
|
79a3a05b882bf7d22d2b7cdd9a4d8210d9cbdfb7
|
[
"MIT"
] | 1 |
2018-05-08T19:30:16.000Z
|
2018-05-08T19:30:16.000Z
|
app/assets/js/custom.js
|
cheenbabes/bbt-ngjs1
|
79a3a05b882bf7d22d2b7cdd9a4d8210d9cbdfb7
|
[
"MIT"
] | 1 |
2018-05-08T18:32:41.000Z
|
2018-05-08T18:32:41.000Z
|
/*!
*
* Angle - Bootstrap Admin App + jQuery
*
* Version: 3.8.8
* Author: @themicon_co
* Website: http://themicon.co
* License: https://wrapbootstrap.com/help/licenses
*
*/
!function(e,t,o,a){if(void 0===o)throw new Error("This application's JavaScript requires jQuery");o.localStorage=Storages.localStorage,o(function(){var e=o("body");(new StateToggler).restoreState(e),o("#chk-fixed").prop("checked",e.hasClass("layout-fixed")),o("#chk-collapsed").prop("checked",e.hasClass("aside-collapsed")),o("#chk-collapsed-text").prop("checked",e.hasClass("aside-collapsed-text")),o("#chk-boxed").prop("checked",e.hasClass("layout-boxed")),o("#chk-float").prop("checked",e.hasClass("aside-float")),o("#chk-hover").prop("checked",e.hasClass("aside-hover")),o(".offsidebar.d-none").removeClass("d-none"),o.ajaxPrefilter(function(e,t,o){e.async=!0})})}(window,document,window.jQuery),function(e,t,o,a){o.fn.andSelf=function(){return this.addBack()},o(function(){o(".flatdoc").each(function(){Flatdoc.run({fetcher:Flatdoc.file("server/documentation/readme.md"),root:".flatdoc",menu:".flatdoc-menu",title:".flatdoc-title",content:".flatdoc-content"})})})}(window,document,window.jQuery),function(e,t,o,a){o(function(){o('[data-toggle="popover"]').popover(),o('[data-toggle="tooltip"]').tooltip({container:"body"}),o(".dropdown input").on("click focus",function(e){e.stopPropagation()})})}(window,document,window.jQuery),function(e,t,o){"use strict";var a="card.removed";e(o).on("click",'[data-tool="card-dismiss"]',function(){var t=e(this).closest(".card"),o=new e.Deferred;function n(){var o=t.parent();e.when(t.trigger(a,[t])).done(function(){t.remove(),o.trigger(a).filter(function(){var t=e(this);return t.is('[class*="col-"]:not(.sortable)')&&0===t.children("*").length}).remove()})}t.trigger("card.remove",[t,o]),o.done(function(){t.animo({animation:"bounceOut"},n)})})}(jQuery,window,document),function(e,t,o){"use strict";var a='[data-tool="card-collapse"]',n="jq-cardState";function r(t,o){var a=e.localStorage.get(n);a||(a={}),a[t]=o,e.localStorage.set(n,a)}e(a).each(function(){var t=e(this),o=t.closest(".card"),a=o.find(".card-wrapper"),i={toggle:!1},l=t.children("em"),s=o.attr("id");a.length||(a=o.children(".card-heading").nextAll().wrapAll("<div/>").parent().addClass("card-wrapper"),i={}),a.collapse(i).on("hide.bs.collapse",function(){l.removeClass("fa-minus").addClass("fa-plus"),r(s,"hide"),a.prev(".card-heading").addClass("card-heading-collapsed")}).on("show.bs.collapse",function(){l.removeClass("fa-plus").addClass("fa-minus"),r(s,"show"),a.prev(".card-heading").removeClass("card-heading-collapsed")});var c=function(t){var o=e.localStorage.get(n);if(o)return o[t]||!1}(s);c&&(setTimeout(function(){a.collapse(c)},50),r(s,c))}),e(o).on("click",a,function(){e(this).closest(".card").find(".card-wrapper").collapse("toggle")})}(jQuery,window,document),function(e,t,o){"use strict";var a="whirl";function n(){this.removeClass(a)}e(o).on("click",'[data-tool="card-refresh"]',function(){var t=e(this),o=t.parents(".card").eq(0),r=t.data("spinner")||"standard";o.addClass(a+" "+r),o.removeSpinner=n,t.trigger("card.refresh",[o])})}(jQuery,window,document),function(e,t,o){"use strict";e(o).on("click","[data-reset-key]",function(o){o.preventDefault();var a=e(this).data("resetKey");a?(e.localStorage.remove(a),t.location.reload()):e.error("No storage key specified for reset.")})}(jQuery,window,document),function(e,t,o,a){e.APP_COLORS={primary:"#5d9cec",success:"#27c24c",info:"#23b7e5",warning:"#ff902b",danger:"#f05050",inverse:"#131e26",green:"#37bc9b",pink:"#f532e5",purple:"#7266ba",dark:"#3a3f51",yellow:"#fad732","gray-darker":"#232735","gray-dark":"#3a3f51",gray:"#dde6e9","gray-light":"#e4eaec","gray-lighter":"#edf1f2"},e.APP_MEDIAQUERY={desktopLG:1200,desktop:992,tablet:768,mobile:480}}(window,document,window.jQuery),function(e,t,o,a){"undefined"!=typeof screenfull&&o(function(){var a=o(t),n=o("[data-toggle-fullscreen]"),r=e.navigator.userAgent;function i(e){screenfull.isFullscreen?e.children("em").removeClass("fa-expand").addClass("fa-compress"):e.children("em").removeClass("fa-compress").addClass("fa-expand")}(r.indexOf("MSIE ")>0||r.match(/Trident.*rv\:11\./))&&n.addClass("hide"),n.is(":visible")&&(n.on("click",function(e){e.preventDefault(),screenfull.enabled?(screenfull.toggle(),i(n)):console.log("Fullscreen not enabled")}),screenfull.raw&&screenfull.raw.fullscreenchange&&a.on(screenfull.raw.fullscreenchange,function(){i(n)}))})}(window,document,window.jQuery),function(e,t,o,a){o(function(){o("[data-load-css]").on("click",function(e){var t=o(this);t.is("a")&&e.preventDefault();var a=t.data("loadCss");a?function(e){var t="autoloaded-stylesheet",a=o("#"+t).attr("id",t+"-old");o("head").append(o("<link/>").attr({id:t,rel:"stylesheet",href:e})),a.length&&a.remove();return o("#"+t)}(a)||o.error("Error creating stylesheet link element."):o.error("No stylesheet location defined.")})})}(window,document,window.jQuery),function(e,t,o,a){var n="site",r="jq-appLang";o(function(){if(o.fn.localize){var e=o.localStorage.get(r)||"en",t={language:e,pathPrefix:"server/i18n",callback:function(t,a){o.localStorage.set(r,e),a(t)}};a(t),o("[data-set-lang]").on("click",function(){(e=o(this).data("setLang"))&&(t.language=e,a(t),function(e){var t=e.parents(".dropdown-menu");if(t.length){var o=t.prev("button, a");o.text(e.text())}}(o(this)))})}function a(e){o("[data-localize]").localize(n,e)}})}(window,document,window.jQuery),function(e,t,o,a){o(function(){var e=new n;o("[data-search-open]").on("click",function(e){e.stopPropagation()}).on("click",e.toggle);var a=o("[data-search-dismiss]");o('.navbar-form input[type="text"]').on("click",function(e){e.stopPropagation()}).on("keyup",function(t){27==t.keyCode&&e.dismiss()}),o(t).on("click",e.dismiss),a.on("click",function(e){e.stopPropagation()}).on("click",e.dismiss)});var n=function(){var e="form.navbar-form";return{toggle:function(){var t=o(e);t.toggleClass("open");var a=t.hasClass("open");t.find("input")[a?"focus":"blur"]()},dismiss:function(){o(e).removeClass("open").find('input[type="text"]').blur()}}}}(window,document,window.jQuery),function(e,t,o,a){o(function(){o("[data-now]").each(function(){var e=o(this),t=e.data("format");function a(){var o=moment(new Date).format(t);e.text(o)}a(),setInterval(a,1e3)})})}(window,document,window.jQuery),function(e,t,o,a){o(function(){var e=o("#maincss"),t=o("#bscss");o("#chk-rtl").on("change",function(){e.attr("href",this.checked?"css/app-rtl.css":"css/app.css"),t.attr("href",this.checked?"css/bootstrap-rtl.css":"css/bootstrap.css")})})}(window,document,window.jQuery),function(e,t,o,a){var n,r,i,l;function s(e){e.siblings("li").removeClass("open").end().toggleClass("open")}function c(){o(".sidebar-subnav.nav-floating").remove(),o(".dropdown-backdrop").remove(),o(".sidebar li.open").removeClass("open")}function d(){return i.hasClass("aside-hover")}o(function(){n=o(e),r=o("html"),i=o("body"),l=o(".sidebar"),APP_MEDIAQUERY;var t=l.find(".collapse");t.on("show.bs.collapse",function(e){e.stopPropagation(),0===o(this).parents(".collapse").length&&t.filter(".show").collapse("hide")});var a=o(".sidebar .active").parents("li");d()||a.addClass("active").children(".collapse").collapse("show"),l.find("li > a + ul").on("show.bs.collapse",function(e){d()&&e.preventDefault()});var u=r.hasClass("touch")?"click":"mouseenter",f=o();l.on(u,".sidebar-nav > li",function(){(i.hasClass("aside-collapsed")||i.hasClass("aside-collapsed-text")||d())&&(f.trigger("mouseleave"),f=function(e){c();var t=e.children("ul");if(!t.length)return o();if(e.hasClass("open"))return s(e),o();var a=o(".aside-container"),r=o(".aside-inner"),d=parseInt(r.css("padding-top"),0)+parseInt(a.css("padding-top"),0),u=t.clone().appendTo(a);s(e);var f=e.position().top+d-l.scrollTop(),p=n.height();return u.addClass("nav-floating").css({position:i.hasClass("layout-fixed")?"fixed":"absolute",top:f,bottom:u.outerHeight(!0)+f>p?0:"auto"}),u.on("mouseleave",function(){s(e),u.remove()}),u}(o(this)),o("<div/>",{class:"dropdown-backdrop"}).insertAfter(".aside-container").on("click mouseenter",function(){c()}))}),void 0!==l.data("sidebarAnyclickClose")&&o(".wrapper").on("click.sidebar",function(e){if(i.hasClass("aside-toggled")){var t=o(e.target);t.parents(".aside-container").length||t.is("#user-block-toggle")||t.parent().is("#user-block-toggle")||i.removeClass("aside-toggled")}})})}(window,document,window.jQuery),function(e,t,o,a){o(function(){o("[data-scrollable]").each(function(){var e=o(this);e.slimScroll({height:e.data("height")||250})})})}(window,document,window.jQuery),function(e,t,o,a){o(function(){o("[data-check-all]").on("change",function(){var e=o(this),t=e.index()+1,a=e.find('input[type="checkbox"]');e.parents("table").find("tbody > tr > td:nth-child("+t+') input[type="checkbox"]').prop("checked",a[0].checked)})})}(window,document,window.jQuery),function(e,t,o,a){o(function(){var t=o("body");toggle=new StateToggler,o("[data-toggle-state]").on("click",function(a){a.stopPropagation();var n=o(this),r=n.data("toggleState"),i=n.data("target"),l=void 0!==n.attr("data-no-persist"),s=i?o(i):t;r&&(s.hasClass(r)?(s.removeClass(r),l||toggle.removeState(r)):(s.addClass(r),l||toggle.addState(r))),o(e).resize()})}),e.StateToggler=function(){var e="jq-toggleState",t={hasWord:function(e,t){return new RegExp("(^|\\s)"+t+"(\\s|$)").test(e)},addWord:function(e,t){if(!this.hasWord(e,t))return e+(e?" ":"")+t},removeWord:function(e,t){if(this.hasWord(e,t))return e.replace(new RegExp("(^|\\s)*"+t+"(\\s|$)*","g"),"")}};return{addState:function(a){var n=o.localStorage.get(e);n=n?t.addWord(n,a):a,o.localStorage.set(e,n)},removeState:function(a){var n=o.localStorage.get(e);n&&(n=t.removeWord(n,a),o.localStorage.set(e,n))},restoreState:function(t){var a=o.localStorage.get(e);a&&t.addClass(a)}}}}(window,document,window.jQuery),function(e,t,o,a){o(function(){var a=o("[data-trigger-resize]"),n=a.data("triggerResize");a.on("click",function(){setTimeout(function(){var o=t.createEvent("UIEvents");o.initUIEvent("resize",!0,!1,e,0),e.dispatchEvent(o)},n||300)})})}(window,document,window.jQuery),function(e,t,o,a){o(function(){o(".card.card-demo").on("card.refresh",function(e,t){setTimeout(function(){t.removeSpinner()},3e3)}).on("hide.bs.collapse",function(e){console.log("Card Collapse Hide")}).on("show.bs.collapse",function(e){console.log("Card Collapse Show")}).on("card.remove",function(e,t,o){console.log("Removing Card"),o.resolve()}).on("card.removed",function(e,t){console.log("Removed Card")})})}(window,document,window.jQuery),function(e,t,o,a){o.fn.nestable&&o(function(){var t=function(t){var a=t.length?t:o(t.target),n=a.data("output");e.JSON?n.val(e.JSON.stringify(a.nestable("serialize"))):n.val("JSON browser support required for this demo.")};o("#nestable").nestable({group:1}).on("change",t),o("#nestable2").nestable({group:1}).on("change",t),t(o("#nestable").data("output",o("#nestable-output"))),t(o("#nestable2").data("output",o("#nestable2-output"))),o(".js-nestable-action").on("click",function(e){var t=o(e.target).data("action");"expand-all"===t&&o(".dd").nestable("expandAll"),"collapse-all"===t&&o(".dd").nestable("collapseAll")})})}(window,document,window.jQuery),function(e,t,o){"use strict";e(o);function a(t){var o=t.data("message"),a=t.data("options");o||e.error("Notify: No message specified"),e.notify(o,a||{})}e(function(){e("[data-notify]").each(function(){var t=e(this);void 0!==t.data("onload")&&setTimeout(function(){a(t)},800),t.on("click",function(e){e.preventDefault(),a(t)})})})}(jQuery,window,document),function(e,t,o){var a={},n={},r=function(t){return"string"==e.type(t)&&(t={message:t}),arguments[1]&&(t=e.extend(t,"string"==e.type(arguments[1])?{status:arguments[1]}:arguments[1])),new i(t).show()},i=function(t){this.options=e.extend({},i.defaults,t),this.uuid="ID"+(new Date).getTime()+"RAND"+Math.ceil(1e5*Math.random()),this.element=e(['<div class="uk-notify-message alert-dismissable">','<a class="close">×</a>',"<div>"+this.options.message+"</div>","</div>"].join("")).data("notifyMessage",this),this.options.status&&(this.element.addClass("alert alert-"+this.options.status),this.currentstatus=this.options.status),this.group=this.options.group,n[this.uuid]=this,a[this.options.pos]||(a[this.options.pos]=e('<div class="uk-notify uk-notify-'+this.options.pos+'"></div>').appendTo("body").on("click",".uk-notify-message",function(){e(this).data("notifyMessage").close()}))};e.extend(i.prototype,{uuid:!1,element:!1,timout:!1,currentstatus:"",group:!1,show:function(){if(!this.element.is(":visible")){var e=this;a[this.options.pos].show().prepend(this.element);var t=parseInt(this.element.css("margin-bottom"),10);return this.element.css({opacity:0,"margin-top":-1*this.element.outerHeight(),"margin-bottom":0}).animate({opacity:1,"margin-top":0,"margin-bottom":t},function(){if(e.options.timeout){var t=function(){e.close()};e.timeout=setTimeout(t,e.options.timeout),e.element.hover(function(){clearTimeout(e.timeout)},function(){e.timeout=setTimeout(t,e.options.timeout)})}}),this}},close:function(e){var t=this,o=function(){t.element.remove(),a[t.options.pos].children().length||a[t.options.pos].hide(),delete n[t.uuid]};this.timeout&&clearTimeout(this.timeout),e?o():this.element.animate({opacity:0,"margin-top":-1*this.element.outerHeight(),"margin-bottom":0},function(){o()})},content:function(e){var t=this.element.find(">div");return e?(t.html(e),this):t.html()},status:function(e){return e?(this.element.removeClass("alert alert-"+this.currentstatus).addClass("alert alert-"+e),this.currentstatus=e,this):this.currentstatus}}),i.defaults={message:"",status:"normal",timeout:5e3,group:null,pos:"top-center"},e.notify=r,e.notify.message=i,e.notify.closeAll=function(e,t){if(e)for(var o in n)e===n[o].group&&n[o].close(t);else for(var o in n)n[o].close(t)}}(jQuery,window,document),function(e,t,o){"use strict";e(function(){e(o).on("click","[data-animate]",function(){var t=e(this),o=t.data("target"),a=t.data("play")||"bounce";o&&e(o).animo({animation:a})})})}(jQuery,window,document),function(e,t,o){"use strict";if(e.fn.sortable){var a='[data-toggle="portlet"]',n="jq-portletState";e(function(){e(a).sortable({connectWith:a,items:"div.card",handle:".portlet-handler",opacity:.7,placeholder:"portlet box-placeholder",cancel:".portlet-cancel",forcePlaceholderSize:!0,iframeFix:!1,tolerance:"pointer",helper:"original",revert:200,forceHelperSize:!0,update:r,create:i})})}function r(t,o){var a=e.localStorage.get(n);a||(a={}),a[this.id]=e(this).sortable("toArray"),a&&e.localStorage.set(n,a)}function i(){var t=e.localStorage.get(n);if(t){var o=this.id,a=t[o];if(a){var r=e("#"+o);e.each(a,function(t,o){e("#"+o).appendTo(r)})}}}}(jQuery,window,document),function(e,t,o,a){"undefined"!=typeof sortable&&o(function(){sortable(".sortable",{forcePlaceholderSize:!0,placeholder:'<div class="box-placeholder p0 m0"><div></div></div>'})})}(window,document,window.jQuery),function(e,t,o,a){o(function(){o("#swal-demo1").on("click",function(e){e.preventDefault(),swal("Here's a message!")}),o("#swal-demo2").on("click",function(e){e.preventDefault(),swal("Here's a message!","It's pretty, isn't it?")}),o("#swal-demo3").on("click",function(e){e.preventDefault(),swal("Good job!","You clicked the button!","success")}),o("#swal-demo4").on("click",function(e){e.preventDefault(),swal({title:"Are you sure?",text:"You will not be able to recover this imaginary file!",type:"warning",showCancelButton:!0,confirmButtonColor:"#DD6B55",confirmButtonText:"Yes, delete it!",closeOnConfirm:!1},function(){swal("Deleted!","Your imaginary file has been deleted.","success")})}),o("#swal-demo5").on("click",function(e){e.preventDefault(),swal({title:"Are you sure?",text:"You will not be able to recover this imaginary file!",type:"warning",showCancelButton:!0,confirmButtonColor:"#DD6B55",confirmButtonText:"Yes, delete it!",cancelButtonText:"No, cancel plx!",closeOnConfirm:!1,closeOnCancel:!1},function(e){e?swal("Deleted!","Your imaginary file has been deleted.","success"):swal("Cancelled","Your imaginary file is safe :)","error")})})})}(window,document,window.jQuery),function(e,t,o,a){o(function(){if(o.fn.knob){var e={width:"50%",displayInput:!0,fgColor:APP_COLORS.info};o("#knob-chart1").knob(e);var t={width:"50%",displayInput:!0,fgColor:APP_COLORS.purple,readOnly:!0};o("#knob-chart2").knob(t);var a={width:"50%",displayInput:!0,fgColor:APP_COLORS.info,bgColor:APP_COLORS.gray,angleOffset:-125,angleArc:250};o("#knob-chart3").knob(a);var n={width:"50%",displayInput:!0,fgColor:APP_COLORS.pink,displayPrevious:!0,thickness:.1,lineCap:"round"};o("#knob-chart4").knob(n)}})}(window,document,window.jQuery),function(e,t,o,a){(0,window.jQuery)(function(){if("undefined"!=typeof Chart){var e=function(){return Math.round(100*Math.random())},o={labels:["January","February","March","April","May","June","July"],datasets:[{label:"My First dataset",backgroundColor:"rgba(114,102,186,0.2)",borderColor:"rgba(114,102,186,1)",pointBorderColor:"#fff",data:[e(),e(),e(),e(),e(),e(),e()]},{label:"My Second dataset",backgroundColor:"rgba(35,183,229,0.2)",borderColor:"rgba(35,183,229,1)",pointBorderColor:"#fff",data:[e(),e(),e(),e(),e(),e(),e()]}]},a=t.getElementById("chartjs-linechart").getContext("2d"),n=(new Chart(a,{data:o,type:"line",options:{legend:{display:!1}}}),{labels:["January","February","March","April","May","June","July"],datasets:[{backgroundColor:"#23b7e5",borderColor:"#23b7e5",data:[e(),e(),e(),e(),e(),e(),e()]},{backgroundColor:"#5d9cec",borderColor:"#5d9cec",data:[e(),e(),e(),e(),e(),e(),e()]}]}),r=t.getElementById("chartjs-barchart").getContext("2d"),i=(new Chart(r,{data:n,type:"bar",options:{legend:{display:!1}}}),t.getElementById("chartjs-doughnutchart").getContext("2d")),l=(new Chart(i,{data:{labels:["Purple","Yellow","Blue"],datasets:[{data:[300,50,100],backgroundColor:["#7266ba","#fad732","#23b7e5"],hoverBackgroundColor:["#7266ba","#fad732","#23b7e5"]}]},type:"doughnut",options:{legend:{display:!1}}}),t.getElementById("chartjs-piechart").getContext("2d")),s=(new Chart(l,{data:{labels:["Purple","Yellow","Blue"],datasets:[{data:[300,50,100],backgroundColor:["#7266ba","#fad732","#23b7e5"],hoverBackgroundColor:["#7266ba","#fad732","#23b7e5"]}]},type:"pie",options:{legend:{display:!1}}}),t.getElementById("chartjs-polarchart").getContext("2d")),c=(new Chart(s,{data:{datasets:[{data:[11,16,7,3],backgroundColor:["#f532e5","#7266ba","#f532e5","#7266ba"],label:"My dataset"}],labels:["Label 1","Label 2","Label 3","Label 4"]},type:"polarArea",options:{legend:{display:!1}}}),t.getElementById("chartjs-radarchart").getContext("2d"));new Chart(c,{data:{labels:["Eating","Drinking","Sleeping","Designing","Coding","Cycling","Running"],datasets:[{label:"My First dataset",backgroundColor:"rgba(114,102,186,0.2)",borderColor:"rgba(114,102,186,1)",data:[65,59,90,81,56,55,40]},{label:"My Second dataset",backgroundColor:"rgba(151,187,205,0.2)",borderColor:"rgba(151,187,205,1)",data:[28,48,40,19,96,27,100]}]},type:"radar",options:{legend:{display:!1}}})}})}(window,document),function(e,t,o,a){(0,window.jQuery)(function(){if("undefined"!=typeof Chartist){new Chartist.Bar("#ct-bar1",{labels:["W1","W2","W3","W4","W5","W6","W7","W8","W9","W10"],series:[[1,2,4,8,6,-2,-1,-4,-6,-2]]},{high:10,low:-10,height:280,axisX:{labelInterpolationFnc:function(e,t){return t%2==0?e:null}}}),new Chartist.Bar("#ct-bar2",{labels:["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],series:[[5,4,3,7,5,10,3],[3,2,9,5,4,6,4]]},{seriesBarDistance:10,reverseData:!0,horizontalBars:!0,height:280,axisY:{offset:70}}),new Chartist.Line("#ct-line1",{labels:["Monday","Tuesday","Wednesday","Thursday","Friday"],series:[[12,9,7,8,5],[2,1,3.5,7,3],[1,3,4,5,6]]},{fullWidth:!0,height:280,chartPadding:{right:40}}),new Chartist.Line("#ct-line3",{labels:["Mon","Tue","Wed","Thu","Fri","Sat"],series:[[1,5,2,5,4,3],[2,3,4,8,1,2],[5,4,3,2,1,.5]]},{low:0,showArea:!0,showPoint:!1,fullWidth:!0,height:300}).on("draw",function(e){"line"!==e.type&&"area"!==e.type||e.element.animate({d:{begin:2e3*e.index,dur:2e3,from:e.path.clone().scale(1,0).translate(0,e.chartRect.height()).stringify(),to:e.path.clone().stringify(),easing:Chartist.Svg.Easing.easeOutQuint}})});var t=new Chartist.Line("#ct-line2",{labels:["1","2","3","4","5","6","7","8","9","10","11","12"],series:[[12,9,7,8,5,4,6,2,3,3,4,6],[4,5,3,7,3,5,5,3,4,4,5,5],[5,3,4,5,6,3,3,4,5,6,3,4],[3,4,5,6,7,6,4,5,6,7,6,3]]},{low:0,height:300}),o=0,a=500;t.on("created",function(){o=0}),t.on("draw",function(e){if(o++,"line"===e.type)e.element.animate({opacity:{begin:80*o+1e3,dur:a,from:0,to:1}});else if("label"===e.type&&"x"===e.axis)e.element.animate({y:{begin:80*o,dur:a,from:e.y+100,to:e.y,easing:"easeOutQuart"}});else if("label"===e.type&&"y"===e.axis)e.element.animate({x:{begin:80*o,dur:a,from:e.x-100,to:e.x,easing:"easeOutQuart"}});else if("point"===e.type)e.element.animate({x1:{begin:80*o,dur:a,from:e.x-10,to:e.x,easing:"easeOutQuart"},x2:{begin:80*o,dur:a,from:e.x-10,to:e.x,easing:"easeOutQuart"},opacity:{begin:80*o,dur:a,from:0,to:1,easing:"easeOutQuart"}});else if("grid"===e.type){var t={begin:80*o,dur:a,from:e[e.axis.units.pos+"1"]-30,to:e[e.axis.units.pos+"1"],easing:"easeOutQuart"},n={begin:80*o,dur:a,from:e[e.axis.units.pos+"2"]-100,to:e[e.axis.units.pos+"2"],easing:"easeOutQuart"},r={};r[e.axis.units.pos+"1"]=t,r[e.axis.units.pos+"2"]=n,r.opacity={begin:80*o,dur:a,from:0,to:1,easing:"easeOutQuart"},e.element.animate(r)}}),t.on("created",function(){e.__exampleAnimateTimeout&&(clearTimeout(e.__exampleAnimateTimeout),e.__exampleAnimateTimeout=null),e.__exampleAnimateTimeout=setTimeout(t.update.bind(t),12e3)})}})}(window,document),function(e,t,o,a){o(function(){if(o.fn.easyPieChart){o("[data-easypiechart]").each(function(){var e=o(this),t=e.data();e.easyPieChart(t||{})});var e={animate:{duration:800,enabled:!0},barColor:APP_COLORS.success,trackColor:!1,scaleColor:!1,lineWidth:10,lineCap:"circle"};o("#easypie1").easyPieChart(e);var t={animate:{duration:800,enabled:!0},barColor:APP_COLORS.warning,trackColor:!1,scaleColor:!1,lineWidth:4,lineCap:"circle"};o("#easypie2").easyPieChart(t);var a={animate:{duration:800,enabled:!0},barColor:APP_COLORS.danger,trackColor:!1,scaleColor:APP_COLORS.gray,lineWidth:15,lineCap:"circle"};o("#easypie3").easyPieChart(a);var n={animate:{duration:800,enabled:!0},barColor:APP_COLORS.danger,trackColor:APP_COLORS.yellow,scaleColor:APP_COLORS["gray-dark"],lineWidth:15,lineCap:"circle"};o("#easypie4").easyPieChart(n)}})}(window,document,window.jQuery),function(e,t,o,a){o(function(){var e={series:{lines:{show:!1},points:{show:!0,radius:4},splines:{show:!0,tension:.4,lineWidth:1,fill:.5}},grid:{borderColor:"#eee",borderWidth:1,hoverable:!0,backgroundColor:"#fcfcfc"},tooltip:!0,tooltipOpts:{content:function(e,t,o){return t+" : "+o}},xaxis:{tickColor:"#fcfcfc",mode:"categories"},yaxis:{min:0,max:150,tickColor:"#eee",tickFormatter:function(e){return e}},shadowSize:0},t=o(".chart-spline");t.length&&o.plot(t,[{label:"Uniques",color:"#768294",data:[["Mar",70],["Apr",85],["May",59],["Jun",93],["Jul",66],["Aug",86],["Sep",60]]},{label:"Recurrent",color:"#1f92fe",data:[["Mar",21],["Apr",12],["May",27],["Jun",24],["Jul",16],["Aug",39],["Sep",15]]}],e);var a=o(".chart-splinev2");a.length&&o.plot(a,[{label:"Hours",color:"#23b7e5",data:[["Jan",70],["Feb",20],["Mar",70],["Apr",85],["May",59],["Jun",93],["Jul",66],["Aug",86],["Sep",60],["Oct",60],["Nov",12],["Dec",50]]},{label:"Commits",color:"#7266ba",data:[["Jan",20],["Feb",70],["Mar",30],["Apr",50],["May",85],["Jun",43],["Jul",96],["Aug",36],["Sep",80],["Oct",10],["Nov",72],["Dec",31]]}],e);var n=o(".chart-splinev3");n.length&&o.plot(n,[{label:"Home",color:"#1ba3cd",data:[["1",38],["2",40],["3",42],["4",48],["5",50],["6",70],["7",145],["8",70],["9",59],["10",48],["11",38],["12",29],["13",30],["14",22],["15",28]]},{label:"Overall",color:"#3a3f51",data:[["1",16],["2",18],["3",17],["4",16],["5",30],["6",110],["7",19],["8",18],["9",110],["10",19],["11",16],["12",10],["13",20],["14",10],["15",20]]}],e)})}(window,document,window.jQuery),function(e,t,o,a){o(function(){var e=o(".chart-area");e.length&&o.plot(e,[{label:"Uniques",color:"#aad874",data:[["Mar",50],["Apr",84],["May",52],["Jun",88],["Jul",69],["Aug",92],["Sep",58]]},{label:"Recurrent",color:"#7dc7df",data:[["Mar",13],["Apr",44],["May",44],["Jun",27],["Jul",38],["Aug",11],["Sep",39]]}],{series:{lines:{show:!0,fill:.8},points:{show:!0,radius:4}},grid:{borderColor:"#eee",borderWidth:1,hoverable:!0,backgroundColor:"#fcfcfc"},tooltip:!0,tooltipOpts:{content:function(e,t,o){return t+" : "+o}},xaxis:{tickColor:"#fcfcfc",mode:"categories"},yaxis:{min:0,tickColor:"#eee",tickFormatter:function(e){return e+" visitors"}},shadowSize:0})})}(window,document,window.jQuery),function(e,t,o,a){o(function(){var e=o(".chart-bar");e.length&&o.plot(e,[{label:"Sales",color:"#9cd159",data:[["Jan",27],["Feb",82],["Mar",56],["Apr",14],["May",28],["Jun",77],["Jul",23],["Aug",49],["Sep",81],["Oct",20]]}],{series:{bars:{align:"center",lineWidth:0,show:!0,barWidth:.6,fill:.9}},grid:{borderColor:"#eee",borderWidth:1,hoverable:!0,backgroundColor:"#fcfcfc"},tooltip:!0,tooltipOpts:{content:function(e,t,o){return t+" : "+o}},xaxis:{tickColor:"#fcfcfc",mode:"categories"},yaxis:{tickColor:"#eee"},shadowSize:0})})}(window,document,window.jQuery),function(e,t,o,a){o(function(){var e={series:{stack:!0,bars:{align:"center",lineWidth:0,show:!0,barWidth:.6,fill:.9}},grid:{borderColor:"#eee",borderWidth:1,hoverable:!0,backgroundColor:"#fcfcfc"},tooltip:!0,tooltipOpts:{content:function(e,t,o){return t+" : "+o}},xaxis:{tickColor:"#fcfcfc",mode:"categories"},yaxis:{tickColor:"#eee"},shadowSize:0},t=o(".chart-bar-stacked");t.length&&o.plot(t,[{label:"Tweets",color:"#51bff2",data:[["Jan",56],["Feb",81],["Mar",97],["Apr",44],["May",24],["Jun",85],["Jul",94],["Aug",78],["Sep",52],["Oct",17],["Nov",90],["Dec",62]]},{label:"Likes",color:"#4a8ef1",data:[["Jan",69],["Feb",135],["Mar",14],["Apr",100],["May",100],["Jun",62],["Jul",115],["Aug",22],["Sep",104],["Oct",132],["Nov",72],["Dec",61]]},{label:"+1",color:"#f0693a",data:[["Jan",29],["Feb",36],["Mar",47],["Apr",21],["May",5],["Jun",49],["Jul",37],["Aug",44],["Sep",28],["Oct",9],["Nov",12],["Dec",35]]}],e);var a=o(".chart-bar-stackedv2");a.length&&o.plot(a,[{label:"Pending",color:"#9289ca",data:[["Pj1",86],["Pj2",136],["Pj3",97],["Pj4",110],["Pj5",62],["Pj6",85],["Pj7",115],["Pj8",78],["Pj9",104],["Pj10",82],["Pj11",97],["Pj12",110],["Pj13",62]]},{label:"Assigned",color:"#7266ba",data:[["Pj1",49],["Pj2",81],["Pj3",47],["Pj4",44],["Pj5",100],["Pj6",49],["Pj7",94],["Pj8",44],["Pj9",52],["Pj10",17],["Pj11",47],["Pj12",44],["Pj13",100]]},{label:"Completed",color:"#564aa3",data:[["Pj1",29],["Pj2",56],["Pj3",14],["Pj4",21],["Pj5",5],["Pj6",24],["Pj7",37],["Pj8",22],["Pj9",28],["Pj10",9],["Pj11",14],["Pj12",21],["Pj13",5]]}],e)})}(window,document,window.jQuery),function(e,t,o,a){o(function(){var e=o(".chart-donut");e.length&&o.plot(e,[{color:"#39C558",data:60,label:"Coffee"},{color:"#00b4ff",data:90,label:"CSS"},{color:"#FFBE41",data:50,label:"LESS"},{color:"#ff3e43",data:80,label:"Jade"},{color:"#937fc7",data:116,label:"AngularJS"}],{series:{pie:{show:!0,innerRadius:.5}}})})}(window,document,window.jQuery),function(e,t,o,a){o(function(){var e=o(".chart-line");e.length&&o.plot(e,[{label:"Complete",color:"#5ab1ef",data:[["Jan",188],["Feb",183],["Mar",185],["Apr",199],["May",190],["Jun",194],["Jul",194],["Aug",184],["Sep",74]]},{label:"In Progress",color:"#f5994e",data:[["Jan",153],["Feb",116],["Mar",136],["Apr",119],["May",148],["Jun",133],["Jul",118],["Aug",161],["Sep",59]]},{label:"Cancelled",color:"#d87a80",data:[["Jan",111],["Feb",97],["Mar",93],["Apr",110],["May",102],["Jun",93],["Jul",92],["Aug",92],["Sep",44]]}],{series:{lines:{show:!0,fill:.01},points:{show:!0,radius:4}},grid:{borderColor:"#eee",borderWidth:1,hoverable:!0,backgroundColor:"#fcfcfc"},tooltip:!0,tooltipOpts:{content:function(e,t,o){return t+" : "+o}},xaxis:{tickColor:"#eee",mode:"categories"},yaxis:{tickColor:"#eee"},shadowSize:0})})}(window,document,window.jQuery),function(e,t,o,a){o(function(){var e={series:{pie:{show:!0,innerRadius:0,label:{show:!0,radius:.8,formatter:function(e,t){return'<div class="flot-pie-label">'+Math.round(t.percent)+"%</div>"},background:{opacity:.8,color:"#222"}}}}},t=o(".chart-pie");t.length&&o.plot(t,[{label:"jQuery",color:"#4acab4",data:30},{label:"CSS",color:"#ffea88",data:40},{label:"LESS",color:"#ff8153",data:90},{label:"SASS",color:"#878bb6",data:75},{label:"Jade",color:"#b2d767",data:120}],e)})}(window,document,window.jQuery),window,document,(0,window.jQuery)(function(){if("undefined"!=typeof Morris){var e=[{y:"2006",a:100,b:90},{y:"2007",a:75,b:65},{y:"2008",a:50,b:40},{y:"2009",a:75,b:65},{y:"2010",a:50,b:40},{y:"2011",a:75,b:65},{y:"2012",a:100,b:90}];new Morris.Line({element:"morris-line",data:e,xkey:"y",ykeys:["a","b"],labels:["Serie A","Serie B"],lineColors:["#31C0BE","#7a92a3"],resize:!0}),new Morris.Donut({element:"morris-donut",data:[{label:"Download Sales",value:12},{label:"In-Store Sales",value:30},{label:"Mail-Order Sales",value:20}],colors:["#f05050","#fad732","#ff902b"],resize:!0}),new Morris.Bar({element:"morris-bar",data:e,xkey:"y",ykeys:["a","b"],labels:["Series A","Series B"],xLabelMargin:2,barColors:["#23b7e5","#f05050"],resize:!0}),new Morris.Area({element:"morris-area",data:e,xkey:"y",ykeys:["a","b"],labels:["Serie A","Serie B"],lineColors:["#7266ba","#23b7e5"],resize:!0})}}),function(e,t,o,a){(0,window.jQuery)(function(){if("undefined"!=typeof Rickshaw){for(var e=[[],[],[]],o=new Rickshaw.Fixtures.RandomData(150),a=0;a<150;a++)o.addData(e);var n=[{color:"#c05020",data:e[0],name:"New York"},{color:"#30c020",data:e[1],name:"London"},{color:"#6060c0",data:e[2],name:"Tokyo"}];new Rickshaw.Graph({element:t.querySelector("#rickshaw1"),series:n,renderer:"area"}).render(),new Rickshaw.Graph({element:t.querySelector("#rickshaw2"),renderer:"area",stroke:!0,series:[{data:[{x:0,y:40},{x:1,y:49},{x:2,y:38},{x:3,y:30},{x:4,y:32}],color:"#f05050"},{data:[{x:0,y:40},{x:1,y:49},{x:2,y:38},{x:3,y:30},{x:4,y:32}],color:"#fad732"}]}).render(),new Rickshaw.Graph({element:t.querySelector("#rickshaw3"),renderer:"line",series:[{data:[{x:0,y:40},{x:1,y:49},{x:2,y:38},{x:3,y:30},{x:4,y:32}],color:"#7266ba"},{data:[{x:0,y:20},{x:1,y:24},{x:2,y:19},{x:3,y:15},{x:4,y:16}],color:"#23b7e5"}]}).render(),new Rickshaw.Graph({element:t.querySelector("#rickshaw4"),renderer:"bar",series:[{data:[{x:0,y:40},{x:1,y:49},{x:2,y:38},{x:3,y:30},{x:4,y:32}],color:"#fad732"},{data:[{x:0,y:20},{x:1,y:24},{x:2,y:19},{x:3,y:15},{x:4,y:16}],color:"#ff902b"}]}).render()}})}(window,document),function(e,t,o,a){o(function(){o("[data-sparkline]").each(function(){var t=o(this),a=t.data(),n=a.values&&a.values.split(",");a.type=a.type||"bar",a.disableHiddenCheck=!0,t.sparkline(n,a),a.resize&&o(e).resize(function(){t.sparkline(n,a)})})})}(window,document,window.jQuery),function(e,t,o,a){if(o.fn.fullCalendar){o(function(){var e,t,a,i,l,s,c,d=o("#calendar"),u=(e=new Date,t=e.getDate(),a=e.getMonth(),i=e.getFullYear(),[{title:"All Day Event",start:new Date(i,a,1),backgroundColor:"#f56954",borderColor:"#f56954"},{title:"Long Event",start:new Date(i,a,t-5),end:new Date(i,a,t-2),backgroundColor:"#f39c12",borderColor:"#f39c12"},{title:"Meeting",start:new Date(i,a,t,10,30),allDay:!1,backgroundColor:"#0073b7",borderColor:"#0073b7"},{title:"Lunch",start:new Date(i,a,t,12,0),end:new Date(i,a,t,14,0),allDay:!1,backgroundColor:"#00c0ef",borderColor:"#00c0ef"},{title:"Birthday Party",start:new Date(i,a,t+1,19,0),end:new Date(i,a,t+1,22,30),allDay:!1,backgroundColor:"#00a65a",borderColor:"#00a65a"},{title:"Open Google",start:new Date(i,a,28),end:new Date(i,a,29),url:"//google.com/",backgroundColor:"#3c8dbc",borderColor:"#3c8dbc"}]);!function(e){var t=o(".external-events");new r(t.children("div"));var a="#f6504d",i=o(".external-event-add-btn"),l=o(".external-event-name"),s=o(".external-event-color-selector .circle");o(".external-events-trash").droppable({accept:".fc-event",activeClass:"active",hoverClass:"hovered",tolerance:"touch",drop:function(t,o){if(n){var a=n.id||n._id;e.fullCalendar("removeEvents",a),o.draggable.remove(),n=null}}}),s.click(function(e){e.preventDefault();var t=o(this);a=t.css("background-color"),s.removeClass("selected"),t.addClass("selected")}),i.click(function(e){e.preventDefault();var n=l.val();if(""!==o.trim(n)){var i=o("<div/>").css({"background-color":a,"border-color":a,color:"#fff"}).html(n);t.prepend(i),new r(i),l.val("")}})}(d),l=d,s=u,c=o("#remove-after-drop"),l.fullCalendar({header:{left:"prev,next today",center:"title",right:"month,agendaWeek,agendaDay"},buttonIcons:{prev:" fa fa-caret-left",next:" fa fa-caret-right"},buttonText:{today:"today",month:"month",week:"week",day:"day"},editable:!0,droppable:!0,drop:function(e,t){var a=o(this),n=a.data("calendarEventObject");if(n){var r=o.extend({},n);r.start=e,r.allDay=t,r.backgroundColor=a.css("background-color"),r.borderColor=a.css("border-color"),l.fullCalendar("renderEvent",r,!0),c.is(":checked")&&a.remove()}},eventDragStart:function(e,t,o){n=e},events:s})});var n=null,r=function(e){e&&e.each(function(){var e=o(this),t={title:o.trim(e.text())};e.data("calendarEventObject",t),e.draggable({zIndex:1070,revert:!0,revertDuration:0})})}}}(window,document,window.jQuery),function(e,t,o,a){o.fn.jQCloud&&o(function(){o("#jqcloud").jQCloud([{text:"Lorem",weight:13},{text:"Ipsum",weight:10.5},{text:"Dolor",weight:9.4},{text:"Sit",weight:8},{text:"Amet",weight:6.2},{text:"Consectetur",weight:5},{text:"Adipiscing",weight:5},{text:"Sit",weight:8},{text:"Amet",weight:6.2},{text:"Consectetur",weight:5},{text:"Adipiscing",weight:5}],{width:240,height:200,steps:7})})}(window,document,window.jQuery),function(e,t,o,a){o.fn.slider&&o.fn.chosen&&o.fn.datepicker&&o(function(){o("[data-ui-slider]").slider(),o(".chosen-select").chosen(),o("#datetimepicker").datepicker({orientation:"bottom",icons:{time:"fa fa-clock-o",date:"fa fa-calendar",up:"fa fa-chevron-up",down:"fa fa-chevron-down",previous:"fa fa-chevron-left",next:"fa fa-chevron-right",today:"fa fa-crosshairs",clear:"fa fa-trash"}})})}(window,document,window.jQuery),function(e,t,o,a){o(function(){o.fn.colorpicker&&(o(".demo-colorpicker").colorpicker(),o("#demo_selectors").colorpicker({colorSelectors:{default:"#777777",primary:APP_COLORS.primary,success:APP_COLORS.success,info:APP_COLORS.info,warning:APP_COLORS.warning,danger:APP_COLORS.danger}}))})}(window,document,window.jQuery),function(e,t,o,a){o.fn.slider&&o.fn.chosen&&o.fn.inputmask&&o.fn.filestyle&&o.fn.wysiwyg&&o.fn.datepicker&&o(function(){o("[data-ui-slider]").slider(),o(".chosen-select").chosen(),o("[data-masked]").inputmask(),o(".filestyle").filestyle(),o(".wysiwyg").wysiwyg(),o("#datetimepicker1").datepicker({orientation:"bottom",icons:{time:"fa fa-clock-o",date:"fa fa-calendar",up:"fa fa-chevron-up",down:"fa fa-chevron-down",previous:"fa fa-chevron-left",next:"fa fa-chevron-right",today:"fa fa-crosshairs",clear:"fa fa-trash"}}),o("#datetimepicker2").datepicker({format:"mm-dd-yyyy"})})}(window,document,window.jQuery),function(e,t,o,a){o(function(){if(o.fn.cropper){var a=o(".img-container > img"),n=o("#dataX"),r=o("#dataY"),i=o("#dataHeight"),l=o("#dataWidth"),s=o("#dataRotate"),c={aspectRatio:16/9,preview:".img-preview",crop:function(e){n.val(Math.round(e.x)),r.val(Math.round(e.y)),i.val(Math.round(e.height)),l.val(Math.round(e.width)),s.val(Math.round(e.rotate))}};a.on({"build.cropper":function(e){console.log(e.type)},"built.cropper":function(e){console.log(e.type)},"dragstart.cropper":function(e){console.log(e.type,e.dragType)},"dragmove.cropper":function(e){console.log(e.type,e.dragType)},"dragend.cropper":function(e){console.log(e.type,e.dragType)},"zoomin.cropper":function(e){console.log(e.type)},"zoomout.cropper":function(e){console.log(e.type)},"change.cropper":function(e){console.log(e.type)}}).cropper(c),o(t.body).on("click","[data-method]",function(){var e,t,n=o(this).data();if(a.data("cropper")&&n.method){if(void 0!==(n=o.extend({},n)).target&&(e=o(n.target),void 0===n.option))try{n.option=JSON.parse(e.val())}catch(e){console.log(e.message)}if(t=a.cropper(n.method,n.option),"getCroppedCanvas"===n.method&&o("#getCroppedCanvasModal").modal().find(".modal-body").html(t),o.isPlainObject(t)&&e)try{e.val(JSON.stringify(t))}catch(e){console.log(e.message)}}}).on("keydown",function(e){if(a.data("cropper"))switch(e.which){case 37:e.preventDefault(),a.cropper("move",-1,0);break;case 38:e.preventDefault(),a.cropper("move",0,-1);break;case 39:e.preventDefault(),a.cropper("move",1,0);break;case 40:e.preventDefault(),a.cropper("move",0,1)}});var d,u=o("#inputImage"),f=e.URL||e.webkitURL;f?u.change(function(){var e,t=this.files;a.data("cropper")&&t&&t.length&&(e=t[0],/^image\/\w+$/.test(e.type)?(d=f.createObjectURL(e),a.one("built.cropper",function(){f.revokeObjectURL(d)}).cropper("reset").cropper("replace",d),u.val("")):alert("Please choose an image file."))}):u.parent().remove(),o(".docs-options :checkbox").on("change",function(){var e=o(this);a.data("cropper")&&(c[e.val()]=e.prop("checked"),a.cropper("destroy").cropper(c))}),o('[data-toggle="tooltip"]').tooltip()}})}(window,document,window.jQuery),function(e,t,o,a){o(function(){o.fn.select2&&(o("#select2-1").select2({theme:"bootstrap4"}),o("#select2-2").select2({theme:"bootstrap4"}),o("#select2-3").select2({theme:"bootstrap4"}),o("#select2-4").select2({placeholder:"Select a state",allowClear:!0,theme:"bootstrap4"}))})}(window,document,window.jQuery),function(e,t,o,a){"undefined"!=typeof Dropzone&&(Dropzone.autoDiscover=!1,o(function(){new Dropzone("#dropzone-area",{autoProcessQueue:!1,uploadMultiple:!0,parallelUploads:100,maxFiles:100,dictDefaultMessage:'<em class="ion-upload color-blue-grey-100 icon-2x"></em><br>Drop files here to upload',paramName:"file",maxFilesize:2,addRemoveLinks:!0,accept:function(e,t){"justinbieber.jpg"===e.name?t("Naha, you dont. :)"):t()},init:function(){var e=this;this.element.querySelector("button[type=submit]").addEventListener("click",function(t){t.preventDefault(),t.stopPropagation(),e.processQueue()}),this.on("addedfile",function(e){console.log("Added file: "+e.name)}),this.on("removedfile",function(e){console.log("Removed file: "+e.name)}),this.on("sendingmultiple",function(){}),this.on("successmultiple",function(){}),this.on("errormultiple",function(){})}})}))}(window,document,window.jQuery),function(e,t,o,a){o.fn.validate&&o(function(){var e=o("#example-form");e.validate({errorPlacement:function(e,t){t.before(e)},rules:{confirm:{equalTo:"#password"}}}),e.children("div").steps({headerTag:"h4",bodyTag:"fieldset",transitionEffect:"slideLeft",onStepChanging:function(t,o,a){return e.validate().settings.ignore=":disabled,:hidden",e.valid()},onFinishing:function(t,o){return e.validate().settings.ignore=":disabled",e.valid()},onFinished:function(e,t){alert("Submitted!"),o(this).submit()}}),o("#example-vertical").steps({headerTag:"h4",bodyTag:"section",transitionEffect:"slideLeft",stepsOrientation:"vertical"})})}(window,document,window.jQuery),function(e,t,o,a){o.fn.xeditable&&o(function(){o.fn.editableform.buttons='<button type="submit" class="btn btn-primary btn-sm editable-submit"><i class="fa fa-fw fa-check"></i></button><button type="button" class="btn btn-default btn-sm editable-cancel"><i class="fa fa-fw fa-times"></i></button>',o("#enable").click(function(){o("#user .editable").editable("toggleDisabled")}),o("#username").editable({type:"text",pk:1,name:"username",title:"Enter username",mode:"inline"}),o("#firstname").editable({validate:function(e){if(""===o.trim(e))return"This field is required"},mode:"inline"}),o("#sex").editable({prepend:"not selected",source:[{value:1,text:"Male"},{value:2,text:"Female"}],display:function(e,t){var a=o.grep(t,function(t){return t.value==e});a.length?o(this).text(a[0].text).css("color",{"":"gray",1:"green",2:"blue"}[e]):o(this).empty()},mode:"inline"}),o("#status").editable({mode:"inline"}),o("#group").editable({showbuttons:!1,mode:"inline"}),o("#dob").editable({mode:"inline"}),o("#event").editable({placement:"right",combodate:{firstItem:"name"},mode:"inline"}),o("#comments").editable({showbuttons:"bottom",mode:"inline"}),o("#note").editable({mode:"inline"}),o("#pencil").click(function(e){e.stopPropagation(),e.preventDefault(),o("#note").editable("toggle")}),o("#user .editable").on("hidden",function(e,t){if("save"===t||"nochange"===t){var a=o(this).closest("tr").next().find(".editable");o("#autoopen").is(":checked")?setTimeout(function(){a.editable("show")},300):a.focus()}}),o("#users a").editable({type:"text",name:"username",title:"Enter username",mode:"inline"})})}(window,document,window.jQuery),function(){"use strict";$(function(){if(!$.fn.bootgrid)return;$("#bootgrid-basic").bootgrid({templates:{actionButton:'<button class="btn btn-secondary" type="button" title="{{ctx.text}}">{{ctx.content}}</button>',actionDropDown:'<div class="{{css.dropDownMenu}}"><button class="btn btn-secondary dropdown-toggle dropdown-toggle-nocaret" type="button" data-toggle="dropdown"><span class="{{css.dropDownMenuText}}">{{ctx.content}}</span></button><ul class="{{css.dropDownMenuItems}}" role="menu"></ul></div>',actionDropDownItem:'<li class="dropdown-item"><a href="" data-action="{{ctx.action}}" class="dropdown-link {{css.dropDownItemButton}}">{{ctx.text}}</a></li>',actionDropDownCheckboxItem:'<li class="dropdown-item"><label class="dropdown-item p-0"><input name="{{ctx.name}}" type="checkbox" value="1" class="{{css.dropDownItemCheckbox}}" {{ctx.checked}} /> {{ctx.label}}</label></li>',paginationItem:'<li class="page-item {{ctx.css}}"><a href="" data-page="{{ctx.page}}" class="page-link {{css.paginationButton}}">{{ctx.text}}</a></li>'}}),$("#bootgrid-selection").bootgrid({selection:!0,multiSelect:!0,rowSelect:!0,keepSelection:!0,templates:{select:'<div class="checkbox c-checkbox"><label class="mb-0"><input type="{{ctx.type}}" class="{{css.selectBox}}" value="{{ctx.value}}" {{ctx.checked}}><span class="fa fa-check"></span></label></div>',actionButton:'<button class="btn btn-secondary" type="button" title="{{ctx.text}}">{{ctx.content}}</button>',actionDropDown:'<div class="{{css.dropDownMenu}}"><button class="btn btn-secondary dropdown-toggle dropdown-toggle-nocaret" type="button" data-toggle="dropdown"><span class="{{css.dropDownMenuText}}">{{ctx.content}}</span></button><ul class="{{css.dropDownMenuItems}}" role="menu"></ul></div>',actionDropDownItem:'<li class="dropdown-item"><a href="" data-action="{{ctx.action}}" class="dropdown-link {{css.dropDownItemButton}}">{{ctx.text}}</a></li>',actionDropDownCheckboxItem:'<li class="dropdown-item"><label class="dropdown-item p-0"><input name="{{ctx.name}}" type="checkbox" value="1" class="{{css.dropDownItemCheckbox}}" {{ctx.checked}} /> {{ctx.label}}</label></li>',paginationItem:'<li class="page-item {{ctx.css}}"><a href="" data-page="{{ctx.page}}" class="page-link {{css.paginationButton}}">{{ctx.text}}</a></li>'}});var e=$("#bootgrid-command").bootgrid({formatters:{commands:function(e,t){return'<button type="button" class="btn btn-sm btn-info mr-2 command-edit" data-row-id="'+t.id+'"><em class="fa fa-edit fa-fw"></em></button><button type="button" class="btn btn-sm btn-danger command-delete" data-row-id="'+t.id+'"><em class="fa fa-trash fa-fw"></em></button>'}},templates:{actionButton:'<button class="btn btn-secondary" type="button" title="{{ctx.text}}">{{ctx.content}}</button>',actionDropDown:'<div class="{{css.dropDownMenu}}"><button class="btn btn-secondary dropdown-toggle dropdown-toggle-nocaret" type="button" data-toggle="dropdown"><span class="{{css.dropDownMenuText}}">{{ctx.content}}</span></button><ul class="{{css.dropDownMenuItems}}" role="menu"></ul></div>',actionDropDownItem:'<li class="dropdown-item"><a href="" data-action="{{ctx.action}}" class="dropdown-link {{css.dropDownItemButton}}">{{ctx.text}}</a></li>',actionDropDownCheckboxItem:'<li class="dropdown-item"><label class="dropdown-item p-0"><input name="{{ctx.name}}" type="checkbox" value="1" class="{{css.dropDownItemCheckbox}}" {{ctx.checked}} /> {{ctx.label}}</label></li>',paginationItem:'<li class="page-item {{ctx.css}}"><a href="" data-page="{{ctx.page}}" class="page-link {{css.paginationButton}}">{{ctx.text}}</a></li>'}}).on("loaded.rs.jquery.bootgrid",function(){e.find(".command-edit").on("click",function(){console.log("You pressed edit on row: "+$(this).data("row-id"))}).end().find(".command-delete").on("click",function(){console.log("You pressed delete on row: "+$(this).data("row-id"))})})})}(),function(){"use strict";$(function(){if(!$.fn.DataTable)return;$("#datatable1").DataTable({paging:!0,ordering:!0,info:!0,responsive:!0,oLanguage:{sSearch:'<em class="ion-search"></em>',sLengthMenu:"_MENU_ records per page",info:"Showing page _PAGE_ of _PAGES_",zeroRecords:"Nothing found - sorry",infoEmpty:"No records available",infoFiltered:"(filtered from _MAX_ total records)",oPaginate:{sNext:'<em class="fa fa-caret-right"></em>',sPrevious:'<em class="fa fa-caret-left"></em>'}}}),$("#datatable2").DataTable({paging:!0,ordering:!0,info:!0,responsive:!0,oLanguage:{sSearch:"Search all columns:",sLengthMenu:"_MENU_ records per page",info:"Showing page _PAGE_ of _PAGES_",zeroRecords:"Nothing found - sorry",infoEmpty:"No records available",infoFiltered:"(filtered from _MAX_ total records)",oPaginate:{sNext:'<em class="fa fa-caret-right"></em>',sPrevious:'<em class="fa fa-caret-left"></em>'}},dom:"Bfrtip",buttons:[{extend:"copy",className:"btn-info"},{extend:"csv",className:"btn-info"},{extend:"excel",className:"btn-info",title:"XLS-File"},{extend:"pdf",className:"btn-info",title:$("title").text()},{extend:"print",className:"btn-info"}]}),$("#datatable3").DataTable({paging:!0,ordering:!0,info:!0,responsive:!0,oLanguage:{sSearch:"Search all columns:",sLengthMenu:"_MENU_ records per page",info:"Showing page _PAGE_ of _PAGES_",zeroRecords:"Nothing found - sorry",infoEmpty:"No records available",infoFiltered:"(filtered from _MAX_ total records)",oPaginate:{sNext:'<em class="fa fa-caret-right"></em>',sPrevious:'<em class="fa fa-caret-left"></em>'}},keys:!0})})}(),function(e,t,o){"use strict";var a={errorClass:"is-invalid",successClass:"is-valid",classHandler:function(e){var t=e.$element.parents(".form-group").find("input");return t.length||(t=e.$element.parents(".c-checkbox").find("label")),t},errorsContainer:function(e){return e.$element.parents(".form-group")},errorsWrapper:'<div class="text-help">',errorTemplate:"<div></div>"},n=e("#loginForm");n.length&&n.parsley(a);var r=e("#registerForm");r.length&&r.parsley(a)}(jQuery,window,document),function(e,t,o){"use strict";var a=[{featureType:"water",stylers:[{visibility:"on"},{color:"#bdd1f9"}]},{featureType:"all",elementType:"labels.text.fill",stylers:[{color:"#334165"}]},{featureType:"landscape",stylers:[{color:"#e9ebf1"}]},{featureType:"road.highway",elementType:"geometry",stylers:[{color:"#c5c6c6"}]},{featureType:"road.arterial",elementType:"geometry",stylers:[{color:"#fff"}]},{featureType:"road.local",elementType:"geometry",stylers:[{color:"#fff"}]},{featureType:"transit",elementType:"geometry",stylers:[{color:"#d8dbe0"}]},{featureType:"poi",elementType:"geometry",stylers:[{color:"#cfd5e0"}]},{featureType:"administrative",stylers:[{visibility:"on"},{lightness:33}]},{featureType:"poi.park",elementType:"labels",stylers:[{visibility:"on"},{lightness:20}]},{featureType:"road",stylers:[{color:"#d8dbe0",lightness:20}]}];if(e.fn.gMap){var n=[];e("[data-gmap]").each(function(){var t=e(this),o=t.data("address")&&t.data("address").split(";"),r=t.data("title")&&t.data("title").split(";"),i=t.data("zoom")||14,l=t.data("maptype")||"ROADMAP",s=[];if(o){for(var c in o)"string"==typeof o[c]&&s.push({address:o[c],html:r&&r[c]||"",popup:!0});var d={controls:{panControl:!0,zoomControl:!0,mapTypeControl:!0,scaleControl:!0,streetViewControl:!0,overviewMapControl:!0},scrollwheel:!1,maptype:l,markers:s,zoom:i},u=t.gMap(d).data("gMap.reference");n.push(u),void 0!==t.data("styled")&&u.setOptions({styles:a})}})}}(jQuery,window,document),function(e,t,o,a){o(function(){var e=o("[data-vector-map]");new VectorMap(e,n,r)});var n={CA:11100,DE:2510,FR:3710,AU:5710,GB:8310,RU:9310,BR:6610,IN:7810,CN:4310,US:839,SA:410},r=[{latLng:[41.9,12.45],name:"Vatican City"},{latLng:[43.73,7.41],name:"Monaco"},{latLng:[-.52,166.93],name:"Nauru"},{latLng:[-8.51,179.21],name:"Tuvalu"},{latLng:[7.11,171.06],name:"Marshall Islands"},{latLng:[17.3,-62.73],name:"Saint Kitts and Nevis"},{latLng:[3.2,73.22],name:"Maldives"},{latLng:[35.88,14.5],name:"Malta"},{latLng:[41,-71.06],name:"New England"},{latLng:[12.05,-61.75],name:"Grenada"},{latLng:[13.16,-59.55],name:"Barbados"},{latLng:[17.11,-61.85],name:"Antigua and Barbuda"},{latLng:[-4.61,55.45],name:"Seychelles"},{latLng:[7.35,134.46],name:"Palau"},{latLng:[42.5,1.51],name:"Andorra"}]}(window,document,window.jQuery),function(e,t,o,a){e.defaultColors={markerColor:"#23b7e5",bgColor:"transparent",scaleColors:["#878c9a"],regionFill:"#bbbec6"},e.VectorMap=function(e,t,o){if(e&&e.length){var a,n,r,i=e.data(),l=i.height||"300",s={markerColor:i.markerColor||defaultColors.markerColor,bgColor:i.bgColor||defaultColors.bgColor,scale:i.scale||1,scaleColors:i.scaleColors||defaultColors.scaleColors,regionFill:i.regionFill||defaultColors.regionFill,mapName:i.mapName||"world_mill_en"};e.css("height",l),a=s,n=t,r=o,e.vectorMap({map:a.mapName,backgroundColor:a.bgColor,zoomMin:1,zoomMax:8,zoomOnScroll:!1,regionStyle:{initial:{fill:a.regionFill,"fill-opacity":1,stroke:"none","stroke-width":1.5,"stroke-opacity":1},hover:{"fill-opacity":.8},selected:{fill:"blue"},selectedHover:{}},focusOn:{x:.4,y:.6,scale:a.scale},markerStyle:{initial:{fill:a.markerColor,stroke:a.markerColor}},onRegionLabelShow:function(e,t,o){n&&n[o]&&t.html(t.html()+": "+n[o]+" visitors")},markers:r,series:{regions:[{values:n,scale:a.scaleColors,normalizeFunction:"polynomial"}]}})}}}(window,document,window.jQuery),window,document,(0,window.jQuery)(function(){});
| 4,556.545455 | 49,940 | 0.683093 |
1204b9476193d9b7a55bfa796e3b52f0b2b8a1c3
| 1,026 |
kt
|
Kotlin
|
src/main/kotlin/de/sambalmueslie/games/hll/tool/game/db/TranslationEntryRepository.kt
|
sambalmueslie/hll-tool
|
a67a6acefeb38b341bc87d24c5e44157349a62a5
|
[
"Apache-2.0"
] | null | null | null |
src/main/kotlin/de/sambalmueslie/games/hll/tool/game/db/TranslationEntryRepository.kt
|
sambalmueslie/hll-tool
|
a67a6acefeb38b341bc87d24c5e44157349a62a5
|
[
"Apache-2.0"
] | 6 |
2022-02-22T22:02:57.000Z
|
2022-03-24T23:11:22.000Z
|
src/main/kotlin/de/sambalmueslie/games/hll/tool/game/db/TranslationEntryRepository.kt
|
sambalmueslie/hll-tool
|
a67a6acefeb38b341bc87d24c5e44157349a62a5
|
[
"Apache-2.0"
] | 1 |
2021-12-19T22:14:38.000Z
|
2021-12-19T22:14:38.000Z
|
package de.sambalmueslie.games.hll.tool.game.db
import io.micronaut.data.annotation.Query
import io.micronaut.data.annotation.Repository
import io.micronaut.data.jdbc.annotation.JdbcRepository
import io.micronaut.data.model.Page
import io.micronaut.data.model.Pageable
import io.micronaut.data.model.query.builder.sql.Dialect
import io.micronaut.data.repository.PageableRepository
@Repository
@JdbcRepository(dialect = Dialect.POSTGRES)
interface TranslationEntryRepository : PageableRepository<TranslationEntryData, Long> {
fun findByTranslationId(translationId: Long): List<TranslationEntryData>
fun findByTranslationId(translationId: Long, pageable: Pageable): Page<TranslationEntryData>
fun findByTranslationIdAndKey(translationId: Long, key: String): TranslationEntryData?
@Query("SELECT e.* from game_translation_entry e INNER JOIN game_translation t ON t.id = e.translation_id WHERE t.lang = :lang and e.key = :key")
fun findByKeyAndLanguage(key: String, lang: String): TranslationEntryData?
}
| 44.608696 | 149 | 0.815789 |
f08d6a5ab818812444812ca4dc80526029133be3
| 5,649 |
js
|
JavaScript
|
brototype.js
|
letsgetrandy/brototype
|
731b02f614971341e6677adc763cb3efafb64c35
|
[
"MIT"
] | 945 |
2015-01-07T12:28:39.000Z
|
2022-03-29T02:40:45.000Z
|
brototype.js
|
letsgetrandy/brototype
|
731b02f614971341e6677adc763cb3efafb64c35
|
[
"MIT"
] | 31 |
2015-01-05T23:35:30.000Z
|
2021-03-22T05:49:34.000Z
|
brototype.js
|
letsgetrandy/brototype
|
731b02f614971341e6677adc763cb3efafb64c35
|
[
"MIT"
] | 48 |
2015-01-27T12:20:10.000Z
|
2021-12-06T12:07:26.000Z
|
/*global module:true, window:true, require:false, define:false*/
(function() {
'use strict';
// Bromise... it's stronger than a Promise
function Bromise(object, method, args) {
this.object = object;
this.method = method;
this.args = args.length > 1 ? args.slice(1) : [];
}
Bromise.brototype = Bromise.prototype = {
"butWhenIdo": function(callback, context) {
if (this.method instanceof Function) {
var returnValue = this.method.apply(this.object, this.args);
if (returnValue) {
(callback || function(){}).call(context || this.object, returnValue);
}
}
return context;
},
"hereComeTheErrors": function(callback) {
if (this.method instanceof Function) {
try {
this.method.apply(this.object, this.args);
} catch(e) {
callback(e);
}
} else {
callback(this.method + ' is not a function.');
}
},
"errorsAreComing": function () {
this.hereComeTheErrors.apply(this, arguments);
}
};
function Bro(obj) {
if (this instanceof Bro) {
this.obj = obj;
} else {
return new Bro(obj);
}
}
Bro.TOTALLY = true;
Bro.NOWAY = false;
Bro.brototype = Bro.prototype = {
"isThatEvenAThing": function() {
return this.obj !== void 0;
},
"doYouEven": function(key, callback, options) {
if (!(callback instanceof Function)) {
options = callback;
}
var optionsBro = Bro(options || {});
if (!(key instanceof Array)) {
key = [key];
}
var self = this;
if (key.every(function(k) {
var bro = self.iCanHaz(k);
return (Bro(bro).isThatEvenAThing() === Bro.TOTALLY);
})) {
optionsBro.iDontAlways('forSure').butWhenIdo();
// Perform callback function
if (callback) {
for (var i = 0; i < key.length; i++) {
callback(self.obj[key[i]], key[i]);
}
}
return Bro.TOTALLY;
} else {
optionsBro.iDontAlways('sorryBro').butWhenIdo();
return Bro.NOWAY;
}
},
"iCanHaz": function(key) {
if (Array.isArray(key)) {
var index, value, result = [];
for (index in key) {
if (key.hasOwnProperty(index)) {
value = this.iCanHaz(key[index]);
result.push(value);
}
}
return result;
}
var props = key.split('.'),
item = this.obj;
for (var i = 0; i < props.length; i++) {
if (typeof item === "undefined" || item === null || Bro(item = item[props[i]]).isThatEvenAThing() === Bro.NOWAY) {
return undefined;
}
}
return item;
},
"comeAtMe": function(brobject) {
var i, prop,
bro = Bro(brobject),
keys = bro.giveMeProps(),
obj = (this instanceof Bro) ? this.obj : Bro.prototype;
for (i = 0; i < keys.length; i++) {
prop = keys[i];
if (bro.hasRespect(prop)) {
obj[prop] = brobject[prop];
}
}
},
"giveMeProps": function() {
var key, props = [];
if (Object.keys) {
props = Object.keys(this.obj);
} else {
for (key in this.obj) {
if (this.obj.hasRespect(key)) {
props.push(key);
}
}
}
return props;
},
"hasRespect": function(prop) {
return this.obj.hasOwnProperty(prop);
},
"iDontAlways": function(methodString) {
var method = this.iCanHaz(methodString);
return new Bromise(this.obj, method, arguments);
},
"braceYourself": function(methodString) {
var method = this.iCanHaz(methodString);
return new Bromise(this.obj, method, arguments);
},
"makeItHappen": function(key, value) {
var brobj = this.obj;
var props = key.split('.');
for (var i = 0; i < props.length - 1; ++i) {
if (brobj[props[i]] === undefined) {
brobj[props[i]] = {};
}
brobj = brobj[props[i]];
}
// the deepest key is set to either an empty object or the value provided
brobj[props[props.length - 1]] = value === undefined ? {} : value;
}
};
(function() {
if (typeof define === 'function' && typeof define.amd === 'object') {
define(function() {
return Bro;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = Bro;
} else if (typeof window !== 'undefined') {
window.Bro = Bro;
}
if (typeof(angular) !== 'undefined') {
angular.module('brototype', []).factory('Bro', function() { return Bro; });
}
})();
})();
| 32.096591 | 130 | 0.438485 |
1e4a7d298f3670aa1cd8f7f92260c244a4f12f4a
| 402 |
css
|
CSS
|
V9 (CSS)/meiryoui.css
|
MasterDalK/kktCSS
|
8592874732c352baccece088b47fbaae40b11bb6
|
[
"MIT"
] | 27 |
2017-04-16T03:13:34.000Z
|
2020-06-30T00:37:25.000Z
|
V9 (CSS)/meiryoui.css
|
MasterDalK/kktCSS
|
8592874732c352baccece088b47fbaae40b11bb6
|
[
"MIT"
] | 46 |
2017-04-16T04:48:22.000Z
|
2020-04-07T20:44:46.000Z
|
V9 (CSS)/meiryoui.css
|
MasterDalK/kktCSS
|
8592874732c352baccece088b47fbaae40b11bb6
|
[
"MIT"
] | 8 |
2017-04-16T03:41:15.000Z
|
2017-08-13T18:10:18.000Z
|
@font-face {
font-family: 'Meiryo UI';
font-style: normal;
font-weight: normal;
letter-spacing: .1em;
padding: 1em;
}
@media screen and (-webkit-min-device-pixel-ratio:0) {
@font-face {
font-family: 'Meiryo UI';
letter-spacing: .1em;
padding: 1em;
}
}
body {
font-family: "Meiryo UI";
font-style: normal;
font-weight: normal;
letter-spacing: .1em;
padding: 1em;
}
| 16.75 | 54 | 0.631841 |
7564b1bed71d63edf90f7ca9438f83ca113edfcb
| 334 |
h
|
C
|
Example/Pods/Headers/Private/PandaFMDB/OPFTableProtocol.h
|
lingen/PandaFMDB
|
a76251063b6eac3f367e2299e56f9a61b053f584
|
[
"MIT"
] | null | null | null |
Example/Pods/Headers/Private/PandaFMDB/OPFTableProtocol.h
|
lingen/PandaFMDB
|
a76251063b6eac3f367e2299e56f9a61b053f584
|
[
"MIT"
] | null | null | null |
Example/Pods/Headers/Private/PandaFMDB/OPFTableProtocol.h
|
lingen/PandaFMDB
|
a76251063b6eac3f367e2299e56f9a61b053f584
|
[
"MIT"
] | null | null | null |
//
// OPTableProtocol.h
// Pods
//
// Created by lingen on 16/3/21.
//
//
#import <Foundation/Foundation.h>
@class OPFTable;
@protocol OPFTableProtocol <NSObject>
@required
/*
* 实现此方法,用于数据库表的创建
*/
+(OPFTable*)createTable;
/*
*实现此方法,用于数据库表的升级功能
*/
+(NSArray*)updateTable:(int)fromVersion toVersion:(int)toVersion;
@end
| 11.133333 | 65 | 0.679641 |
4b7f84cf0d276e61e97004664ed311373e1a22e4
| 1,838 |
kt
|
Kotlin
|
kotlinsugardemo/src/test/java/dev/mko/kotlinsugardemo/KotlinSugarDemoTest.kt
|
mark-kowalski/KotlinExtensions-Android
|
f76453e35e37e8daf28602f903e4d623e4252853
|
[
"MIT"
] | null | null | null |
kotlinsugardemo/src/test/java/dev/mko/kotlinsugardemo/KotlinSugarDemoTest.kt
|
mark-kowalski/KotlinExtensions-Android
|
f76453e35e37e8daf28602f903e4d623e4252853
|
[
"MIT"
] | null | null | null |
kotlinsugardemo/src/test/java/dev/mko/kotlinsugardemo/KotlinSugarDemoTest.kt
|
mark-kowalski/KotlinExtensions-Android
|
f76453e35e37e8daf28602f903e4d623e4252853
|
[
"MIT"
] | null | null | null |
package dev.mko.kotlinsugardemo
import dev.mko.kotlinsugar.model.AssociatedEnum
import dev.mko.kotlinsugar.multiCatch
import dev.mko.kotlinsugar.multiLet
import org.junit.Test
import java.io.IOException
/**
* Unit test to demonstrate how to use these awesome Extension functions
*/
class KotlinSugarDemoTest {
@Test
fun multiCatchTest_successfulCatch() {
multiCatch({
throw IOException()
}, { e ->
assert(true) // Do some logging or whatever instead
}, ReflectiveOperationException::class, IOException::class)
multiCatch({
// ClassNotFoundException is inheritance of ReflectiveOperationException. This should also work.
throw ClassNotFoundException()
}, { e ->
assert(true) // Do some logging or whatever instead
}, ReflectiveOperationException::class, IOException::class)
}
@Test
fun multiCatchTest_forwardException() {
try {
multiCatch({
throw ArrayIndexOutOfBoundsException()
}, { e ->
assert(false)
}, ClassNotFoundException::class, IOException::class)
} catch (e: ArrayIndexOutOfBoundsException) {
assert(true)
}
}
@Test
fun multiLet_success() {
multiLet("", 1) { anyString, anyInt ->
assert(anyString == "")
assert(anyInt == 1)
assert(true)
}
}
@Test
fun multiLet_fail() {
multiLet("", 1) { anyString, anyInt ->
assert(true)
}
}
@Test
fun associatedEnum_test() {
var associatedEnum: AssociatedEnum = AssociatedEnum.Unknown
assert(!associatedEnum.value5)
associatedEnum = AssociatedEnum.Valid("", 3, 1)
assert(associatedEnum.value5)
}
}
| 26.637681 | 108 | 0.605005 |
932f8abc5ef5b178e864eb8ee5aa76114a4dde35
| 511 |
kt
|
Kotlin
|
presentation/controller/src/main/kotlin/com/kazakago/blueprint/presentation/controller/global/entrypoint/MainActivity.kt
|
weathercock/AndroidCleanArchitectureSample
|
9d92409366926b8d19645dd454acc8610c84a44b
|
[
"Apache-2.0"
] | null | null | null |
presentation/controller/src/main/kotlin/com/kazakago/blueprint/presentation/controller/global/entrypoint/MainActivity.kt
|
weathercock/AndroidCleanArchitectureSample
|
9d92409366926b8d19645dd454acc8610c84a44b
|
[
"Apache-2.0"
] | null | null | null |
presentation/controller/src/main/kotlin/com/kazakago/blueprint/presentation/controller/global/entrypoint/MainActivity.kt
|
weathercock/AndroidCleanArchitectureSample
|
9d92409366926b8d19645dd454acc8610c84a44b
|
[
"Apache-2.0"
] | null | null | null |
package com.kazakago.blueprint.presentation.controller.global.entrypoint
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.kazakago.blueprint.presentation.controller.global.routing.Router
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent { Router() }
}
}
| 30.058824 | 75 | 0.806262 |
ce7686c970d95cd193b291be3c0da2f75bc91d14
| 1,953 |
kt
|
Kotlin
|
apptentive-survey/src/main/java/apptentive/com/android/feedback/survey/model/SurveyResponsePayload.kt
|
apptentive/apptentive-android-sdk
|
7f158214cf78ef91f667136e79dbfaf56f3b7308
|
[
"BSD-3-Clause"
] | null | null | null |
apptentive-survey/src/main/java/apptentive/com/android/feedback/survey/model/SurveyResponsePayload.kt
|
apptentive/apptentive-android-sdk
|
7f158214cf78ef91f667136e79dbfaf56f3b7308
|
[
"BSD-3-Clause"
] | null | null | null |
apptentive-survey/src/main/java/apptentive/com/android/feedback/survey/model/SurveyResponsePayload.kt
|
apptentive/apptentive-android-sdk
|
7f158214cf78ef91f667136e79dbfaf56f3b7308
|
[
"BSD-3-Clause"
] | null | null | null |
package apptentive.com.android.feedback.survey.model
import androidx.annotation.Keep
import apptentive.com.android.feedback.Constants.buildHttpPath
import apptentive.com.android.feedback.engagement.interactions.InteractionId
import apptentive.com.android.feedback.model.payloads.ConversationPayload
import apptentive.com.android.feedback.payload.MediaType
import apptentive.com.android.feedback.payload.PayloadType
import apptentive.com.android.network.HttpMethod
import apptentive.com.android.util.generateUUID
@Keep
internal class SurveyResponsePayload(
nonce: String = generateUUID(),
val id: String,
val answers: Map<String, List<AnswerData>>
) : ConversationPayload(nonce = nonce) {
data class AnswerData(
val id: String? = null,
val value: Any? = null
)
override fun getPayloadType() = PayloadType.SurveyResponse
override fun getJsonContainer() = "response"
override fun getHttpMethod() = HttpMethod.POST
override fun getHttpPath() = buildHttpPath("surveys/$id/responses")
override fun getContentType() = MediaType.applicationJson
companion object {
fun fromAnswers(
id: InteractionId,
answers: Map<String, SurveyQuestionAnswer>
) = SurveyResponsePayload(
id = id,
answers = answers
.map { (id, answer) -> id to convertAnswer(answer) }
.toMap()
)
private fun convertAnswer(answer: SurveyQuestionAnswer) =
when (answer) {
is SingleLineQuestion.Answer -> listOf(AnswerData(value = answer.value))
is RangeQuestion.Answer -> listOf(AnswerData(value = answer.selectedIndex))
is MultiChoiceQuestion.Answer -> answer.choices.mapNotNull { if (it.checked) AnswerData(it.id, it.value) else null }
else -> throw IllegalArgumentException("Unexpected type: ${answer::class.java}")
}
}
}
| 36.849057 | 132 | 0.69022 |
739c4d8c0ff0142ea91a26701a2294cb09da0abb
| 526 |
sql
|
SQL
|
queries/sherlock/setup/feed_quality_score.sql
|
stefmolin/watson-api
|
49ca922f66646f3134b500c4ec9e6cd23fb31f2c
|
[
"MIT"
] | null | null | null |
queries/sherlock/setup/feed_quality_score.sql
|
stefmolin/watson-api
|
49ca922f66646f3134b500c4ec9e6cd23fb31f2c
|
[
"MIT"
] | 1 |
2018-09-20T01:04:57.000Z
|
2018-10-06T21:39:44.000Z
|
queries/sherlock/setup/feed_quality_score.sql
|
stefmolin/watson-api
|
49ca922f66646f3134b500c4ec9e6cd23fb31f2c
|
[
"MIT"
] | null | null | null |
SELECT
day
, CASE WHEN COUNT(DISTINCT day) = 0 THEN 0
ELSE (SUM(catalog_quality)/COUNT(DISTINCT day))/10000 END AS feed_quality
, MAX(last_date_import) AS feed_import
FROM
schema.fact_table AS fc
JOIN
(SELECT
partner_id
, client_id
FROM
schema.dim_table
WHERE
client_id = {client_id}
GROUP BY
partner_id
, client_id) c
ON
c.partner_id = fc.partner_id
WHERE
client_id = {client_id}
AND day BETWEEN '{start_date}' AND '{end_date}'
GROUP BY
client_id
, day
ORDER BY
day
| 18.137931 | 82 | 0.692015 |
c829c2d4ff87ef172ea1732f1adad21590a72250
| 1,586 |
lua
|
Lua
|
server/main.lua
|
vwxyzzett/td-atmrob
|
d0259d1c841e5f5d2f577db1de98a6c9425c2880
|
[
"Apache-2.0"
] | null | null | null |
server/main.lua
|
vwxyzzett/td-atmrob
|
d0259d1c841e5f5d2f577db1de98a6c9425c2880
|
[
"Apache-2.0"
] | null | null | null |
server/main.lua
|
vwxyzzett/td-atmrob
|
d0259d1c841e5f5d2f577db1de98a6c9425c2880
|
[
"Apache-2.0"
] | 1 |
2022-02-15T12:53:47.000Z
|
2022-02-15T12:53:47.000Z
|
ESX = nil
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
ESX.RegisterServerCallback('hasan:copCount', function(source, cb)
local xPlayers = ESX.GetPlayers()
copConnected = 0
for i=1, #xPlayers, 1 do
local xPlayer = ESX.GetPlayerFromId(xPlayers[i])
if xPlayer.job.name == 'police' then
copConnected = copConnected + 1
end
end
cb(copConnected)
end)
RegisterNetEvent('td-atmrob:givemoney')
AddEventHandler('td-atmrob:givemoney', function()
local xPlayer = ESX.GetPlayerFromId(source)
xPlayer.addMoney(Config.Money)
end)
ESX.RegisterUsableItem('usefulusb', function(source)
local xPlayer = ESX.GetPlayerFromId(source)
TriggerClientEvent('td-atmrob:client:start', source)
end)
RegisterNetEvent('td-atmrob:giveitem')
AddEventHandler('td-atmrob:giveitem', function()
local xPlayer = ESX.GetPlayerFromId(source)
local Item = 'documents'
xPlayer.addInventoryItem(Item,1)
end)
ESX.RegisterServerCallback("hasan:itemkontrol", function(source, cb, itemname)
local xPlayer = ESX.GetPlayerFromId(source)
local item = xPlayer.getInventoryItem(itemname)["count"]
if item >= 1 then
cb(true)
else
cb(false)
end
end)
RegisterServerEvent("hasan:itemsil2")
AddEventHandler("hasan:itemsil2", function(itemname)
local xPlayer = ESX.GetPlayerFromId(source)
xPlayer.removeInventoryItem(itemname, count)
end)
RegisterServerEvent('hasan:itemver2')
AddEventHandler('hasan:itemver2', function(item, count)
local player = ESX.GetPlayerFromId(source)
player.addInventoryItem(item, count)
end)
| 24.030303 | 78 | 0.742749 |
4a2fbf7c9e1a02547e27985eabbd8e286a972048
| 1,897 |
js
|
JavaScript
|
generators/app/templates/webpack.config.js
|
deyhle/generator-ec.dynamic-website
|
4facdb984a4c3a692b9a578f07cb5c47efedcda3
|
[
"MIT"
] | 1 |
2020-07-29T18:59:16.000Z
|
2020-07-29T18:59:16.000Z
|
generators/app/templates/webpack.config.js
|
deyhle/generator-ec.dynamic-website
|
4facdb984a4c3a692b9a578f07cb5c47efedcda3
|
[
"MIT"
] | 3 |
2020-09-04T16:51:46.000Z
|
2021-05-08T06:17:46.000Z
|
generators/app/templates/webpack.config.js
|
deyhle/generator-ec.dynamic-website
|
4facdb984a4c3a692b9a578f07cb5c47efedcda3
|
[
"MIT"
] | null | null | null |
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const FixStyleOnlyEntriesPlugin = require('webpack-fix-style-only-entries');
module.exports = {
entry: {
main: ['intersection-observer', 'babel-polyfill', './src/main.js'],
styles: ['./style/style.scss'],
},
node: {
fs: 'empty',
Buffer: true,
net: 'empty',
tls: 'empty',
},
devtool: process.env.NODE_ENV === 'production' ? false : 'source-map',
output: {
path: path.resolve('static'),
filename: 'main.js?hash=[hash]',
},
resolve: {
alias: {
vue: process.env.NODE_ENV === 'production' ? 'vue/dist/vue.min.js' : 'vue/dist/vue.esm.js',
},
},
module: {
rules: [
{
test: /\.js$/,
// exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: [
[
'@babel/preset-env',
{
targets: {
browsers: ['last 3 versions', 'ie 9'],
},
},
],
],
plugins: ['@babel/plugin-syntax-dynamic-import'],
},
},
},
{
test: /\.scss$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
],
},
optimization: {
minimize: process.env.NODE_ENV === 'production',
},
mode: process.env.NODE_ENV,
plugins: [
new FixStyleOnlyEntriesPlugin(),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'main.css?hash=[hash]',
chunkFilename: 'main-[id].css?hash=[hash]',
}),
new ManifestPlugin(), // outputs hashes to manifest.json for getMinifiedFile nunjucks filter
],
};
| 25.635135 | 97 | 0.534001 |
b516f6a02af30c7eab2766b0881373c52e49499b
| 839 |
rs
|
Rust
|
host/build/rust.rs
|
CDirkx/ipcheck
|
d222a7a5a1377715ea68a62f864077ea34655b95
|
[
"MIT"
] | null | null | null |
host/build/rust.rs
|
CDirkx/ipcheck
|
d222a7a5a1377715ea68a62f864077ea34655b95
|
[
"MIT"
] | null | null | null |
host/build/rust.rs
|
CDirkx/ipcheck
|
d222a7a5a1377715ea68a62f864077ea34655b95
|
[
"MIT"
] | null | null | null |
pub fn build() -> std::io::Result<&'static str> {
if !std::path::Path::new("../artifacts/rust").exists() {
std::fs::create_dir("../artifacts/rust").expect("failed to create Rust artifacts dir");
}
std::fs::copy("../impls/rust/main.rs", "../artifacts/rust/main.rs")?;
std::fs::copy("../impls/rust/Cargo.toml", "../artifacts/rust/Cargo.toml")?;
let output = std::process::Command::new("cargo")
.args(&[
"build",
"--release",
"-Z", "unstable-options",
"--out-dir", ".",
])
.current_dir("../artifacts/rust")
.output()?;
if output.status.success() {
Ok("../artifacts/rust/ipcheck")
} else {
Err(std::io::Error::new(std::io::ErrorKind::Other, format!("{:?}", String::from_utf8_lossy(&output.stderr))))
}
}
| 33.56 | 117 | 0.529201 |
3e6413db8d045f8f8ddfe7d6379cdd2de7d6049d
| 17,812 |
h
|
C
|
src/callback.h
|
tiankk/taskthread
|
10fa84c7d31da3365b8aad31d96f739ffb001af4
|
[
"MIT"
] | 1 |
2016-09-12T12:43:12.000Z
|
2016-09-12T12:43:12.000Z
|
src/callback.h
|
tiankk/taskthread
|
10fa84c7d31da3365b8aad31d96f739ffb001af4
|
[
"MIT"
] | null | null | null |
src/callback.h
|
tiankk/taskthread
|
10fa84c7d31da3365b8aad31d96f739ffb001af4
|
[
"MIT"
] | null | null | null |
#ifndef __CALLBACK_H__
#define __CALLBACK_H__
#include "callback_internal.h"
// /* bind function */
// int Return5() { return 5; }
// tthread::utility::Callback<int(void)> func_cb = tthread::Bind(&Return5);
// LOG(INFO) << func_cb.Run(); // Prints 5.
//
// void PrintHi() { LOG(INFO) << "hi."; }
// tthread::utility::Closure void_func_cb = tthread::Bind(&PrintHi);
// void_func_cb.Run(); // Prints: hi.
//
// /* bind method of reference-counted class */
// class Ref : public tthread::RefCountedThreadSafe<Ref> {
// public:
// int Foo() { return 3; }
// void PrintBye() { LOG(INFO) << "bye."; }
// };
// tthread::ScopedRefPtr<Ref> ref = new Ref();
// tthread::utility::Callback<int(void)> ref_cb = tthread::Bind(&Ref::Foo, ref.get());
// LOG(INFO) << ref_cb.Run(); // Prints out 3.
//
// tthread::utility::Closure void_ref_cb = tthread::Bind(&Ref::PrintBye, ref.get());
// void_ref_cb.Run(); // Prints: bye.
//
// /* bind method
// *
// * WARNING: Must be sure object's lifecycle is long enough to run its method.
// */
// class NoRef {
// public:
// int Foo() { return 4; }
// void PrintWhy() { LOG(INFO) << "why???"; }
// };
// NoRef no_ref;
// tthread::utility::Callback<int(void)> no_ref_cb =
// tthread::Bind(&NoRef::Foo, tthread::Unretained(&no_ref));
// LOG(INFO) << ref_cb.Run(); // Prints out 4.
//
// tthread::utility::Closure void_no_ref_cb =
// tthread::Bind(&NoRef::PrintWhy, tthread::Unretained(&no_ref));
// void_no_ref_cb.Run(); // Prints: why???
//
// /* bind reference */
// int Identity(int n) { return n; }
// int value = 1;
// tthread::utility::Callback<int(void)> bound_copy_cb = tthread::Bind(&Identity, value);
// tthread::utility::Callback<int(void)> bound_ref_cb =
// tthread::Bind(&Identity, tthread::ConstRef(value));
// LOG(INFO) << bound_copy_cb.Run(); // Prints 1.
// LOG(INFO) << bound_ref_cb.Run(); // Prints 1.
// value = 2;
// LOG(INFO) << bound_copy_cb.Run(); // Prints 1.
// LOG(INFO) << bound_ref_cb.Run(); // Prints 2.
//
// /* curry func */
// int Sum(int a, int b, int c) {
// return a + b + c;
// }
// tthread::utility::Callback<int(int, int)> sum3_cb = tthread::Bind(&Sum, 3);
// LOG(INFO) << sum3_cb.Run(4, 5); // Prints 12.
//
// tthread::utility::Callback<int(int)> sum7_cb = tthread::Bind(&Sum, 3, 4);
// LOG(INFO) << sum7_cb.Run(10); // Prints 17.
namespace tthread {
namespace utility {
template <typename Sig>
class Callback;
namespace internal {
template <typename Runnable, typename RunType, typename BoundArgsType>
struct BindState;
} // namespace internal
template <typename R>
class Callback<R(void)> : public internal::CallbackBase {
public:
typedef R(RunType)();
Callback() : CallbackBase(NULL) { }
template <typename Runnable, typename RunType, typename BoundArgsType>
Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
: CallbackBase(bind_state) {
PolymorphicInvoke invoke_func =
&internal::BindState<Runnable, RunType, BoundArgsType>
::InvokerType::Run;
polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
}
bool Equals(const Callback& other) const {
return CallbackBase::Equals(other);
}
R Run() const {
PolymorphicInvoke f =
reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
return f(bind_state_.get());
}
private:
typedef R(*PolymorphicInvoke)(
internal::BindStateBase*);
};
template <typename R, typename A1>
class Callback<R(A1)> : public internal::CallbackBase {
public:
typedef R(RunType)(A1);
Callback() : CallbackBase(NULL) { }
template <typename Runnable, typename RunType, typename BoundArgsType>
Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
: CallbackBase(bind_state) {
PolymorphicInvoke invoke_func =
&internal::BindState<Runnable, RunType, BoundArgsType>
::InvokerType::Run;
polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
}
bool Equals(const Callback& other) const {
return CallbackBase::Equals(other);
}
R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1) const {
PolymorphicInvoke f =
reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
return f(bind_state_.get(), internal::CallbackForward(a1));
}
private:
typedef R(*PolymorphicInvoke)(
internal::BindStateBase*,
typename internal::CallbackParamTraits<A1>::ForwardType);
};
template <typename R, typename A1, typename A2>
class Callback<R(A1, A2)> : public internal::CallbackBase {
public:
typedef R(RunType)(A1, A2);
Callback() : CallbackBase(NULL) { }
template <typename Runnable, typename RunType, typename BoundArgsType>
Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
: CallbackBase(bind_state) {
PolymorphicInvoke invoke_func =
&internal::BindState<Runnable, RunType, BoundArgsType>
::InvokerType::Run;
polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
}
bool Equals(const Callback& other) const {
return CallbackBase::Equals(other);
}
R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1,
typename internal::CallbackParamTraits<A2>::ForwardType a2) const {
PolymorphicInvoke f =
reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
return f(bind_state_.get(), internal::CallbackForward(a1),
internal::CallbackForward(a2));
}
private:
typedef R(*PolymorphicInvoke)(
internal::BindStateBase*,
typename internal::CallbackParamTraits<A1>::ForwardType,
typename internal::CallbackParamTraits<A2>::ForwardType);
};
template <typename R, typename A1, typename A2, typename A3>
class Callback<R(A1, A2, A3)> : public internal::CallbackBase {
public:
typedef R(RunType)(A1, A2, A3);
Callback() : CallbackBase(NULL) { }
template <typename Runnable, typename RunType, typename BoundArgsType>
Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
: CallbackBase(bind_state) {
PolymorphicInvoke invoke_func =
&internal::BindState<Runnable, RunType, BoundArgsType>
::InvokerType::Run;
polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
}
bool Equals(const Callback& other) const {
return CallbackBase::Equals(other);
}
R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1,
typename internal::CallbackParamTraits<A2>::ForwardType a2,
typename internal::CallbackParamTraits<A3>::ForwardType a3) const {
PolymorphicInvoke f =
reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
return f(bind_state_.get(), internal::CallbackForward(a1),
internal::CallbackForward(a2),
internal::CallbackForward(a3));
}
private:
typedef R(*PolymorphicInvoke)(
internal::BindStateBase*,
typename internal::CallbackParamTraits<A1>::ForwardType,
typename internal::CallbackParamTraits<A2>::ForwardType,
typename internal::CallbackParamTraits<A3>::ForwardType);
};
template <typename R, typename A1, typename A2, typename A3, typename A4>
class Callback<R(A1, A2, A3, A4)> : public internal::CallbackBase {
public:
typedef R(RunType)(A1, A2, A3, A4);
Callback() : CallbackBase(NULL) { }
template <typename Runnable, typename RunType, typename BoundArgsType>
Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
: CallbackBase(bind_state) {
PolymorphicInvoke invoke_func =
&internal::BindState<Runnable, RunType, BoundArgsType>
::InvokerType::Run;
polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
}
bool Equals(const Callback& other) const {
return CallbackBase::Equals(other);
}
R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1,
typename internal::CallbackParamTraits<A2>::ForwardType a2,
typename internal::CallbackParamTraits<A3>::ForwardType a3,
typename internal::CallbackParamTraits<A4>::ForwardType a4) const {
PolymorphicInvoke f =
reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
return f(bind_state_.get(), internal::CallbackForward(a1),
internal::CallbackForward(a2),
internal::CallbackForward(a3),
internal::CallbackForward(a4));
}
private:
typedef R(*PolymorphicInvoke)(
internal::BindStateBase*,
typename internal::CallbackParamTraits<A1>::ForwardType,
typename internal::CallbackParamTraits<A2>::ForwardType,
typename internal::CallbackParamTraits<A3>::ForwardType,
typename internal::CallbackParamTraits<A4>::ForwardType);
};
template <typename R, typename A1, typename A2, typename A3, typename A4,
typename A5>
class Callback<R(A1, A2, A3, A4, A5)> : public internal::CallbackBase {
public:
typedef R(RunType)(A1, A2, A3, A4, A5);
Callback() : CallbackBase(NULL) { }
template <typename Runnable, typename RunType, typename BoundArgsType>
Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
: CallbackBase(bind_state) {
PolymorphicInvoke invoke_func =
&internal::BindState<Runnable, RunType, BoundArgsType>
::InvokerType::Run;
polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
}
bool Equals(const Callback& other) const {
return CallbackBase::Equals(other);
}
R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1,
typename internal::CallbackParamTraits<A2>::ForwardType a2,
typename internal::CallbackParamTraits<A3>::ForwardType a3,
typename internal::CallbackParamTraits<A4>::ForwardType a4,
typename internal::CallbackParamTraits<A5>::ForwardType a5) const {
PolymorphicInvoke f =
reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
return f(bind_state_.get(), internal::CallbackForward(a1),
internal::CallbackForward(a2),
internal::CallbackForward(a3),
internal::CallbackForward(a4),
internal::CallbackForward(a5));
}
private:
typedef R(*PolymorphicInvoke)(
internal::BindStateBase*,
typename internal::CallbackParamTraits<A1>::ForwardType,
typename internal::CallbackParamTraits<A2>::ForwardType,
typename internal::CallbackParamTraits<A3>::ForwardType,
typename internal::CallbackParamTraits<A4>::ForwardType,
typename internal::CallbackParamTraits<A5>::ForwardType);
};
template <typename R, typename A1, typename A2, typename A3, typename A4,
typename A5, typename A6>
class Callback<R(A1, A2, A3, A4, A5, A6)> : public internal::CallbackBase {
public:
typedef R(RunType)(A1, A2, A3, A4, A5, A6);
Callback() : CallbackBase(NULL) { }
template <typename Runnable, typename RunType, typename BoundArgsType>
Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
: CallbackBase(bind_state) {
PolymorphicInvoke invoke_func =
&internal::BindState<Runnable, RunType, BoundArgsType>
::InvokerType::Run;
polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
}
bool Equals(const Callback& other) const {
return CallbackBase::Equals(other);
}
R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1,
typename internal::CallbackParamTraits<A2>::ForwardType a2,
typename internal::CallbackParamTraits<A3>::ForwardType a3,
typename internal::CallbackParamTraits<A4>::ForwardType a4,
typename internal::CallbackParamTraits<A5>::ForwardType a5,
typename internal::CallbackParamTraits<A6>::ForwardType a6) const {
PolymorphicInvoke f =
reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
return f(bind_state_.get(), internal::CallbackForward(a1),
internal::CallbackForward(a2),
internal::CallbackForward(a3),
internal::CallbackForward(a4),
internal::CallbackForward(a5),
internal::CallbackForward(a6));
}
private:
typedef R(*PolymorphicInvoke)(
internal::BindStateBase*,
typename internal::CallbackParamTraits<A1>::ForwardType,
typename internal::CallbackParamTraits<A2>::ForwardType,
typename internal::CallbackParamTraits<A3>::ForwardType,
typename internal::CallbackParamTraits<A4>::ForwardType,
typename internal::CallbackParamTraits<A5>::ForwardType,
typename internal::CallbackParamTraits<A6>::ForwardType);
};
template <typename R, typename A1, typename A2, typename A3, typename A4,
typename A5, typename A6, typename A7>
class Callback<R(A1, A2, A3, A4, A5, A6, A7)> : public internal::CallbackBase {
public:
typedef R(RunType)(A1, A2, A3, A4, A5, A6, A7);
Callback() : CallbackBase(NULL) { }
template <typename Runnable, typename RunType, typename BoundArgsType>
Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
: CallbackBase(bind_state) {
PolymorphicInvoke invoke_func =
&internal::BindState<Runnable, RunType, BoundArgsType>
::InvokerType::Run;
polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
}
bool Equals(const Callback& other) const {
return CallbackBase::Equals(other);
}
R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1,
typename internal::CallbackParamTraits<A2>::ForwardType a2,
typename internal::CallbackParamTraits<A3>::ForwardType a3,
typename internal::CallbackParamTraits<A4>::ForwardType a4,
typename internal::CallbackParamTraits<A5>::ForwardType a5,
typename internal::CallbackParamTraits<A6>::ForwardType a6,
typename internal::CallbackParamTraits<A7>::ForwardType a7) const {
PolymorphicInvoke f =
reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
return f(bind_state_.get(), internal::CallbackForward(a1),
internal::CallbackForward(a2),
internal::CallbackForward(a3),
internal::CallbackForward(a4),
internal::CallbackForward(a5),
internal::CallbackForward(a6),
internal::CallbackForward(a7));
}
private:
typedef R(*PolymorphicInvoke)(
internal::BindStateBase*,
typename internal::CallbackParamTraits<A1>::ForwardType,
typename internal::CallbackParamTraits<A2>::ForwardType,
typename internal::CallbackParamTraits<A3>::ForwardType,
typename internal::CallbackParamTraits<A4>::ForwardType,
typename internal::CallbackParamTraits<A5>::ForwardType,
typename internal::CallbackParamTraits<A6>::ForwardType,
typename internal::CallbackParamTraits<A7>::ForwardType);
};
typedef Callback<void(void)> Closure;
} // namespace utility
} // namespace tthread
#endif // __CALLBACK_H__
| 41.423256 | 91 | 0.58528 |
50c4b5619cfddd86c5ca925d4d2c8c7c01c36157
| 97 |
go
|
Go
|
pfennig.go
|
embik/pfennig
|
91c277efb9616a9084b40095838b32b4ee274332
|
[
"MIT"
] | null | null | null |
pfennig.go
|
embik/pfennig
|
91c277efb9616a9084b40095838b32b4ee274332
|
[
"MIT"
] | null | null | null |
pfennig.go
|
embik/pfennig
|
91c277efb9616a9084b40095838b32b4ee274332
|
[
"MIT"
] | null | null | null |
package main
import (
"github.com/embik/pfennig/cmd"
)
func main() {
cmd.StartPfennig()
}
| 9.7 | 31 | 0.659794 |
0c998b3ac75eae9f76dce560875ced69e8123b01
| 6,511 |
py
|
Python
|
cmdb_v0.1/apps/detail/models.py
|
codemaker-man/projects
|
334aac28b72a7b466fba23df4db11e95df13a3ec
|
[
"MIT"
] | 1 |
2018-12-05T05:29:46.000Z
|
2018-12-05T05:29:46.000Z
|
cmdb_v0.1/apps/detail/models.py
|
codemaker-man/projects
|
334aac28b72a7b466fba23df4db11e95df13a3ec
|
[
"MIT"
] | null | null | null |
cmdb_v0.1/apps/detail/models.py
|
codemaker-man/projects
|
334aac28b72a7b466fba23df4db11e95df13a3ec
|
[
"MIT"
] | null | null | null |
# -*- coding:utf-8 -*-
from django.db import models
import django.utils.timezone as timezone
# 用户登录信息表(服务器、虚拟机)
class ConnectionInfo(models.Model):
# 用户连接相关信息
ssh_username = models.CharField(max_length=10, default='', verbose_name=u'ssh用户名', null=True)
ssh_userpasswd = models.CharField(max_length=40, default='', verbose_name=u'ssh用户密码', null=True)
ssh_hostip = models.CharField(max_length=40, default='', verbose_name=u'ssh登录的ip', null=True)
ssh_host_port = models.CharField(max_length=10, default='', verbose_name=u'ssh登录的端口', null=True)
ssh_rsa = models.CharField(max_length=64, default='', verbose_name=u'ssh私钥')
rsa_pass = models.CharField(max_length=64, default='', verbose_name=u'私钥的密钥')
# 0-登录失败,1-登录成功
ssh_status = models.IntegerField(default=0, verbose_name=u'用户连接状态,0-登录失败,1-登录成功')
# 1-rsa登录,2-dsa登录,3-普通用户_rsa登录,4-docker成功,5-docker无法登录
ssh_type = models.IntegerField(default=0, verbose_name=u'用户连接类型, 1-rsa登录,2-dsa登录,'
u'3-ssh_rsa登录,4-docker成功,5-docker无法登录')
# 唯一对象标示
sn_key = models.CharField(max_length=256, verbose_name=u"唯一设备ID", default="")
class Meta:
verbose_name = u'用户登录信息表'
verbose_name_plural = verbose_name
db_table = "connectioninfo"
#用户登录信息表(交换机、网络设备)
class NetConnectionInfo(models.Model):
tel_username = models.CharField(max_length=10, default='', verbose_name=u'用户名', null=True)
tel_userpasswd = models.CharField(max_length=40, default='', verbose_name=u'设备用户密码', null=True)
tel_enpasswd = models.CharField(max_length=40, default='', verbose_name=u'设备超级用户密码', null=True)
tel_host_port = models.CharField(max_length=10, default='', verbose_name=u'设备登录的端口', null=True)
tel_hostip = models.CharField(max_length=40, default='', verbose_name=u'设备登录的ip', null=True)
# 0-登录失败,1-登录成功
tel_status = models.IntegerField(default=0, verbose_name=u'用户连接状态,0-登录失败,1-登录成功')
tel_type = models.IntegerField(default=0, verbose_name=u'用户连接类型, 1-普通用户可登录,2-超级用户可登录')
# 唯一对象标示
sn_key = models.CharField(max_length=256, verbose_name=u"唯一设备ID", default="")
dev_info = models.ForeignKey('NetWorkInfo')
class Meta:
verbose_name = u'网络设备用户登录信息'
verbose_name_plural = verbose_name
db_table = "netconnectioninfo"
# 机柜的信息
class CabinetInfo(models.Model):
cab_name = models.CharField(max_length=10, verbose_name=u'机柜编号')
# 1-10分别代表1~10层
cab_lever = models.CharField(max_length=2, verbose_name=u'机器U数,1-10分别代表1~10层')
class Meta:
verbose_name = u'机柜信息表'
verbose_name_plural = verbose_name
db_table = "cabinetinfo"
# 物理服务器信息
class PhysicalServerInfo(models.Model):
# server_name = models.CharField(max_length=15, verbose_name=u'服务器名')
server_ip = models.CharField(max_length=40, verbose_name=u'服务器IP')
# 机器的类型 dell or other?
machine_brand = models.CharField(max_length=60, default='--', verbose_name=u'服务器品牌')
# 机器的类型
# machine_type = models.IntegerField(default=0, verbose_name=u'服务器,0-物理服务器,1-虚拟服务器,2-')
system_ver = models.CharField(max_length=30, default='', verbose_name=u'操作系统版本')
sys_hostname = models.CharField(max_length=15, verbose_name=u'操作系统主机名')
mac = models.CharField(max_length=512, default='', verbose_name=u'MAC地址')
sn = models.CharField(max_length=256, verbose_name=u'SN-主机的唯一标识', default='')
vir_type = models.CharField(max_length=2, verbose_name=u'宿主机类型', default='')
# 物理服务器关联的机柜
ser_cabin = models.ForeignKey('CabinetInfo')
# 用户登录系统信息
conn_phy = models.ForeignKey('ConnectionInfo')
class Meta:
verbose_name = u'物理服务器信息表'
verbose_name_plural = verbose_name
db_table = "physicalserverinfo"
# 虚拟设备信息
class VirtualServerInfo(models.Model):
# server_name = models.CharField(max_length=15, verbose_name=u'服务器名')
server_ip = models.CharField(max_length=40, verbose_name=u'服务器IP')
# 机器的类型 0=kvm,2=虚拟资产,3=网络设备 0=其他类型(未知)
server_type = models.CharField(max_length=80, default='', verbose_name=u'服务器类型:kvm,Vmware,Docker,others')
system_ver = models.CharField(max_length=30, default='', verbose_name=u'操作系统版本')
sys_hostname = models.CharField(max_length=15, verbose_name=u'操作系统主机名')
mac = models.CharField(max_length=512, default='', verbose_name=u'MAC地址')
sn = models.CharField(max_length=256, verbose_name=u'SN-主机的唯一标识', default='')
# 虚拟设备关联的物理服务器
vir_phy = models.ForeignKey('PhysicalServerInfo')
# 用户登录系统信息
conn_vir = models.ForeignKey('ConnectionInfo')
class Meta:
verbose_name = u'虚拟设备表'
verbose_name_plural = verbose_name
db_table = "virtualserverinfo"
# 网络设备表
class NetWorkInfo(models.Model):
host_ip = models.CharField(max_length=40, verbose_name=u'网络设备ip')
host_name = models.CharField(max_length=10, verbose_name=u'网络设备名')
sn = models.CharField(max_length=256, verbose_name=u"SN-设备的唯一标识", default="")
# 网络设备所在的机柜
net_cab = models.ForeignKey('CabinetInfo')
class Meta:
verbose_name = u'网络设备表'
verbose_name_plural = verbose_name
db_table = "networkinfo"
class OtherMachineInfo(models.Model):
ip = models.CharField(max_length=40, verbose_name=u'设备ip')
sn_key = models.CharField(max_length=256, verbose_name=u'设备的唯一标识')
machine_name = models.CharField(max_length=20, verbose_name=u'设备名称')
remark = models.TextField(default='', verbose_name=u'备注')
reson_str = models.CharField(max_length=128,verbose_name=u"归纳原因",default='')
# 关联的机柜
oth_cab = models.ForeignKey('CabinetInfo')
class Meta:
verbose_name = u'其它设备表'
verbose_name_plural = verbose_name
db_table = 'othermachineinfo'
class StatisticsRecord(models.Model):
datatime = models.DateTimeField(verbose_name=u"更新时间",default=timezone.now().strftime('%Y-%m-%d'))
all_count = models.IntegerField(verbose_name=u"所有设备数量",default=0)
pyh_count = models.IntegerField(verbose_name=u"物理设备数量",default=0)
net_count = models.IntegerField(verbose_name=u"网络设备数量",default=0)
other_count = models.IntegerField(verbose_name=u"其他设备数量",default=0)
kvm_count = models.IntegerField(verbose_name=u"KVM设备数量",default=0)
docker_count = models.IntegerField(verbose_name=u"Docker设备数量",default=0)
vmx_count = models.IntegerField(verbose_name=u"VMX设备数量",default=0)
class Meta:
verbose_name = u'扫描后的汇总硬件统计信息'
verbose_name_plural = verbose_name
db_table = 'statisticsrecord'
| 42.835526 | 109 | 0.714176 |
93c3a4b565cb03debef83384b043256fc0d30706
| 27,225 |
rs
|
Rust
|
frame/oracle/src/tests.rs
|
ArturoFinance/composable
|
8ea2468b3ea955cf12dc98a0fbd4979788c67864
|
[
"Unlicense"
] | null | null | null |
frame/oracle/src/tests.rs
|
ArturoFinance/composable
|
8ea2468b3ea955cf12dc98a0fbd4979788c67864
|
[
"Unlicense"
] | null | null | null |
frame/oracle/src/tests.rs
|
ArturoFinance/composable
|
8ea2468b3ea955cf12dc98a0fbd4979788c67864
|
[
"Unlicense"
] | null | null | null |
use crate::{
mock::{AccountId, Call, Extrinsic, *},
AssetInfo, Error, PrePrice, Price, Withdraw, *,
};
use codec::Decode;
use composable_traits::defi::CurrencyPair;
use frame_support::{
assert_noop, assert_ok,
traits::{Currency, OnInitialize},
BoundedVec,
};
use pallet_balances::Error as BalancesError;
use parking_lot::RwLock;
use sp_core::offchain::{testing, OffchainDbExt, OffchainWorkerExt, TransactionPoolExt};
use sp_io::TestExternalities;
use sp_keystore::{testing::KeyStore, KeystoreExt, SyncCryptoStore};
use sp_runtime::{
traits::{BadOrigin, Zero},
FixedPointNumber, FixedU128, Percent, RuntimeAppPublic,
};
use std::sync::Arc;
#[test]
fn add_asset_and_info() {
new_test_ext().execute_with(|| {
const ASSET_ID: u128 = 1;
const MIN_ANSWERS: u32 = 3;
const MAX_ANSWERS: u32 = 5;
const THRESHOLD: Percent = Percent::from_percent(80);
const BLOCK_INTERVAL: u64 = 5;
const REWARD: u64 = 5;
const SLASH: u64 = 5;
// passes
let account_2 = get_account_2();
assert_ok!(Oracle::add_asset_and_info(
Origin::signed(account_2),
ASSET_ID,
THRESHOLD,
MIN_ANSWERS,
MAX_ANSWERS,
BLOCK_INTERVAL,
REWARD,
SLASH
));
// does not increment if exists
assert_ok!(Oracle::add_asset_and_info(
Origin::signed(account_2),
ASSET_ID,
THRESHOLD,
MIN_ANSWERS,
MAX_ANSWERS,
BLOCK_INTERVAL,
REWARD,
SLASH
));
assert_eq!(Oracle::assets_count(), 1);
assert_ok!(Oracle::add_asset_and_info(
Origin::signed(account_2),
ASSET_ID + 1,
THRESHOLD,
MIN_ANSWERS,
MAX_ANSWERS,
BLOCK_INTERVAL,
REWARD,
SLASH
));
let asset_info = AssetInfo {
threshold: THRESHOLD,
min_answers: MIN_ANSWERS,
max_answers: MAX_ANSWERS,
block_interval: BLOCK_INTERVAL,
reward: REWARD,
slash: SLASH,
};
// id now activated and count incremented
assert_eq!(Oracle::asset_info(1), Some(asset_info));
assert_eq!(Oracle::assets_count(), 2);
// fails with non permission
let account_1 = get_account_1();
assert_noop!(
Oracle::add_asset_and_info(
Origin::signed(account_1),
ASSET_ID,
THRESHOLD,
MAX_ANSWERS,
MAX_ANSWERS,
BLOCK_INTERVAL,
REWARD,
SLASH
),
BadOrigin
);
assert_noop!(
Oracle::add_asset_and_info(
Origin::signed(account_2),
ASSET_ID,
THRESHOLD,
MAX_ANSWERS,
MIN_ANSWERS,
BLOCK_INTERVAL,
REWARD,
SLASH
),
Error::<Test>::MaxAnswersLessThanMinAnswers
);
assert_noop!(
Oracle::add_asset_and_info(
Origin::signed(account_2),
ASSET_ID,
Percent::from_percent(100),
MIN_ANSWERS,
MAX_ANSWERS,
BLOCK_INTERVAL,
REWARD,
SLASH
),
Error::<Test>::ExceedThreshold
);
assert_noop!(
Oracle::add_asset_and_info(
Origin::signed(account_2),
ASSET_ID,
THRESHOLD,
MIN_ANSWERS,
MAX_ANSWERS + 1,
BLOCK_INTERVAL,
REWARD,
SLASH
),
Error::<Test>::ExceedMaxAnswers
);
assert_noop!(
Oracle::add_asset_and_info(
Origin::signed(account_2),
ASSET_ID,
THRESHOLD,
0,
MAX_ANSWERS,
BLOCK_INTERVAL,
REWARD,
SLASH
),
Error::<Test>::InvalidMinAnswers
);
assert_noop!(
Oracle::add_asset_and_info(
Origin::signed(account_2),
ASSET_ID + 2,
THRESHOLD,
MIN_ANSWERS,
MAX_ANSWERS,
BLOCK_INTERVAL,
REWARD,
SLASH
),
Error::<Test>::ExceedAssetsCount
);
assert_noop!(
Oracle::add_asset_and_info(
Origin::signed(account_2),
ASSET_ID,
THRESHOLD,
MIN_ANSWERS,
MAX_ANSWERS,
BLOCK_INTERVAL - 4,
REWARD,
SLASH
),
Error::<Test>::BlockIntervalLength
);
});
}
#[test]
fn set_signer() {
new_test_ext().execute_with(|| {
let account_1 = get_account_1();
let account_2 = get_account_2();
let account_3 = get_account_3();
let account_4 = get_account_4();
let account_5 = get_account_5();
assert_ok!(Oracle::set_signer(Origin::signed(account_2), account_1));
assert_eq!(Oracle::controller_to_signer(account_2), Some(account_1));
assert_eq!(Oracle::signer_to_controller(account_1), Some(account_2));
assert_ok!(Oracle::set_signer(Origin::signed(account_1), account_5));
assert_eq!(Oracle::controller_to_signer(account_1), Some(account_5));
assert_eq!(Oracle::signer_to_controller(account_5), Some(account_1));
assert_noop!(
Oracle::set_signer(Origin::signed(account_3), account_4),
BalancesError::<Test>::InsufficientBalance
);
assert_noop!(
Oracle::set_signer(Origin::signed(account_4), account_1),
Error::<Test>::SignerUsed
);
assert_noop!(
Oracle::set_signer(Origin::signed(account_1), account_2),
Error::<Test>::ControllerUsed
);
});
}
#[test]
fn add_stake() {
new_test_ext().execute_with(|| {
let account_1 = get_account_1();
let account_2 = get_account_2();
// fails no controller set
assert_noop!(Oracle::add_stake(Origin::signed(account_1), 50), Error::<Test>::UnsetSigner);
assert_ok!(Oracle::set_signer(Origin::signed(account_1), account_2));
assert_eq!(Balances::free_balance(account_2), 100);
assert_eq!(Balances::free_balance(account_1), 99);
assert_ok!(Oracle::add_stake(Origin::signed(account_1), 50));
assert_eq!(Balances::free_balance(account_1), 49);
assert_eq!(Balances::total_balance(&account_1), 49);
// funds were transferred to signer and locked
assert_eq!(Balances::free_balance(account_2), 100);
assert_eq!(Balances::total_balance(&account_2), 151);
assert_eq!(Oracle::oracle_stake(account_2), Some(51));
assert_eq!(Oracle::oracle_stake(account_1), None);
assert_ok!(Oracle::add_stake(Origin::signed(account_1), 39));
assert_eq!(Balances::free_balance(account_1), 10);
assert_eq!(Balances::total_balance(&account_1), 10);
assert_eq!(Balances::free_balance(account_2), 100);
assert_eq!(Balances::total_balance(&account_2), 190);
assert_eq!(Oracle::oracle_stake(account_2), Some(90));
assert_eq!(Oracle::oracle_stake(account_1), None);
assert_noop!(
Oracle::add_stake(Origin::signed(account_1), 10),
BalancesError::<Test>::KeepAlive
);
});
}
#[test]
fn remove_and_reclaim_stake() {
new_test_ext().execute_with(|| {
let account_1 = get_account_1();
let account_2 = get_account_2();
let account_3 = get_account_3();
assert_ok!(Oracle::set_signer(Origin::signed(account_1), account_2));
assert_ok!(Oracle::add_stake(Origin::signed(account_1), 50));
assert_noop!(Oracle::reclaim_stake(Origin::signed(account_1)), Error::<Test>::Unknown);
assert_ok!(Oracle::remove_stake(Origin::signed(account_1)));
let withdrawal = Withdraw { stake: 51, unlock_block: 1 };
assert_eq!(Oracle::declared_withdraws(account_2), Some(withdrawal));
assert_eq!(Oracle::oracle_stake(account_2), None);
assert_noop!(Oracle::remove_stake(Origin::signed(account_1)), Error::<Test>::NoStake);
assert_noop!(Oracle::reclaim_stake(Origin::signed(account_1)), Error::<Test>::StakeLocked);
System::set_block_number(2);
assert_ok!(Oracle::reclaim_stake(Origin::signed(account_1)));
// everyone gets their funds back
assert_eq!(Balances::free_balance(account_1), 100);
assert_eq!(Balances::total_balance(&account_1), 100);
assert_eq!(Balances::free_balance(account_2), 100);
assert_eq!(Balances::total_balance(&account_2), 100);
// signer controller pruned
assert_eq!(Oracle::controller_to_signer(account_1), None);
assert_eq!(Oracle::signer_to_controller(account_2), None);
assert_noop!(Oracle::reclaim_stake(Origin::signed(account_3)), Error::<Test>::UnsetSigner);
});
}
#[test]
fn add_price() {
new_test_ext().execute_with(|| {
let account_1 = get_account_1();
let account_2 = get_account_2();
let account_4 = get_account_4();
let account_5 = get_account_5();
assert_ok!(Oracle::add_asset_and_info(
Origin::signed(account_2),
0,
Percent::from_percent(80),
3,
3,
5,
5,
5
));
System::set_block_number(6);
// fails no stake
assert_noop!(
Oracle::submit_price(Origin::signed(account_1), 100_u128, 0_u128),
Error::<Test>::NotEnoughStake
);
assert_ok!(Oracle::set_signer(Origin::signed(account_2), account_1));
assert_ok!(Oracle::set_signer(Origin::signed(account_1), account_2));
assert_ok!(Oracle::set_signer(Origin::signed(account_5), account_4));
assert_ok!(Oracle::set_signer(Origin::signed(account_4), account_5));
assert_ok!(Oracle::add_stake(Origin::signed(account_1), 50));
assert_ok!(Oracle::add_stake(Origin::signed(account_2), 50));
assert_ok!(Oracle::add_stake(Origin::signed(account_4), 50));
assert_ok!(Oracle::add_stake(Origin::signed(account_5), 50));
assert_ok!(Oracle::submit_price(Origin::signed(account_1), 100_u128, 0_u128));
assert_ok!(Oracle::submit_price(Origin::signed(account_2), 100_u128, 0_u128));
assert_noop!(
Oracle::submit_price(Origin::signed(account_2), 100_u128, 0_u128),
Error::<Test>::AlreadySubmitted
);
assert_ok!(Oracle::submit_price(Origin::signed(account_4), 100_u128, 0_u128));
assert_eq!(Oracle::answer_in_transit(account_1), Some(5));
assert_eq!(Oracle::answer_in_transit(account_2), Some(5));
assert_eq!(Oracle::answer_in_transit(account_4), Some(5));
assert_noop!(
Oracle::submit_price(Origin::signed(account_5), 100_u128, 0_u128),
Error::<Test>::MaxPrices
);
let price = PrePrice { price: 100_u128, block: 6, who: account_1 };
let price2 = PrePrice { price: 100_u128, block: 6, who: account_2 };
let price4 = PrePrice { price: 100_u128, block: 6, who: account_4 };
assert_eq!(Oracle::pre_prices(0), vec![price, price2, price4]);
System::set_block_number(2);
Oracle::on_initialize(2);
// fails price not requested
assert_noop!(
Oracle::submit_price(Origin::signed(account_1), 100_u128, 0_u128),
Error::<Test>::PriceNotRequested
);
// non existent asset_id
assert_noop!(
Oracle::submit_price(Origin::signed(account_1), 100_u128, 10_u128),
Error::<Test>::PriceNotRequested
);
});
}
#[test]
fn medianize_price() {
new_test_ext().execute_with(|| {
let account_1 = get_account_1();
// should not panic
Oracle::get_median_price(&Oracle::pre_prices(0));
for i in 0..3 {
let price = i as u128 + 100_u128;
add_price_storage(price, 0, account_1, 0);
}
let price = Oracle::get_median_price(&Oracle::pre_prices(0));
assert_eq!(price, Some(101));
});
}
#[test]
#[should_panic = "No `keystore` associated for the current context!"]
fn check_request() {
new_test_ext().execute_with(|| {
let account_2 = get_account_2();
assert_ok!(Oracle::add_asset_and_info(
Origin::signed(account_2),
0,
Percent::from_percent(80),
3,
5,
5,
5,
5
));
System::set_block_number(6);
Oracle::check_requests();
});
}
#[test]
fn not_check_request() {
new_test_ext().execute_with(|| {
Oracle::check_requests();
});
}
#[test]
fn is_requested() {
new_test_ext().execute_with(|| {
let account_2 = get_account_2();
assert_ok!(Oracle::add_asset_and_info(
Origin::signed(account_2),
0,
Percent::from_percent(80),
3,
5,
5,
5,
5
));
System::set_block_number(6);
assert!(Oracle::is_requested(&0));
let price = Price { price: 0, block: 6 };
Prices::<Test>::insert(0, price);
assert!(!Oracle::is_requested(&0));
System::set_block_number(11);
assert!(!Oracle::is_requested(&0));
});
}
#[test]
fn test_payout_slash() {
new_test_ext().execute_with(|| {
let account_1 = get_account_1();
let account_2 = get_account_2();
let account_3 = get_account_3();
let account_4 = get_account_4();
let account_5 = get_account_5();
assert_ok!(Oracle::set_signer(Origin::signed(account_5), account_2));
let one = PrePrice { price: 79, block: 0, who: account_1 };
let two = PrePrice { price: 100, block: 0, who: account_2 };
let three = PrePrice { price: 151, block: 0, who: account_3 };
let four = PrePrice { price: 400, block: 0, who: account_4 };
let five = PrePrice { price: 100, block: 0, who: account_5 };
let asset_info = AssetInfo {
threshold: Percent::from_percent(0),
min_answers: 0,
max_answers: 0,
block_interval: 0,
reward: 0,
slash: 0,
};
// doesn't panic when percent not set
Oracle::handle_payout(&vec![one, two, three, four, five], 100, 0, &asset_info);
assert_eq!(Balances::free_balance(account_1), 100);
assert_ok!(Oracle::add_asset_and_info(
Origin::signed(account_2),
0,
Percent::from_percent(80),
3,
5,
5,
5,
5
));
add_price_storage(79, 0, account_1, 0);
add_price_storage(100, 0, account_2, 0);
assert_eq!(Oracle::answer_in_transit(account_1), Some(5));
assert_eq!(Oracle::answer_in_transit(account_2), Some(5));
Oracle::handle_payout(
&vec![one, two, three, four, five],
100,
0,
&Oracle::asset_info(0).unwrap(),
);
assert_eq!(Oracle::answer_in_transit(account_1), Some(0));
assert_eq!(Oracle::answer_in_transit(account_2), Some(0));
// account 1 and 4 gets slashed 2 and 5 gets rewarded
assert_eq!(Balances::free_balance(account_1), 95);
// 5 gets 2's reward and its own
assert_eq!(Balances::free_balance(account_5), 109);
assert_eq!(Balances::free_balance(account_2), 100);
assert_eq!(Balances::free_balance(account_3), 0);
assert_eq!(Balances::free_balance(account_4), 95);
assert_ok!(Oracle::add_asset_and_info(
Origin::signed(account_2),
0,
Percent::from_percent(90),
3,
5,
5,
4,
5
));
Oracle::handle_payout(
&vec![one, two, three, four, five],
100,
0,
&Oracle::asset_info(0).unwrap(),
);
// account 4 gets slashed 2 5 and 1 gets rewarded
assert_eq!(Balances::free_balance(account_1), 90);
// 5 gets 2's reward and its own
assert_eq!(Balances::free_balance(account_5), 117);
assert_eq!(Balances::free_balance(account_2), 100);
assert_eq!(Balances::free_balance(account_3), 0);
assert_eq!(Balances::free_balance(account_4), 90);
});
}
#[test]
fn on_init() {
new_test_ext().execute_with(|| {
// no price fetch
Oracle::on_initialize(1);
let price = Price { price: 0, block: 0 };
assert_eq!(Oracle::prices(0), price);
// add and request oracle id
let account_2 = get_account_2();
assert_ok!(Oracle::add_asset_and_info(
Origin::signed(account_2),
0,
Percent::from_percent(80),
3,
5,
5,
5,
5
));
// set prices into storage
let account_1 = get_account_1();
for i in 0..3 {
let price = i as u128 + 100_u128;
add_price_storage(price, 0, account_1, 2);
}
Oracle::on_initialize(2);
let price = Price { price: 101, block: 2 };
assert_eq!(Oracle::prices(0), price);
// prunes state
assert_eq!(Oracle::pre_prices(0), vec![]);
// doesn't prune state if under min prices
for i in 0..2 {
let price = i as u128 + 100_u128;
add_price_storage(price, 0, account_1, 3);
}
// does not fire under min answers
Oracle::on_initialize(3);
assert_eq!(Oracle::pre_prices(0).len(), 2);
assert_eq!(Oracle::prices(0), price);
});
}
#[test]
fn historic_pricing() {
new_test_ext().execute_with(|| {
// add and request oracle id
let account_2 = get_account_2();
assert_ok!(Oracle::add_asset_and_info(
Origin::signed(account_2),
0,
Percent::from_percent(80),
3,
5,
5,
5,
5
));
let mut price_history = vec![];
do_price_update(0, 0);
assert_eq!(Oracle::price_history(0).len(), 0);
assert_eq!(Oracle::price_history(0), price_history);
do_price_update(0, 5);
let price_5 = Price { price: 101, block: 5 };
price_history = vec![price_5.clone()];
assert_eq!(Oracle::price_history(0), price_history);
assert_eq!(Oracle::price_history(0).len(), 1);
do_price_update(0, 10);
let price_10 = Price { price: 101, block: 10 };
price_history = vec![price_5.clone(), price_10.clone()];
assert_eq!(Oracle::price_history(0), price_history);
assert_eq!(Oracle::price_history(0).len(), 2);
do_price_update(0, 15);
let price_15 = Price { price: 101, block: 15 };
price_history = vec![price_5, price_10.clone(), price_15.clone()];
assert_eq!(Oracle::price_history(0), price_history);
assert_eq!(Oracle::price_history(0).len(), 3);
do_price_update(0, 20);
let price_20 = Price { price: 101, block: 20 };
price_history = vec![price_10, price_15, price_20];
assert_eq!(Oracle::price_history(0), price_history);
assert_eq!(Oracle::price_history(0).len(), 3);
});
}
#[test]
fn price_of_amount() {
new_test_ext().execute_with(|| {
let value = 100500;
let id = 42;
let amount = 10000;
let price = Price { price: value, block: System::block_number() };
Prices::<Test>::insert(id, price);
let total_price =
<Oracle as composable_traits::oracle::Oracle>::get_price(id, amount).unwrap();
assert_eq!(total_price.price, value * amount)
});
}
#[test]
fn ratio_human_case() {
new_test_ext().execute_with(|| {
let price = Price { price: 10000, block: System::block_number() };
Prices::<Test>::insert(13, price);
let price = Price { price: 100, block: System::block_number() };
Prices::<Test>::insert(42, price);
let mut pair = CurrencyPair::new(13, 42);
let ratio = <Oracle as composable_traits::oracle::Oracle>::get_ratio(pair).unwrap();
assert_eq!(ratio, FixedU128::saturating_from_integer(100));
pair.reverse();
let ratio = <Oracle as composable_traits::oracle::Oracle>::get_ratio(pair).unwrap();
assert_eq!(ratio, FixedU128::saturating_from_rational(1_u32, 100_u32));
})
}
#[test]
fn inverses() {
new_test_ext().execute_with(|| {
let price = Price { price: 1, block: System::block_number() };
Prices::<Test>::insert(13, price);
let inverse =
<Oracle as composable_traits::oracle::Oracle>::get_price_inverse(13, 1).unwrap();
assert_eq!(inverse, 1);
let price = Price { price: 1, block: System::block_number() };
Prices::<Test>::insert(13, price);
let inverse =
<Oracle as composable_traits::oracle::Oracle>::get_price_inverse(13, 2).unwrap();
assert_eq!(inverse, 2);
})
}
#[test]
fn ratio_base_is_way_less_smaller() {
new_test_ext().execute_with(|| {
let price = Price { price: 1, block: System::block_number() };
Prices::<Test>::insert(13, price);
let price = Price { price: 10_u128.pow(12), block: System::block_number() };
Prices::<Test>::insert(42, price);
let pair = CurrencyPair::new(13, 42);
let ratio = <Oracle as composable_traits::oracle::Oracle>::get_ratio(pair).unwrap();
assert_eq!(ratio, FixedU128::saturating_from_rational(1, 1000000000000_u64));
})
}
#[test]
fn get_twap() {
new_test_ext().execute_with(|| {
// add and request oracle id
let account_2 = get_account_2();
assert_ok!(Oracle::add_asset_and_info(
Origin::signed(account_2),
0,
Percent::from_percent(80),
3,
5,
5,
5,
5
));
do_price_update(0, 0);
let price_1 = Price { price: 100, block: 20 };
let price_2 = Price { price: 100, block: 20 };
let price_3 = Price { price: 120, block: 20 };
let historic_prices = [price_1, price_2, price_3].to_vec();
set_historic_prices(0, historic_prices);
let twap = Oracle::get_twap(0, vec![20, 30, 50]);
// twap should be (0.2 * 100) + (0.3 * 120) + (0.5 * 101)
assert_eq!(twap, Ok(106));
let err_twap = Oracle::get_twap(0, vec![21, 30, 50]);
assert_eq!(err_twap, Err(Error::<Test>::MustSumTo100.into()));
let err_2_twap = Oracle::get_twap(0, vec![10, 10, 10, 10, 60]);
assert_eq!(err_2_twap, Err(Error::<Test>::DepthTooLarge.into()));
});
}
#[test]
fn on_init_prune_scenerios() {
new_test_ext().execute_with(|| {
// add and request oracle id
let account_2 = get_account_2();
assert_ok!(Oracle::add_asset_and_info(
Origin::signed(account_2),
0,
Percent::from_percent(80),
3,
5,
5,
5,
5
));
// set prices into storage
let account_1 = get_account_1();
for i in 0..3 {
let price = i as u128 + 100_u128;
add_price_storage(price, 0, account_1, 0);
}
// all pruned
Oracle::on_initialize(3);
let price = Price { price: 0, block: 0 };
assert_eq!(Oracle::prices(0), price);
assert_eq!(Oracle::pre_prices(0).len(), 0);
for i in 0..5 {
let price = i as u128 + 1_u128;
add_price_storage(price, 0, account_1, 0);
}
for i in 0..3 {
let price = i as u128 + 100_u128;
add_price_storage(price, 0, account_1, 3);
}
// more than half pruned
Oracle::on_initialize(3);
let price = Price { price: 101, block: 3 };
assert_eq!(Oracle::prices(0), price);
for i in 0..5 {
let price = i as u128 + 1_u128;
add_price_storage(price, 0, account_1, 0);
}
for i in 0..2 {
let price = i as u128 + 300_u128;
add_price_storage(price, 0, account_1, 3);
}
// more than half pruned not enough for a price call, same as previous
Oracle::on_initialize(5);
let price = Price { price: 101, block: 3 };
assert_eq!(Oracle::pre_prices(0).len(), 2);
assert_eq!(Oracle::prices(0), price);
});
}
#[test]
fn on_init_over_max_answers() {
new_test_ext().execute_with(|| {
// add and request oracle id
let account_2 = get_account_2();
assert_ok!(Oracle::add_asset_and_info(
Origin::signed(account_2),
0,
Percent::from_percent(80),
1,
2,
5,
5,
5
));
// set prices into storage
let account_1 = get_account_1();
for i in 0..5 {
let price = i as u128 + 100_u128;
add_price_storage(price, 0, account_1, 0);
}
assert_eq!(Oracle::answer_in_transit(account_1), Some(25));
// all pruned
Oracle::on_initialize(0);
// price prunes all but first 2 answers, median went from 102 to 100
let price = Price { price: 100, block: 0 };
assert_eq!(Oracle::prices(0), price);
assert_eq!(Oracle::pre_prices(0).len(), 0);
assert_eq!(Oracle::answer_in_transit(account_1), Some(0));
});
}
#[test]
fn prune_old_pre_prices_edgecase() {
new_test_ext().execute_with(|| {
let asset_info = AssetInfo {
threshold: Percent::from_percent(80),
min_answers: 3,
max_answers: 5,
block_interval: 5,
reward: 5,
slash: 5,
};
Oracle::prune_old_pre_prices(&asset_info, vec![], 0);
});
}
#[test]
fn should_make_http_call_and_parse_result() {
let (mut t, _) = offchain_worker_env(|state| price_oracle_response(state, "0"));
t.execute_with(|| {
// when
let price = Oracle::fetch_price(&0).unwrap();
// then
assert_eq!(price, 15523);
});
}
#[test]
fn knows_how_to_mock_several_http_calls() {
let (mut t, _) = offchain_worker_env(|state| {
state.expect_request(testing::PendingRequest {
method: "GET".into(),
uri: "http://localhost:3001/price/0".into(),
response: Some(br#"{"0": 100}"#.to_vec()),
sent: true,
..Default::default()
});
state.expect_request(testing::PendingRequest {
method: "GET".into(),
uri: "http://localhost:3001/price/0".into(),
response: Some(br#"{"0": 200}"#.to_vec()),
sent: true,
..Default::default()
});
state.expect_request(testing::PendingRequest {
method: "GET".into(),
uri: "http://localhost:3001/price/0".into(),
response: Some(br#"{"0": 300}"#.to_vec()),
sent: true,
..Default::default()
});
});
t.execute_with(|| {
let price1 = Oracle::fetch_price(&0).unwrap();
let price2 = Oracle::fetch_price(&0).unwrap();
let price3 = Oracle::fetch_price(&0).unwrap();
assert_eq!(price1, 100);
assert_eq!(price2, 200);
assert_eq!(price3, 300);
})
}
#[test]
fn should_submit_signed_transaction_on_chain() {
let (mut t, pool_state) = offchain_worker_env(|state| price_oracle_response(state, "0"));
t.execute_with(|| {
let account_2 = get_account_2();
assert_ok!(Oracle::add_asset_and_info(
Origin::signed(account_2),
0,
Percent::from_percent(80),
3,
3,
5,
5,
5
));
// when
Oracle::fetch_price_and_send_signed(&0, Oracle::asset_info(0).unwrap()).unwrap();
// then
let tx = pool_state.write().transactions.pop().unwrap();
assert!(pool_state.read().transactions.is_empty());
let tx = Extrinsic::decode(&mut &*tx).unwrap();
assert_eq!(tx.signature.unwrap().0, 0);
assert_eq!(tx.call, Call::Oracle(crate::Call::submit_price { price: 15523, asset_id: 0 }));
});
}
#[test]
#[should_panic = "Tx already submitted"]
fn should_check_oracles_submitted_price() {
let (mut t, _) = offchain_worker_env(|state| price_oracle_response(state, "0"));
t.execute_with(|| {
let account_2 = get_account_2();
assert_ok!(Oracle::add_asset_and_info(
Origin::signed(account_2),
0,
Percent::from_percent(80),
3,
3,
5,
5,
5
));
add_price_storage(100_u128, 0, account_2, 0);
// when
Oracle::fetch_price_and_send_signed(&0, Oracle::asset_info(0).unwrap()).unwrap();
});
}
#[test]
#[should_panic = "Max answers reached"]
fn should_check_oracles_max_answer() {
let (mut t, _) = offchain_worker_env(|state| price_oracle_response(state, "0"));
let asset_info = AssetInfo {
threshold: Percent::from_percent(0),
min_answers: 0,
max_answers: 0,
block_interval: 0,
reward: 0,
slash: 0,
};
t.execute_with(|| {
Oracle::fetch_price_and_send_signed(&0, asset_info).unwrap();
});
}
#[test]
fn parse_price_works() {
let test_data = vec![
("{\"1\":6536.92}", Some(6536)),
("{\"1\":650000000}", Some(650000000)),
("{\"2\":6536}", None),
("{\"0\":\"6432\"}", None),
];
for (json, expected) in test_data {
assert_eq!(expected, Oracle::parse_price(json, "1"));
}
}
fn add_price_storage(price: u128, asset_id: u128, who: AccountId, block: u64) {
let price = PrePrice { price, block, who };
PrePrices::<Test>::mutate(asset_id, |current_prices| current_prices.try_push(price).unwrap());
AnswerInTransit::<Test>::mutate(who, |transit| {
*transit = Some(transit.unwrap_or_else(Zero::zero) + 5)
});
}
fn do_price_update(asset_id: u128, block: u64) {
let account_1 = get_account_1();
for i in 0..3 {
let price = i as u128 + 100_u128;
add_price_storage(price, asset_id, account_1, block);
}
System::set_block_number(block);
Oracle::on_initialize(block);
let price = Price { price: 101, block };
assert_eq!(Oracle::prices(asset_id), price);
}
fn set_historic_prices(asset_id: u128, historic_prices: Vec<Price<u128, u64>>) {
PriceHistory::<Test>::insert(asset_id, BoundedVec::try_from(historic_prices).unwrap());
}
fn price_oracle_response(state: &mut testing::OffchainState, price_id: &str) {
let base: String = "http://localhost:3001/price/".to_owned();
let url = base + price_id;
state.expect_request(testing::PendingRequest {
method: "GET".into(),
uri: url,
response: Some(br#"{"0": 15523}"#.to_vec()),
sent: true,
..Default::default()
});
}
fn offchain_worker_env(
state_updater: fn(&mut testing::OffchainState),
) -> (TestExternalities, Arc<RwLock<testing::PoolState>>) {
const PHRASE: &str =
"news slush supreme milk chapter athlete soap sausage put clutch what kitten";
let (offchain, offchain_state) = testing::TestOffchainExt::new();
let (pool, pool_state) = testing::TestTransactionPoolExt::new();
let keystore = KeyStore::new();
SyncCryptoStore::sr25519_generate_new(
&keystore,
crate::crypto::Public::ID,
Some(&format!("{}/hunter1", PHRASE)),
)
.unwrap();
let mut t = sp_io::TestExternalities::default();
t.register_extension(OffchainDbExt::new(offchain.clone()));
t.register_extension(OffchainWorkerExt::new(offchain));
t.register_extension(TransactionPoolExt::new(pool));
t.register_extension(KeystoreExt(Arc::new(keystore)));
state_updater(&mut offchain_state.write());
(t, pool_state)
}
| 26.177885 | 95 | 0.678678 |
21fedb507f0cd3599fc7edade4f45774fdd26d49
| 6,906 |
html
|
HTML
|
14_student_account.html
|
debug314/rsitm-web
|
0d4983227006709dfc8b0f98e3d9267abcc20eb7
|
[
"BSD-3-Clause"
] | null | null | null |
14_student_account.html
|
debug314/rsitm-web
|
0d4983227006709dfc8b0f98e3d9267abcc20eb7
|
[
"BSD-3-Clause"
] | null | null | null |
14_student_account.html
|
debug314/rsitm-web
|
0d4983227006709dfc8b0f98e3d9267abcc20eb7
|
[
"BSD-3-Clause"
] | null | null | null |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Student's Site | Articles</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/reset.css" type="text/css" media="all">
<link rel="stylesheet" href="css/style.css" type="text/css" media="all">
<script type="text/javascript" src="js/jquery-1.4.2.min.js" ></script>
<script type="text/javascript" src="js/cufon-yui.js"></script>
<script type="text/javascript" src="js/cufon-replace.js"></script>
<script type="text/javascript" src="js/Myriad_Pro_300.font.js"></script>
<script type="text/javascript" src="js/Myriad_Pro_400.font.js"></script>
<script type="text/javascript" src="js/script.js"></script>
<!--[if lt IE 7]>
<link rel="stylesheet" href="css/ie6.css" type="text/css" media="screen">
<script type="text/javascript" src="js/ie_png.js"></script>
<script type="text/javascript">ie_png.fix('.png, footer, header nav ul li a, .nav-bg, .list li img');</script>
<![endif]-->
<!--[if lt IE 9]><script type="text/javascript" src="js/html5.js"></script><![endif]-->
</head>
<body id="page2">
<!-- START PAGE SOURCE -->
<div class="wrap">
<header>
<div class="container">
<h1><a href="#">Student's site</a></h1>
<nav>
<ul>
<li><a href="1_index.html" class="m1">Home Page</a></li>
<li ><a href="2_about-us.html" class="m2">About Us</a></li>
<li><a href="3_courses.html" class="m3">Courses</a></li>
<li><a href="#" class="m4">gallery</a></li>
<li class="last"><a href="19_contact-us(slt).html" class="m5">Contact us</a></li>
</ul>
</nav>
</div>
</header>
<div class="container">
<aside>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li><p></p>
<span class="txt1">RisingSUN Institute of Technology and Management is recognised by:-</span>
<ul>
<li>
<p></p>
</li>
<li>
<p>University Grants Commission(UGC)</p>
</li>
<li>
<p>All India Council for Technical Education (AICTE)</p>
</li>
<li>
<p>Distance Education Council (DEC)</p>
</li>
<li> </li>
<li> </li>
<li> </li>
<li></li>
<li></li>
<li></li>
</ul>
</li>
</ul>
<p> </p>
<h2>Fresh <span>News</span></h2>
<ul class="news">
<li><strong>August 30, 2013</strong>
<h4><a href="3_courses.html">Admissions now Open</a></h4>
Admission for the streams MCA, MSc(IT), MSc(MM) is now open. Apply Now !</li>
<li><strong>August 14, 2013</strong>
<h4><a href="3_courses.html">Launch of MSc(MM)</a></h4>
We are proud to announce the launch of Master of Science in Multimedia programme.</li>
<li><strong>August 10, 2013</strong>
<h4><a href="20_contact-us(jdv).html">RisingSUN now in Jadavpur</a></h4>
We are proud to announce the inauguration of our Jadavpur branch.</li>
<li></li>
</ul>
</aside>
<section id="content">
<div class="inside">
<table width="600" height="439" border="5" cellpadding="5" cellspacing="0">
<tr>
<td width="304" height="30">Welcome </td>
<td width="262"><div align="left">
<label for="name"></label>
<input type="text" name="name" id="name" size="40">
</div></td>
</tr>
<tr>
<td height="30">Your Contact number:</td>
<td><div align="left">
<input type="text" name="cont_no" id="cont_no" size="40">
</div></td>
</tr>
<tr>
<td height="30">You Applied for:</td>
<td><div align="left">
<input type="text" name="apply" id="apply" size="40">
</div></td>
</tr>
<tr>
<td height="30">Your Email ID:</td>
<td><div align="left">
<input type="text" name="e_mail" id="e_mail" size="40">
</div></td>
</tr>
<tr>
<td height="73" colspan="2"> <h2> Check Your <span>Status Below</span></h2></td>
</tr>
<tr>
<td class="txt1"><div align="center">
<p> </p>
<p align="left">Thanks For Your Registration</p>
<p align="right"> Your Student ID :
<input type="text" name="s_id" id="s_id">
</p>
<label for="s_id"></label>
</div>
<div align="center"></div></td>
<td><div align="left"><img src="images/blue_tick2.png" alt="t1" width="83" height="68" align="left"></div></td>
</tr>
<tr>
<td class="txt1"><div align="center">
<p> </p>
<p>Your documents are received</p>
</div></td>
<td><div align="left"><img src="images/blue_tick2.png" alt="t1" width="83" height="68" align="left"></div></td>
</tr>
<tr>
<td class="txt1"><div align="center">
<p> </p>
<p>Admission Granted</p>
</div></td>
<td><div align="left"><img src="images/blue_tick2.png" alt="t1" width="83" height="68" align="left"></div></td>
</tr>
<tr class="txt1">
<td ><input type="image" src="images/Blue12.png" alt="sign out" width="125" height="74" align="right"></td>
</tr>
<tr class="txt1">
<td colspan="2" style="visibility:hidden"><p>Congratulations ! You are selected for admission
</p>
<p><a href="15_feesMCA.html" class="txt1">Click Here For more Details of MCA candidates</a></p>
<p><a href="#" class="txt1">Click Here For more Details of MScIT candidates</a></p>
<p><a href="#" class="txt1">Click Here For more Details of MScMM candidates</a></p>
</td>
</tr>
<tr>
<td> </td>
<td><div align="left"></div></td>
</tr>
<tr>
<td> </td>
<td><div align="left"></div></td>
</tr>
</table>
<p> </p>
<p> </p>
<p> </p>
</div>
</section>
</div>
</div>
<footer>
<div class="footerlink"></div>
</footer>
<script type="text/javascript"> Cufon.now(); </script>
<!-- END PAGE SOURCE -->
<div align=center></body>
</html>
| 37.32973 | 125 | 0.477266 |
c57570bcbb0fbe787b812ba62024f5b2ab3a35d4
| 580 |
kt
|
Kotlin
|
app/src/main/java/com/rabindra/app/weatherapp/domain/datasource/forecast/ForecastLocalDataSource.kt
|
rabindranarayanpandit/android
|
acc759c89a2c9bcf14e93aa575d4a5ef967d4208
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/rabindra/app/weatherapp/domain/datasource/forecast/ForecastLocalDataSource.kt
|
rabindranarayanpandit/android
|
acc759c89a2c9bcf14e93aa575d4a5ef967d4208
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/rabindra/app/weatherapp/domain/datasource/forecast/ForecastLocalDataSource.kt
|
rabindranarayanpandit/android
|
acc759c89a2c9bcf14e93aa575d4a5ef967d4208
|
[
"MIT"
] | null | null | null |
package com.rabindra.app.weatherapp.domain.datasource.forecast
import com.rabindra.app.weatherapp.db.dao.ForecastDao
import com.rabindra.app.weatherapp.db.entity.ForecastEntity
import com.rabindra.app.weatherapp.domain.model.ForecastResponse
import javax.inject.Inject
/**
* Created by Furkan on 2019-10-21
*/
class ForecastLocalDataSource @Inject constructor(private val forecastDao: ForecastDao) {
fun getForecast() = forecastDao.getForecast()
fun insertForecast(forecast: ForecastResponse) = forecastDao.deleteAndInsert(
ForecastEntity(forecast)
)
}
| 29 | 89 | 0.793103 |
95381cda43e59ebc1eef405ef7efadf3381a93fd
| 1,311 |
css
|
CSS
|
src/binary_browser/css/style.css
|
tranminhduc4796/far_cry_online
|
8efc063f3f7de1912a5b3767a629fbe67a1c78a1
|
[
"MIT"
] | null | null | null |
src/binary_browser/css/style.css
|
tranminhduc4796/far_cry_online
|
8efc063f3f7de1912a5b3767a629fbe67a1c78a1
|
[
"MIT"
] | 3 |
2021-01-28T19:53:38.000Z
|
2022-03-25T18:44:26.000Z
|
src/binary_browser/css/style.css
|
tranminhduc4796/far_cry_online
|
8efc063f3f7de1912a5b3767a629fbe67a1c78a1
|
[
"MIT"
] | null | null | null |
* {
padding: 0;
margin: 0;
font-family: 'Roboto', sans-serif;
}
body {
background: url('../../../assets/binary_browser_background.png');
}
.icon {
margin: 0 5px;
opacity: 0.7;
padding: 2px;
-webkit-app-region: no-drag;
}
.icon:hover {
opacity: 1;
}
nav {
width: 100%;
display: flex;
align-items: center;
justify-content: flex-end;
-webkit-app-region: drag;
}
.content {
margin-left: 20px;
}
.content label {
font-style: normal;
font-weight: bold;
font-size: 18px;
color: rgba(255, 255, 255, 0.7);
margin: 0;
}
.content #error-mess {
padding: 2px 10px;
background-color: rgba(255,0,0,0.7);
width: 20%;
color: white;
}
.path_input {
height: fit-content;
display: flex;
align-items: center;
}
.path_input input {
width: 45%;
height: 25px;
opacity: 0.5;
background-color: black;
border: rgba(0,0,0,0.7) solid 1px;
color: white;
}
.path_input .icon{
padding: 0;
}
footer {
position: absolute;
right: 10px;
bottom: 5px;
}
footer button {
margin: 0 10px;
width: 100px;
height: 35px;
text-decoration: none;
color: white;
background-color: rgba(0,0,0,0.7);
border: none;
}
footer button:hover {
border: deepskyblue solid 1px;
}
| 15.244186 | 69 | 0.587338 |
dd707193dd1fd3d7843445fb6338dfaa0d6482ba
| 3,079 |
go
|
Go
|
examples/restore.go
|
IrennaLumbuun/nimble-golang-sdk
|
2af65b6ef8137fbc07c24cc78c2118206ca04149
|
[
"Apache-2.0"
] | null | null | null |
examples/restore.go
|
IrennaLumbuun/nimble-golang-sdk
|
2af65b6ef8137fbc07c24cc78c2118206ca04149
|
[
"Apache-2.0"
] | null | null | null |
examples/restore.go
|
IrennaLumbuun/nimble-golang-sdk
|
2af65b6ef8137fbc07c24cc78c2118206ca04149
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2020 Hewlett Packard Enterprise Development LP
package main
import (
"fmt"
"github.com/hpe-storage/nimble-golang-sdk/pkg/client/v1/nimbleos"
"github.com/hpe-storage/nimble-golang-sdk/pkg/param"
"github.com/hpe-storage/nimble-golang-sdk/pkg/service"
)
func main() {
// login to Array, get groupService instance
groupService, err := service.NewNimbleGroupService(
service.WithHost("1.1.1.1"),
service.WithUser("xxx"),
service.WithPassword("xxx"),
service.WithoutWaitForAsyncJobs())
if err != nil {
fmt.Printf("NewGroupService(): Unable to connect to group, err: %v", err.Error())
return
}
defer groupService.LogoutService()
// set debug
groupService.SetDebug()
// get volume service instance
volSvc := groupService.GetVolumeService()
// Initialize volume attributes
var sizeField int64 = 5120
descriptionField := "This volume was created as part of a unit test"
var limitIopsField int64 = 256
var limitMbpsField int64 = 1
// set volume attributes
newVolume := &nimbleos.Volume{
Name: param.NewString("RestoreVolume"),
Size: &sizeField,
Description: &descriptionField,
ThinlyProvisioned: param.NewBool(true),
Online: param.NewBool(true),
LimitIops: &limitIopsField,
LimitMbps: &limitMbpsField,
MultiInitiator: param.NewBool(true),
AgentType: nimbleos.NsAgentTypeNone,
}
// create volume
volume, err := volSvc.CreateVolume(newVolume)
if volume != nil {
volcollName := &nimbleos.VolumeCollection{
Name: param.NewString("TestVolcoll"),
}
volcoll, err := groupService.GetVolumeCollectionService().CreateVolumeCollection(volcollName)
if err != nil {
fmt.Println("Failed to create volume collection")
return
}
// add volume to volume collection
err = volSvc.AssociateVolume(*volume.ID, *volcoll.ID)
if err != nil {
fmt.Println("Failed to associate RestoreVolume to volcoll ")
return
}
// create a snapshot collection
snapColl, _ := groupService.GetSnapshotCollectionService().CreateSnapshotCollection(&nimbleos.SnapshotCollection{
Name: param.NewString("RestoreSnapColl"),
VolcollId: volcoll.ID,
})
// Get snapshot collection by name
snapColl, err = groupService.GetSnapshotCollectionService().GetSnapshotCollectionByName("RestoreSnapColl")
if err != nil {
fmt.Printf("Failed to get snapshot collection by name, err: %v\n", err)
}
fmt.Println(snapColl)
// set the volume offline before restore
volSvc.OfflineVolume(*volume.ID, true)
//restore volume to snapcoll
err = volSvc.RestoreVolume(*volume.ID, *snapColl.SnapshotsList[0].SnapId)
if err != nil {
fmt.Println("Failed to restore volume")
}
// cleanup
// disassociate volume from volume collection
err = volSvc.DisassociateVolume(*volume.ID)
if err != nil {
fmt.Printf("Failed to remove %s volume from volume collection\n", *volume.ID)
return
}
// delete volcoll
groupService.GetVolumeCollectionService().DeleteVolumeCollection(*volcoll.ID)
volSvc.DeleteVolume(*volume.ID)
}
}
| 28.509259 | 115 | 0.715167 |
9c39c03462738217dee5cad2afd2fb9bd45ef7ac
| 2,378 |
js
|
JavaScript
|
CMS/CMSScripts/CMSModules/CMS.Forms/Directives/CMSInputAttributesDirective.js
|
mzhokh/FilterByCategoryWidget
|
c6b83215aea4f4df607d070fe4c772bd96ee6a95
|
[
"MIT"
] | 26 |
2019-02-26T19:44:44.000Z
|
2021-07-19T01:45:37.000Z
|
CMS/CMSScripts/CMSModules/CMS.Forms/Directives/CMSInputAttributesDirective.js
|
mzhokh/FilterByCategoryWidget
|
c6b83215aea4f4df607d070fe4c772bd96ee6a95
|
[
"MIT"
] | 34 |
2018-12-10T09:30:13.000Z
|
2020-09-02T11:14:12.000Z
|
CMS/CMSScripts/CMSModules/CMS.Forms/Directives/CMSInputAttributesDirective.js
|
mzhokh/FilterByCategoryWidget
|
c6b83215aea4f4df607d070fe4c772bd96ee6a95
|
[
"MIT"
] | 50 |
2018-12-06T17:32:43.000Z
|
2021-11-04T09:48:07.000Z
|
cmsdefine([], function () {
/**
* This directive looks for supported attributes in the parent scope. If any of the supported
* value is found, it is passed to the context element.
* If the scope specifies id attribute, its value will be used for the name attribute as well.
*
* This directive is valid only for input, textarea or select element.
*
* @example
* ...
* $scope = {
* required: true,
* maxlength: 50,
* id: "someId"
* };
*
* ...
*
* <input type="text" data-ng-model="model" cms-input-attributes="" />
*
* will transform the input to
*
* <input type="text" data-ng-model="model" name="someId" id="someId" required maxlength="50" cms-input-attributes="" />
*
* @throws If the directive is used for not supported element.
*/
// Array of supported HTML attributes containing values
var supportedAttributes = ["maxlength", "required", "cols", "rows", "id"],
// Array of supported HTML attributes without the value
supportedProperties = ["required"];
return [function () {
return {
restrict: "A",
link: function ($scope, $element) {
var elementTagName = $element.prop("tagName").toLowerCase();
if ((elementTagName !== "input") && (elementTagName !== "textarea") && (elementTagName !== "select")) {
throw "This directive can be used only for input, textarea or select element, but was used for the '" + elementTagName + "'.";
}
supportedAttributes.forEach(function(attribute) {
if ($scope[attribute]) {
$element.attr(attribute, $scope[attribute]);
}
});
supportedProperties.forEach(function (property) {
if ($scope[property]) {
$element.prop(property, true);
}
});
// Name is special attribute, since is usually matches the id, so it will be added even if it is not explicitly specified in the scope
if ($scope.id) {
$element.attr("name", $scope.id);
}
}
};
}];
});
| 37.746032 | 150 | 0.519765 |
2b59cdc909c3f77b9904fd75a847089e1d0e82e9
| 3,908 |
sql
|
SQL
|
resources/migrations/2017091817300000-update-completed_benchmark-metrics.up.sql
|
nucleotides/event-api
|
aea8f9ce8e76fbff646d1535228c6c09be4a7158
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
resources/migrations/2017091817300000-update-completed_benchmark-metrics.up.sql
|
nucleotides/event-api
|
aea8f9ce8e76fbff646d1535228c6c09be4a7158
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
resources/migrations/2017091817300000-update-completed_benchmark-metrics.up.sql
|
nucleotides/event-api
|
aea8f9ce8e76fbff646d1535228c6c09be4a7158
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
-- Drop this view first to then drop dependent views
DROP VIEW completed_benchmark_metrics;
-- No longer going to base the completed_benchmark_metrics table off of this view
DROP VIEW image_task_benchmarking_state;
--
-- View of numbers of tasks per benchmark instance by benchmark type
--
-- The numbers of tasks is always going to be 1 (the produce task) plus however
-- many evaluation tasks there are.
--
CREATE MATERIALIZED VIEW tasks_per_benchmark_instance_by_benchmark_type AS
SELECT benchmark_type_id,
(COUNT(image_task_id) + 1) AS n_tasks
FROM benchmark_type
JOIN image_expanded_fields ON benchmark_type.evaluation_image_type_id = image_expanded_fields.image_type_id
GROUP BY benchmark_type_id;
--
CREATE UNIQUE INDEX ON tasks_per_benchmark_instance_by_benchmark_type (benchmark_type_id);
--
-- View of the state of each benchmark instance
--
CREATE VIEW benchmark_instance_state AS
SELECT benchmark_instance_id,
COALESCE(bool_and(event.success), FALSE) AS instance_successful,
COUNT(event_id) = n_tasks AS instance_finished
FROM benchmark_instance
JOIN task USING (benchmark_instance_id)
JOIN tasks_per_benchmark_instance_by_benchmark_type USING (benchmark_type_id)
LEFT JOIN events_prioritised_by_successful AS event USING (task_id)
GROUP BY benchmark_instance_id, n_tasks;
--
-- Simpler view of all benchmarking metrics, only requiring each individual
-- benchmark instance has been completed, rather than all tasks for a given image
-- task be completed.
--
CREATE VIEW completed_benchmark_metrics AS
SELECT external_id AS benchmark_id,
benchmark_type.name AS benchmark_type_name,
input_file.sha256 AS input_file_id,
image_type_name AS image_type,
image_instance_name AS image_name,
image_version_name AS image_version,
image_task_name AS image_task,
input_file.platform,
input_file.protocol,
input_file.material,
input_file.extraction_method,
input_file.run_mode,
input_file.biological_source_type,
input_file.biological_source_name,
input_file.input_file_set_name,
metric_type.name AS variable,
metric_instance.value
FROM benchmark_instance_state AS state
JOIN benchmark_instance USING (benchmark_instance_id)
JOIN benchmark_type USING (benchmark_type_id)
JOIN input_data_file_expanded_fields AS input_file USING (input_data_file_id)
JOIN image_expanded_fields AS image ON benchmark_instance.product_image_task_id = image.image_task_id
JOIN task USING (benchmark_instance_id)
JOIN events_prioritised_by_successful USING (task_id)
JOIN metric_instance USING (event_id)
JOIN metric_type USING (metric_type_id)
WHERE state.instance_successful = true
AND state.instance_finished = true;
--;;
--;; Function rebuild all benchmark instances and tasks
--;;
CREATE OR REPLACE FUNCTION rebuild_benchmarks () RETURNS void AS $$
BEGIN
REFRESH MATERIALIZED VIEW input_data_file_expanded_fields;
REFRESH MATERIALIZED VIEW image_expanded_fields;
PERFORM populate_benchmark_instance();
PERFORM populate_task();
REFRESH MATERIALIZED VIEW tasks_per_image_by_benchmark_type;
REFRESH MATERIALIZED VIEW tasks_per_benchmark_instance_by_benchmark_type;
REINDEX TABLE benchmark_instance;
REINDEX TABLE task;
REINDEX TABLE tasks_per_image_by_benchmark_type;
END; $$
LANGUAGE PLPGSQL;
| 44.409091 | 124 | 0.691146 |
39cb2cd9a2be2a89503423d8460a50ab99de9008
| 129 |
js
|
JavaScript
|
settings.js
|
Sollunad/Niles-Edit
|
4c340c6900e324f3aad472398fd7beefb962be92
|
[
"MIT"
] | null | null | null |
settings.js
|
Sollunad/Niles-Edit
|
4c340c6900e324f3aad472398fd7beefb962be92
|
[
"MIT"
] | 1 |
2021-05-11T10:52:11.000Z
|
2021-05-11T10:52:11.000Z
|
settings.js
|
Sollunad/Niles-Edit
|
4c340c6900e324f3aad472398fd7beefb962be92
|
[
"MIT"
] | 1 |
2019-09-24T15:21:02.000Z
|
2019-09-24T15:21:02.000Z
|
module.exports = {
secrets: require("./config/secrets.json"),
calendarConfig: require("./config/calendarsettings.js")
};
| 25.8 | 59 | 0.689922 |
dd856166ea47c636e9ad3e78c25a6a64e15f013d
| 1,561 |
go
|
Go
|
cmd/podman/shared/funcs_test.go
|
gbraad/libpod
|
8cccac54979b804d1086ff42654de07dba802a2e
|
[
"Apache-2.0"
] | 2 |
2020-04-20T23:10:51.000Z
|
2021-01-06T12:09:05.000Z
|
cmd/podman/shared/funcs_test.go
|
gbraad/libpod
|
8cccac54979b804d1086ff42654de07dba802a2e
|
[
"Apache-2.0"
] | null | null | null |
cmd/podman/shared/funcs_test.go
|
gbraad/libpod
|
8cccac54979b804d1086ff42654de07dba802a2e
|
[
"Apache-2.0"
] | null | null | null |
package shared
import (
"testing"
"github.com/containers/libpod/pkg/util"
"github.com/stretchr/testify/assert"
)
var (
name = "foo"
imageName = "bar"
)
func TestGenerateRunEnvironment(t *testing.T) {
opts := make(map[string]string)
opts["opt1"] = "one"
opts["opt2"] = "two"
opts["opt3"] = "three"
envs := GenerateRunEnvironment(name, imageName, opts)
assert.True(t, util.StringInSlice("OPT1=one", envs))
assert.True(t, util.StringInSlice("OPT2=two", envs))
assert.True(t, util.StringInSlice("OPT3=three", envs))
}
func TestGenerateRunEnvironmentNoOpts(t *testing.T) {
opts := make(map[string]string)
envs := GenerateRunEnvironment(name, imageName, opts)
assert.False(t, util.StringInSlice("OPT1=", envs))
assert.False(t, util.StringInSlice("OPT2=", envs))
assert.False(t, util.StringInSlice("OPT3=", envs))
}
func TestGenerateRunEnvironmentSingleOpt(t *testing.T) {
opts := make(map[string]string)
opts["opt1"] = "one"
envs := GenerateRunEnvironment(name, imageName, opts)
assert.True(t, util.StringInSlice("OPT1=one", envs))
assert.False(t, util.StringInSlice("OPT2=", envs))
assert.False(t, util.StringInSlice("OPT3=", envs))
}
func TestGenerateRunEnvironmentName(t *testing.T) {
opts := make(map[string]string)
envs := GenerateRunEnvironment(name, imageName, opts)
assert.True(t, util.StringInSlice("NAME=foo", envs))
}
func TestGenerateRunEnvironmentImage(t *testing.T) {
opts := make(map[string]string)
envs := GenerateRunEnvironment(name, imageName, opts)
assert.True(t, util.StringInSlice("IMAGE=bar", envs))
}
| 28.907407 | 56 | 0.721973 |
fa2a0bf1b8f9a96b3e09e1d0a0b80af640de9d84
| 122 |
sql
|
SQL
|
SQL/sign_in_validation.sql
|
yanirmor/shiny-user-management
|
ec63f167281d4b151cce802fe46944e1f09fc7d2
|
[
"MIT"
] | 25 |
2018-09-13T15:51:33.000Z
|
2022-02-12T05:24:58.000Z
|
SQL/sign_in_validation.sql
|
apollolrr/shiny-user-management
|
ec63f167281d4b151cce802fe46944e1f09fc7d2
|
[
"MIT"
] | 1 |
2021-08-12T15:35:06.000Z
|
2021-08-12T15:35:06.000Z
|
SQL/sign_in_validation.sql
|
apollolrr/shiny-user-management
|
ec63f167281d4b151cce802fe46944e1f09fc7d2
|
[
"MIT"
] | 6 |
2021-03-09T11:20:22.000Z
|
2022-02-10T10:47:59.000Z
|
SELECT username, color
FROM user_management
WHERE is_enabled = 'y'
AND username = ?username
AND password = ?password;
| 20.333333 | 27 | 0.754098 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.