identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/truongoi/truong-cloud-gatsby-netlify/blob/master/src/components/Sidebar/Toggle/Toggle.js
|
Github Open Source
|
Open Source
|
MIT
| null |
truong-cloud-gatsby-netlify
|
truongoi
|
JavaScript
|
Code
| 34
| 109
|
import React from 'react';
import styles from './Toggle.module.scss';
const Toggle = (props) => {
return (
<div className={[styles['Toggle'], props.isOpen ? styles['active'] : null].join(' ')} onClick={props.clicked}>
<div></div>
<div></div>
<div></div>
</div>
)
}
export default Toggle;
| 23,315
|
https://github.com/keygenqt/skill-patterns-kotlin/blob/master/src/main/kotlin/com/keygenqt/patterns/pattern/behavioral/observer/Observer.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
skill-patterns-kotlin
|
keygenqt
|
Kotlin
|
Code
| 9
| 33
|
package com.keygenqt.patterns.pattern.behavioral.observer
interface Observer {
fun update(message: String)
}
| 35,256
|
https://github.com/bilam/ide_jnet/blob/master/util/fiw.ijs
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
ide_jnet
|
bilam
|
J
|
Code
| 1,421
| 4,689
|
require 'regex'
coclass 'jfiw'
coinsert 'j';'jijs'
FIWCASE=: 1
FIWCONNDX=: 0
FIWDOWN=: 1
FIWDEFAULT=: 1
FIWH=: ''
FIWINC=: 0
FIWMSK=: ''
FIWWHAT=: ''
FIWMAX=: 20
FIWTITLE=: 'Find'
FIWRTITLE=: 'Find & Replace'
FIWCONTEXT=: 0 : 0
any
name only
assigned
assigned globally
assigned locally
in comment text
)
3 : 0''
if. _1=4!:0 <'FIWFIND' do.
FIWFIND_j_=: i.0 3
FIWREPLACE_j_=: ''
end.
)
deb=: #~ (+. 1: |. (> </\))@(' '&~:)
find=: #@[ (| - =) i.
bcfind=: find &: (tolower each)
finfo=: 3 : 'wdinfo FIWTITLE;y'
frinfo=: 3 : 'wdinfo FIWRTITLE;y'
fquery=: 4 : 'x wdquery FIWTITLE;y'
groupndx=: [: <: I. + e.~
subs=. 2 : 'm I. @(e.&n)@]} ]'
toblank=: ' ' subs '_'
tohyphen=: '_' subs ' '
subtcc=: ' '&(I.@(e.&(TAB,CRLF))@]})
termLF=: , (0: < #) # LF"_ -. _1&{.
termdelLF=: }.~ [: - 0: i.~ LF&= @ |.
tolist=: }. @ ; @: (LF&, each)
toLF=: (10{a.)&(I. @(e.&(13{a.))@]})
ffmatch=: ({.@{.+{:@(1&{)) @ rxmatch_jregex_
ffmatches=: ({.@{.+{:@(1&{))"2 @ rxmatches_jregex_
fiwsbs=: #~ -.@('\\'&E.)
fiwplain=: ;@(,~&.> e.&'[](){}$^.*+?|\' #&.> (<PATHSEP_j_)"_)
a=. ,&';'
b=. e.&', ;' > [: ~:/\ e.&'"'
c=. b (< @ (-.&'"')) ;._2 ]
d=. -.&a:
fcut=: d@c@a f.
comments=: 3 : 0
txt=. <;._2 y,LF
f=. 'NB.'&E. <: ~:/\@(''''&=)
g=. i.&0 + 3: * 0&e.
h=. g@f ($&' '@[ , }.) ]
txt=. h each txt
}: ;txt ,each LF
)
fiwmax=: 3 : 0
dat=. y #~ ~: {."1 ,. y
(FIWMAX <. #dat) {. dat
)
JFIR=: 0 : 0
pc6j jfir closeok;pn "Find and Replace";
xywh 2 8 40 11;cc s0 static ss_right;cn "Find what:";
xywh 45 7 122 70;cc what combodrop ws_border cbs_autohscroll rightmove;
xywh 2 26 40 11;cc s1 static ss_right;cn "In context:";
xywh 45 25 70 100;cc context combolist rightmove;
xywh 2 49 40 11;cc s2 static ss_right;cn "Replace:";
xywh 45 48 122 70;cc repwhat combodrop ws_border cbs_autohscroll rightmove;
xywh 119 26 53 12;cc case checkbox leftmove rightmove;cn "Match case";
xywh 91 64 80 12;cc undo button leftmove rightmove;cn "Undo Last";
xywh 176 4 80 12;cc findtop button bs_defpushbutton leftmove rightmove;cn "Find Top (Ctrl+F3)";
xywh 176 19 80 12;cc find button leftmove rightmove;cn "Find Next (F3)";
xywh 176 34 80 12;cc findback button bs_defpushbutton leftmove rightmove;cn "Find Back (Shift+F3)";
xywh 176 49 80 12;cc replace button leftmove rightmove;cn "Replace";
xywh 176 64 80 12;cc replaceall button leftmove rightmove;cn "Replace Forward";
pas 8 2;pcenter;ptop;
rem form end;
)
jfir_run=: 3 : 0
FIWINC=: 0
FIWHOLD=: FIWH
oldformx=. 0 ".wd'qformx'
wd JFIR
FIWH=: wd 'qhwndp'
wd 'setfocus what'
wd 'set context *',FIWCONTEXT
if. #FIWFIND do.
txt=. {."1 FIWFIND
wd 'set what *',utf8 tolist txt
if. #FIWWHAT do.
wd 'setselect what ',":ndx=. txt i. <FIWWHAT
FIWCASE=: 2 pick ndx{FIWFIND
FIWCONNDX=: 1 pick ndx{FIWFIND
wd 'setfocus repwhat'
end.
end.
if. #FIWREPLACE do.
wd 'set repwhat *',utf8 tolist FIWREPLACE
end.
wd 'setselect context ',":{:0,FIWCONNDX
wd 'set case ',":FIWCASE
wd 'setenable undo 0'
wd 'pmovex ',":(3 {. oldformx),{: 0 ". wd'qformx'
wd 'pshow'
wd 'psel ',FIWHOLD
wd 'pclose;psel ',FIWH
wd 'pactive'
)
jfir_read=: 3 : 0
FIWINC=: 0
jfir_readrest''
)
jfir_readrest=: 3 : 0
jfiw_readrest''
FIWREPWHAT=: ucp repwhat
jfirsetfind''
)
jfir_readundo=: 3 : 0
FIWTEXTOLD=: FIWTEXT
FIWPOSOLD=: FIWPOS
FIWINCOLD=: FIWINC
)
jfirsetfind=: 3 : 0
if. #FIWREPWHAT do.
FIWREPLACE_j_=: fiwmax (<FIWREPWHAT),FIWREPLACE
wd 'set repwhat *',utf8 tolist FIWREPLACE
wd 'setselect repwhat 0'
end.
)
jfir_close=: 3 : 0
if. #FIWH do.
wd 'psel ',FIWH
wd 'pclose'
FIWH=: ''
end.
)
jfirok=: 3 : 0
if. 0=#FIWWHAT do. 0 [ frinfo 'Nothing to replace' return. end.
if. FIWREPWHAT-:FIWWHAT do.
0 [ frinfo 'Find and Replace texts are the same' return.
end.
1
)
jfir_replace_button=: 3 : 0
jfir_readrest''
if. 0=jfirok'' do. FIWINC=0 return. end.
if. FIWINC=0 do.
old=. FIWPOS
dat=. fwss''
if. dat=_1 do. return. end.
if. dat=_2 do. frinfo 'No match found' return. end.
FIWPOS=: dat
FIWINC=: 1
if. old~:FIWPOS do. jfir_show'' return. end.
end.
jfir_readundo''
dat=. fwrs''
smwrite FIWTEXT
wd 'psel ',FIWH
wd 'setenable undo 1'
if. dat=_3 do.
jfir_show 1
FIWINC=: 0
else.
FIWINC=: 1
FIWPOS=: dat
jfir_show''
end.
)
jfir_replaceall_button=: 3 : 0
jfir_read''
if. 0=jfirok'' do. return. end.
count=. 0
old=. FIWPOS
dat=. fwss''
if. dat=_1 do. return. end.
if. dat=_2 do. frinfo 'No matches found' return. end.
FIWPOS=: dat
FIWINC=: 1
jfir_readundo''
whilst. 0 <: dat do.
count=. count + 1
dat=. fwrs''
end.
wd 'psel ',FIWH
wd 'setenable undo 1'
smwrite FIWTEXT
wd 'psel ',FIWH
frinfo (":count),' replacement',((1<count)#'s'),' made'
FIWINC=: 0
)
jfir_repwhat_select=: 3 : 0
FIWINC=: 0
FIWREPWHAT=: repwhat
jfirsetfind''
)
jfir_undo_button=: 3 : 0
FIWTEXT=: FIWTEXTOLD
FIWPOS=: FIWPOSOLD
FIWINC=: FIWINCOLD
wd 'psel ',FIWH
wd 'setenable undo 0'
smwrite FIWTEXT
jfir_show''
)
jfir_show=: 3 : 0
if. y-:1 do. len=. 0 else. len=. #FIWWHAT end.
smscroll 0 >. _7 + +/ LF = FIWPOS {. FIWTEXT
smsetselect (FIWPOS+0,len),1
smfocus''
)
jfir_case_button=: jfiw_case_button
jfir_find_button=: jfiw_find_button
jfir_findback_button=: jfiw_findback_button
jfir_findtop_button=: jfiw_findtop_button
jfir_context_button=: jfiw_find_button
jfir_what_button=: jfiw_what_button
jfir_enter=: jfir_context_button=: jfir_repwhat_button=: jfiw_find_button
jfir_what_select=: jfiw_what_select
jfir_context_select=: jfiw_context_select
jfir_fctrl_fkey=: jfiw_find_button
jfir_fctrl_fkey=: jfiw_find_button bind 1
jfir_f3_fkey=: jfiw_find_button bind 1
jfir_f3ctrl_fkey=: jfiw_find_button bind 0
jfir_f3shift_fkey=: jfiw_find_button bind _1
jfir_cancel_button=: jfir_cancel=: jfir_close
fwssinit=: 3 : 0
p=. y
nna=. '(^|[^[:alnum:]_])'
nnz=. '($|[^[:alnum:]_])'
select. FIWCONNDX
case. 1 do. p=. nna,p,nnz
case. 2 do. p=. nna,p,'[[:space:]]*=[.:]'
case. 3 do. p=. nna,p,'[[:space:]]*=:'
case. 4 do. p=. nna,p,'[[:space:]]*=\.'
end.
FIWCOMP=: rxcomp_jregex_ :: _1: p
if. FIWCOMP -: _1 do.
finfo 'Unable to compile regular expression'
0
else.
1
end.
)
fwss=: 3 : 0
if. FIWCASE=0 do.
txt=. tolower FIWTEXT
what=. tolower FIWWHAT
else.
txt=. FIWTEXT
what=. FIWWHAT
end.
regex=. FIWCONNDX e. 1 2 3 4
if. regex do.
if. 0=fwssinit what do. _1 return. end.
end.
if. FIWCONNDX=5 do.
txt=. comments txt
end.
if. FIWDOWN=0 do.
blk=. FIWPOS{.txt
if. regex do.
ndx=. FIWCOMP ffmatches blk
rxfree_jregex_ FIWCOMP
else.
ndx=. I. what E. blk
end.
if. 0 e. $ndx do. _2 else. {:ndx end.
else.
blk=. (FIWPOS+FIWINC)}.txt
if. regex do.
ndx=. _1 -.~ FIWCOMP ffmatch blk
rxfree_jregex_ FIWCOMP
else.
ndx=. I. what E. blk
end.
if. 0 e. $ndx do. _2 else. FIWPOS+FIWINC+{.ndx end.
end.
)
fwrs=: 3 : 0
FIWTEXT=: (FIWPOS{.FIWTEXT),FIWREPWHAT,(FIWPOS+#FIWWHAT)}.FIWTEXT
old=. FIWPOS
FIWPOS=: FIWPOS+FIWDOWN * 0 >. <:#FIWREPWHAT
hit=. fwss''
if. hit<0 do.
FIWPOS=: old
_3
else.
FIWPOS=: hit
end.
)
JFIW=: 0 : 0
pc6j jfiw;pn "Find";
xywh 2 8 40 11;cc s0 static ss_right;cn "Find what:";
xywh 45 7 122 70;cc what combodrop ws_border cbs_autohscroll rightmove;
xywh 2 26 40 11;cc s1 static ss_right;cn "In context:";
xywh 45 25 70 100;cc context combolist rightmove;
xywh 119 26 53 12;cc case checkbox leftmove rightmove;cn "Match case";
xywh 176 4 80 12;cc findtop button bs_defpushbutton leftmove rightmove;cn "Find Top (Ctrl+F3)";
xywh 176 19 80 12;cc find button leftmove rightmove;cn "Find Next (F3)";
xywh 176 34 80 12;cc findback button leftmove rightmove;cn "Find Back (Shift+F3)";
xywh 176 49 80 12;cc replace button leftmove rightmove;cn "Replace...";
pas 8 2;pcenter;ptop;
rem form end;
)
jfiw_run=: 3 : 0
if. wdishandle FIWH do.
wd 'psel ',FIWH
jfiw_find_button y
return.
end.
FIWINC=: 0
FIWDOWN=: 1
FIWDEFAULT=: 1
wd JFIW
FIWH=: wd 'qhwndp'
wpset 'jfiw'
wd 'set context *',FIWCONTEXT
if. #FIWFIND do. jfiwsetfind 0 end.
wd 'setselect context ',":FIWCONNDX
wd 'set case ',":FIWCASE
wd 'setfocus what'
wd 'pshow'
)
jfiw_close=: 3 : 0
if. #FIWH do.
wd 'psel ',FIWH
wpsave 'jfiw'
wd 'psel ',FIWH
end.
wd 'pclose'
FIWH=: ''
)
jfiw_read=: 3 : 0
FIWINC=: 0
jfiw_readrest''
)
jfiw_readrest=: 3 : 0
FIWWHAT=: ucp what
FIWCONNDX=: {: 0,". context_select
FIWCASE=: ". case
if. #FIWWHAT do.
FIWFIND_j_=: fiwmax (FIWWHAT;FIWCONNDX;FIWCASE),FIWFIND
wd 'set what *',utf8 tolist {."1 FIWFIND
wd 'setselect what 0'
end.
smselact''
FIWTEXT=: smread ''
FIWPOS=: {. smgetsel ''
wd 'psel ',FIWH
)
jfiw_find_button=: 3 : 0
if. 0=#FIWH do. return. end.
jfiw_readrest''
y=. {. y,1
select. y
case. _1 do.
FIWDOWN=: 0
case. 0 do.
FIWPOS=: 0
FIWINC=: 0
FIWDOWN=: 1
FIWDEFAULT=: 1
case. do.
FIWDOWN=: 1
FIWDEFAULT=: 0
end.
dat=. fwss''
if. _1-:dat do. return. end.
if. _2-:dat do. finfo 'No match found' return. end.
FIWPOS=: dat
jfiw_show''
FIWINC=: 1
)
jfiw_findback_button=: jfiw_find_button bind _1
jfiw_findtop_button=: jfiw_find_button bind 0
jfiw_finddefault=: 3 : 0
jfiw_find_button FIWDEFAULT
)
jfiw_show=: 3 : 0
if. y-:1 do. len=. 0 else. len=. #FIWWHAT end.
smsetselect (FIWPOS+0,len),0
smfocus''
)
jfiw_what_select=: 3 : 0
FIWINC=: 0
if. #what_select do.
jfiwsetfind ".what_select
end.
)
jfiwsetfind=: 3 : 0
FIWFIND_j_=: FIWFIND /: y ~: i.#FIWFIND
'FIWWHAT FIWCONNDX FIWCASE'=: 0{FIWFIND
wd 'set what *',utf8 tolist {."1 FIWFIND
wd 'setselect what 0'
wd 'set case ',":FIWCASE
wd 'setselect context ',":FIWCONNDX
)
jfiw_enter=: jfiw_what_button=: jfiw_context_button=: jfiw_finddefault
jfiw_cancel_button=: jfiw_cancel=: jfiw_close
jfiw_replace_button=: jfir_run @ jfiw_read
jfiw_rctrl_fkey=: jfiw_replace_button
jfiw_context_select=: jfiw_read
jfiw_case_button=: jfiw_read
jfiw_fctrl_fkey=: jfiw_find_button bind 1
jfiw_f3_fkey=: jfiw_find_button bind 1
jfiw_f3ctrl_fkey=: jfiw_find_button bind 0
jfiw_f3shift_fkey=: jfiw_find_button bind _1
fiw=: jfiw_run
| 27,970
|
https://github.com/emelleme/G8-life/blob/master/mysite/javascript/requestform.js
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,011
|
G8-life
|
emelleme
|
JavaScript
|
Code
| 185
| 517
|
$(document).ready(function(){
//Load the Request form
//On Click of Continue, submit form and check address
$("#registrant").submit(function(e) {
var form = $(this);
//$("#apple").html('<p>Saving your information...<br><img src="themes/solar/images/ajax-loader.gif" /></p>');
// client-side validation OK.
if (!e.isDefaultPrevented()) {
$("#apple").overlay({
// custom top position
// some mask tweaks suitable for facebox-looking dialogs
mask: {
// you might also consider a "transparent" color for the mask
color: '#000',
// load mask a little faster
loadSpeed: 200,
// very transparent
opacity: 0.5
},
effect: 'apple',
// disable this for modal dialog-type of overlays
closeOnClick: false,
// load it immediately after the construction
load: true
//Submit form data with Ajax
});
$.post(jQuery(this).attr("action"),$('#registrant').serialize(), function(data){
$('#apple').html(data);
});
// prevent default form submission logic
e.preventDefault();
}
});
});
function loadForm(){
$("#apple").overlay({
// custom top position
// some mask tweaks suitable for facebox-looking dialogs
mask: {
// you might also consider a "transparent" color for the mask
color: '#000',
// load mask a little faster
loadSpeed: 200,
// very transparent
opacity: 0.5
},
// disable this for modal dialog-type of overlays
closeOnClick: true,
// load it immediately after the construction
load: true
//Submit form data with Ajax
});
}
| 8,737
|
https://github.com/hhandika/yap/blob/master/src/stats/qscores.rs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
yap
|
hhandika
|
Rust
|
Code
| 177
| 641
|
//! Heru Handika
//! Only support Illumina 1.8 Quality Scores
pub struct QScore {
pub q_len: u32,
pub mean_q: f64,
pub low_bases: u32,
pub sum: u32,
}
impl QScore {
pub fn analyze_qscores(q_line: &[u8]) -> Self {
let q_scores = q_line.iter()
.map(|scr|
{ if *scr < 75 {
*scr as u32 - 33
} else {
panic!("UNSUPPORTED Q-SCORE ENCODING!");
}
})
.collect::<Vec<u32>>();
let mut q = Self {
q_len: q_scores.iter().count() as u32,
low_bases: q_scores.iter()
.filter(|&x| *x < 20)
.count() as u32,
sum: q_scores.iter().sum(),
mean_q: 0.0
};
q.mean();
q
}
fn mean(&mut self) {
self.mean_q = self.sum as f64 / self.q_len as f64
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn qscore_test () {
let p = String::from("II!)");
let q = String::from("II");
let q_score = QScore::analyze_qscores(q.as_bytes());
let p_score = QScore::analyze_qscores(p.as_bytes());
assert_eq!(2, q_score.q_len);
assert_eq!(40.0, q_score.mean_q);
assert_eq!(0, q_score.low_bases);
assert_eq!(2, p_score.low_bases);
}
#[test]
fn decode_qscores_test() {
let q = String::from("II");
let qs = QScore::analyze_qscores(q.as_bytes());
// let res = vec![40, 40];
assert_eq!(80, qs.sum);
}
#[test]
#[should_panic(expected = "UNSUPPORTED Q-SCORE ENCODING!")]
fn decode_panic_qscore() {
let p = String::from("II!)K");
QScore::analyze_qscores(&p.as_bytes());
}
}
| 18,262
|
https://github.com/gatewayapps/crondroid/blob/master/app/src/main/java/gatewayapps/crondroid/utils/Key.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
crondroid
|
gatewayapps
|
Java
|
Code
| 497
| 1,220
|
/*
* Copyright 2001-2009 Terracotta, Inc.
*
* 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 gatewayapps.crondroid.utils;
import java.io.Serializable;
import java.util.UUID;
/**
* <p>
* Object representing a job or trigger key.
* </p>
*
* @author <a href="mailto:jeff@binaryfeed.org">Jeffrey Wescott</a>
*/
public class Key<T> implements Serializable, Comparable<Key<T>> {
private static final long serialVersionUID = -7141167957642391350L;
/**
* The default group for scheduling entities, with the value "DEFAULT".
*/
public static final String DEFAULT_GROUP = "DEFAULT";
private final String name;
private final String group;
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Constructors.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/**
* Construct a new key with the given name and group.
*
* @param name
* the name
* @param group
* the group
*/
public Key(String name, String group) {
if(name == null)
throw new IllegalArgumentException("Name cannot be null.");
this.name = name;
if(group != null)
this.group = group;
else
this.group = DEFAULT_GROUP;
}
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Interface.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/**
* <p>
* Get the name portion of the key.
* </p>
*
* @return the name
*/
public String getName() {
return name;
}
/**
* <p>
* Get the group portion of the key.
* </p>
*
* @return the group
*/
public String getGroup() {
return group;
}
/**
* <p>
* Return the string representation of the key. The format will be:
* <group>.<name>.
* </p>
*
* @return the string representation of the key
*/
@Override
public String toString() {
return getGroup() + '.' + getName();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((group == null) ? 0 : group.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
@SuppressWarnings("unchecked")
Key<T> other = (Key<T>) obj;
if (group == null) {
if (other.group != null)
return false;
} else if (!group.equals(other.group))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public int compareTo(Key<T> o) {
if(group.equals(DEFAULT_GROUP) && !o.group.equals(DEFAULT_GROUP))
return -1;
if(!group.equals(DEFAULT_GROUP) && o.group.equals(DEFAULT_GROUP))
return 1;
int r = group.compareTo(o.getGroup());
if(r != 0)
return r;
return name.compareTo(o.getName());
}
public static String createUniqueName(String group) {
if(group == null)
group = DEFAULT_GROUP;
String n1 = UUID.randomUUID().toString();
String n2 = UUID.nameUUIDFromBytes(group.getBytes()).toString();
return String.format("%s-%s", n2.substring(24), n1);
}
}
| 23,236
|
https://github.com/ass-a2s/rancherui/blob/master/lib/shared/addon/components/storage-class/provisioner-gce-pd/component.js
|
Github Open Source
|
Open Source
|
Apache-2.0, LicenseRef-scancode-warranty-disclaimer
| 2,019
|
rancherui
|
ass-a2s
|
JavaScript
|
Code
| 147
| 427
|
import Component from '@ember/component';
import layout from './template';
import StorageClassProvisioner from 'shared/mixins/storage-class-provisioner';
import { get, set, setProperties } from '@ember/object';
export const VOLUME_TYPES = [
'pd-standard',
'pd-ssd',
];
export default Component.extend(StorageClassProvisioner, {
layout,
volumeTypes: VOLUME_TYPES,
volumeType: null,
zones: null,
zoneAutomatic: null,
didReceiveAttrs() {
const changes = {};
changes['volumeType'] = get(this, 'parameters.type') || 'pd-standard';
const zone = get(this, 'parameters.zone');
const zones = get(this, 'parameters.zones');
if ( zones && zones.length ) {
changes['zoneAutomatic'] = false;
changes['zones'] = zones;
} else if ( zone ) {
changes['zoneAutomatic'] = false;
changes['zones'] = zone;
} else {
changes['zoneAutomatic'] = true;
changes['zones'] = '';
}
setProperties(this, changes);
},
updateParams() {
const type = get(this, 'volumeType');
const out = { type, };
const zoneAutomatic = get(this, 'zoneAutomatic');
if ( !zoneAutomatic ) {
const zones = (get(this, 'zones') || '').trim();
if ( zones ) {
out['zones'] = zones;
}
}
set(this, 'parameters', out);
}
});
| 43,167
|
https://github.com/juanicastellan0/meli-sdk/blob/master/tests/MeliSdk/Test/Resource/LoggedUser/GetLoggedUserTest.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
meli-sdk
|
juanicastellan0
|
PHP
|
Code
| 76
| 384
|
<?php
namespace Tecnogo\MeliSdk\Test\Resource\LoggedUser;
use Tecnogo\MeliSdk\Client;
use Tecnogo\MeliSdk\Test\Resource\AbstractResourceTest;
use Tecnogo\MeliSdk\Test\Resource\CreateCallbackResponseGetRequest;
class GetLoggedUserTest extends AbstractResourceTest
{
use CreateCallbackResponseGetRequest;
/**
* @param Client $client
* @throws \Tecnogo\MeliSdk\Exception\ContainerException
* @throws \Tecnogo\MeliSdk\Exception\MissingConfigurationException
* @throws \Tecnogo\MeliSdk\Request\Exception\RequestException
*/
protected function triggerRequestForErrorResponses(Client $client)
{
$client->loggedUser()->raw();
}
/**
* @param $httpCode
* @param $response
* @return Client
* @throws \Tecnogo\MeliSdk\Exception\ContainerException
* @throws \Tecnogo\MeliSdk\Exception\MissingConfigurationException
* @throws \Tecnogo\MeliSdk\Site\Exception\InvalidSiteIdException
*/
protected function createClientForResponseErrorTest($httpCode, $response)
{
return $this->getClientWithFixedGetResponse($httpCode, $response, [
'app_id' => 'wubba_lubba_dub',
'access_token' => 'wubba_lubba_dub'
]);
}
}
| 50,020
|
https://github.com/r2d2rigo/Win2D/blob/master/winrt/test.internal/stubs/StubD2DDeviceContext.h
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
Win2D
|
r2d2rigo
|
C
|
Code
| 205
| 794
|
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
#pragma once
namespace canvas
{
class StubD2DDeviceContext : public MockD2DDeviceContext
{
ComPtr<ID2D1Device> m_owner;
ComPtr<ID2D1Image> m_target;
D2D1_BITMAP_PROPERTIES1* m_overrideProperties;
float m_dpiX;
float m_dpiY;
public:
StubD2DDeviceContext(ID2D1Device* owner = nullptr)
: m_owner(owner)
, m_overrideProperties(nullptr)
, m_dpiX(DEFAULT_DPI)
, m_dpiY(DEFAULT_DPI)
{
ClearMethod.AllowAnyCall();
SetDpiMethod.AllowAnyCall(
[=] (float x, float y)
{
m_dpiX = x;
m_dpiY = y;
});
GetDpiMethod.AllowAnyCall(
[=] (float* x, float* y)
{
*x = m_dpiX;
*y = m_dpiY;
});
GetImageLocalBoundsMethod.AllowAnyCall(
[](ID2D1Image*, D2D1_RECT_F*)
{
return S_OK;
});
SetTextAntialiasModeMethod.AllowAnyCall();
}
//
// Allows callers to pick which bitmap properties are set when a
// D2DBitmap is created. It's up to the caller to ensure that the
// D2D1_BITMAP_PROPERTIES1 pointed to remains valid for the duration.
//
void SetOverridePropertiesForCreateBitmap(D2D1_BITMAP_PROPERTIES1* properties)
{
m_overrideProperties = properties;
}
IFACEMETHODIMP_(void) GetDevice(ID2D1Device** device) const override
{
m_owner.CopyTo(device);
}
IFACEMETHODIMP_(void) BeginDraw() override
{
}
IFACEMETHODIMP EndDraw(D2D1_TAG *,D2D1_TAG *) override
{
return S_OK;
}
IFACEMETHODIMP_(void) SetTarget(ID2D1Image* theValue) override
{
m_target = theValue;
}
IFACEMETHODIMP_(void) GetTarget(ID2D1Image** theValue) const override
{
m_target.CopyTo(theValue);
}
IFACEMETHODIMP CreateBitmapFromDxgiSurface(
IDXGISurface* surface,
D2D1_BITMAP_PROPERTIES1 const* properties,
ID2D1Bitmap1** bitmap) override
{
auto overiddenProperties = m_overrideProperties ? m_overrideProperties : properties;
return Make<StubD2DBitmap>(surface, overiddenProperties).CopyTo(bitmap);
}
};
}
| 35,989
|
https://github.com/sod-21/flexdeck2/blob/master/templates/page-service.php
|
Github Open Source
|
Open Source
|
MIT
| null |
flexdeck2
|
sod-21
|
PHP
|
Code
| 283
| 1,059
|
<?php
/**
* Template Name: Show Child Pages
*/
get_header();
?>
<main id="primary" class="site-main">
<?php
while ( have_posts() ) :
the_post();
?>
<div data-section="1">
<div class="container">
<div class=" column is-10 is-offset-1">
<?php the_content(); ?>
</div>
</div>
</div>
<div data-section>
<div class="container">
<div class="columns is-multiline">
<?php
$industrys_count = get_field("show_count");
if ($industrys_count) {
$industrys_count = (int)$industrys_count;
} else {
$industrys_count = 9;
}
$parent = get_the_ID();
$industrys = get_posts( array(
"post_type" => "page",
'numberposts' => $industrys_count,
'order' => 'ASC',
'orderby' => 'title',
'post_status' => "publish",
"post_parent" => $parent
));
foreach ( $industrys as $post ) {
setup_postdata($post);
?>
<div class="column is-one-third-tablet">
<div class="industy-thumnail">
<div class="thumbnail">
<?php
$url = get_field("thumbnail_image");
if ($url) {
echo "<a class='image-overlay' href='" . get_the_permalink() . "'>";
sod_generate_image_tag( $url );
echo "</a>";
} else {
$url = get_the_post_thumbnail_url( $post->ID);
if ($url) {
echo "<a class='image-overlay' href='" . get_the_permalink() . "'>";
sod_generate_image_tag( $url );
echo "</a>";
}
}
?>
</div>
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
</div>
</div>
<?php
wp_reset_postdata();
}
?>
</div>
</div>
</div>
<?php
$platform_title = get_field("comercial_platform");
?>
<div data-section="3" class="bg-color2">
<div class="container">
<h2 class="comercial-title"><?php echo $platform_title; ?></h2>
<div class="columns is-multiline">
<?php
$platforms = get_field("platform__vairant");
if (!empty($platforms)):
foreach ($platforms as $p):
$icon = $p["icon"];
$title = $p["title"];
$content = $p["content"];
$url = $p["url"];
?>
<div class="column is-half-tablet">
<div class="c-content">
<div class="icon">
<a href="<?php echo $url; ?>">
<?php sod_generate_image_tag( $icon); ?>
</a>
</div>
<div class="content">
<h4><?php echo $title; ?></h4>
<p><?php echo $content; ?></p>
</div>
</div>
</div>
<?php endforeach;
endif;
?>
</div>
</div>
</div>
<?php
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
endwhile; // End of the loop.
?>
</main><!-- #main -->
<?php
get_footer();
| 1,802
|
https://github.com/messersm/bridges/blob/master/src/bridges/gui/BoardCanvas.java
|
Github Open Source
|
Open Source
|
MIT
| null |
bridges
|
messersm
|
Java
|
Code
| 2,087
| 4,954
|
package bridges.gui;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import bridges.game.Board;
import bridges.game.Island;
import bridges.model.GameModel;
import bridges.game.Bridge;
import bridges.game.Direction;
/**
* Represents the drawn board for the BridgesApp.
* <p>
* Enables the user to interact with the board
* (build and remove bridges).
*
* @author Maik Messerschmidt
*/
public class BoardCanvas extends Canvas implements Observer {
private GameModel game;
private int boardWidth = 0;
private int boardHeight = 0;
private Bridge selectedBridge = null;
private Bridge lastBridge = null;
private boolean displayMissing = false;
// Colors
private Color gridColor = Color.LIGHT_GRAY;
private Color islandColor = Color.GRAY;
private Color invalidIslandColor = Color.RED;
private Color completeIslandColor = Color.GREEN;
private Color textColor = Color.BLACK;
private Color displayMissingColor = Color.WHITE;
private Color bridgeColor = Color.BLACK;
private Color plannedBridgeColor = Color.BLUE;
private Color lastBridgeColor = Color.GREEN;
private Color invalidBridgeColor = Color.RED;
/*
* Margin to each side in pixel.
*/
final private int MARGIN = 10;
private int gridOffsetX = 0;
private int gridOffsetY = 0;
private float gridStep = 0;
private int gridDiameter = 0;
private int gridTolerance = 0;
/**
* Create a new BoardCanvas using the given game model.
*
* @param game - the game model to use.
*/
public BoardCanvas(GameModel game) {
super();
this.game = game;
game.addObserver(this);
/*
* Bind calculateGrid() to the resize event of this canvas
* in order to update the grid, island sizes, etc.
*/
this.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
BoardCanvas.this.calculateGrid();
}
});
// Enable user to build a bridge by left-clicking.
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
buildBridge(e.getX(), e.getY());
}
}
});
// Enable user to remove a bridge by right-clicking.
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3)
removeBridge(e.getX(), e.getY());
}
});
// Enable user to see a possible bridge.
this.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
selectBridge(e.getX(), e.getY());
}
});
}
/**
* Display a bridge at the given position, if
* one could be placed.
*
* @param mouseX - the x coordinate of the mouse.
* @param mouseY - the y coordinate of the mouse.
*/
private void selectBridge(int mouseX, int mouseY) {
// If a bridge is present select the
// present bridge. Build a new one otherwise.
Bridge newBridge = searchBridge(mouseX, mouseY);
if (newBridge == null)
newBridge = createBridge(mouseX, mouseY);
// Repaint the canvas, if the planned bridge changed.
if (selectedBridge == null) {
if (newBridge != null) {
selectedBridge = newBridge;
repaint();
}
} else if (!selectedBridge.equals(newBridge)) {
selectedBridge = newBridge;
repaint();
}
}
/**
* Place a bridge on the board at the given position,
* if possible.
*
* @param mouseX - the x coordinate of the mouse.
* @param mouseY - the y coordinate of the mouse.
*/
private void buildBridge(int mouseX, int mouseY) {
Bridge bridge = createBridge(mouseX, mouseY);
if (bridge != null) {
// If we want to allow crossing bridges,
// the isValid() check must be removed.
if (game.isValid(bridge)) {
game.addBridge(bridge);
}
}
}
/**
* Remove one bridge at the given mouse position.
* <br/><br/>
* This will turn a double bridge into a single
* bridge and completely remove a single bridge.
*
* @param mouseX - the x coordinate of the mouse.
* @param mouseY - the y coordinate of the mouse.
*/
private void removeBridge(int mouseX, int mouseY) {
Bridge bridge = searchBridge(mouseX, mouseY);
if (bridge != null) {
game.removeOneBridge(bridge);
}
}
public void displayMissing(boolean doDisplay) {
displayMissing = doDisplay;
repaint();
}
/**
* Return an island near the given pixel position or null.
*
* @param pixelX - the x coordinate.
* @param pixelY - the y coordinate.
* @return The island at the given position or null.
*/
private Island nearestIsland(int pixelX, int pixelY) {
Point boardPos = getBoardPosition(pixelX, pixelY);
return game.getIslandAt((int) boardPos.x, (int) boardPos.y);
}
/**
* Return a bridge, which can be build at the given position.
* (or null).
*
* @param mouseX - the x coordinate of the mouse.
* @param mouseY - the y coordinate of the mouse.
* @return A possible bridge at the given position or null.
*/
private Bridge createBridge(int mouseX, int mouseY) {
/*
* 1. If no board is given, return null.
* 2. Find an island near the given mouse position
* or return null.
* 3. Calculate the direction of the mouse position relative
* to the island position or return null.
* 4. Find a neighboring island in the given direction
* or return null.
* 5. Ensure there can be a bridge between the two islands
* added to the board or return null.
* 6. Return the bridge.
*/
if (!game.hasBoard())
return null;
Island island = nearestIsland(mouseX, mouseY);
if (island == null)
return null;
Point islandPos = getPixelPosition(island.getX(), island.getY());
Direction dir = getDirection(mouseX, mouseY, (int) islandPos.x, (int) islandPos.y);
if (dir == null)
return null;
return game.createBridge(island, dir);
}
/**
* Return a bridge, which is already built at the given position.
*
* @param mouseX - the x coordinate of the mouse.
* @param mouseY - the y coordinate of the mouse.
* @return The bridge at the given position or null.
*/
private Bridge searchBridge(int mouseX, int mouseY) {
if (!game.hasBoard())
return null;
Island island = nearestIsland(mouseX, mouseY);
if (island == null)
return null;
Point islandPos = getPixelPosition(island.getX(), island.getY());
Direction dir = getDirection(mouseX, mouseY, (int) islandPos.x, (int) islandPos.y);
if (dir == null)
return null;
List<Bridge> bridges = game.getBridges(island, dir);
if (bridges.isEmpty())
return null;
else
return bridges.get(0);
}
private Direction getDirection(int mouseX, int mouseY, int islandX, int islandY) {
int dx = mouseX - islandX;
int dy = mouseY - islandY;
if (Math.abs(dx) > 0 && Math.abs(dx) < gridTolerance
&& Math.abs(dy) > 0 && Math.abs(dy) < gridTolerance) {
return Direction.nearest(dx, dy);
} else
return null;
}
/**
* (Re)paints the board, that is: the grid, the bridges and the islands.
*/
@Override
public void paint(Graphics g) {
if (!game.hasBoard())
return;
paintGrid(g);
paintBridges(g);
paintIslands(g);
}
/**
* (Re)paint the grid.
*
* @param g - the Graphics instance to draw on.
*/
private void paintGrid(Graphics g) {
// draw grid
g.setColor(gridColor);
// horizontal lines
for (int y = 0; y < game.getHeight(); y++) {
Point p1 = this.getPixelPosition(0, y);
Point p2 = this.getPixelPosition(game.getWidth() - 1, y);
g.drawLine((int) p1.getX(), (int) p1.getY(), (int) p2.getX(), (int) p2.getY());
}
// vertical lines
for (int x = 0; x < game.getWidth(); x++) {
Point p1 = this.getPixelPosition(x, 0);
Point p2 = this.getPixelPosition(x, game.getHeight() - 1);
g.drawLine((int) p1.getX(), (int) p1.getY(), (int) p2.getX(), (int) p2.getY());
}
}
/**
* (Re)paint the islands.
*
* @param g - the Graphics instance to draw on.
*/
private void paintIslands(Graphics g) {
for (Island island : game.getIslands()) {
int required = island.getRequiredBridges();
int count = Bridge.count(game.getBridges(island));
String label;
Color labelColor;
if (displayMissing) {
label = Integer.toString(required - count);
labelColor = displayMissingColor;
} else {
label = Integer.toString(required);
labelColor = textColor;
}
if (count < required)
paintIsland(g, island, islandColor, label, labelColor);
else if (count == required)
paintIsland(g, island, completeIslandColor, label, labelColor);
else
paintIsland(g, island, invalidIslandColor, label, labelColor);
}
}
/**
* Draw a single island.
*
* @param g - the Graphics instance to draw on.
* @param island - the island to draw.
* @param color - the color to draw the island in.
* @param label - the label to draw over the island.
* @param labelColor - the color of the label.
*/
private void paintIsland(Graphics g, Island island, Color color, String label, Color labelColor) {
Point p = getPixelPosition(island.getX(), island.getY());
int x = (int) p.getX() - gridDiameter / 2;
int y = (int) p.getY() - gridDiameter / 2;
g.setColor(color);
g.fillArc(x, y, gridDiameter, gridDiameter, 0, 360);
g.setColor(labelColor);
drawCenteredString(g, label, (int) p.getX(), (int) p.getY(), labelColor);
}
/**
* Draw a single bridge.
*
* @param g - the Graphics instance to draw on.
* @param bridge - the bridge to draw.
* @param color - the color to draw the bridge in.
*/
private void paintBridge(Graphics g, Bridge bridge, Color color) {
Island island1 = bridge.getFirstIsland();
Island island2 = bridge.getSecondIsland();
Point p1 = getPixelPosition(island1.getX(), island1.getY());
Point p2 = getPixelPosition(island2.getX(), island2.getY());
int dx;
int dy;
if (bridge.isDouble()) {
// vertical double bridge
if (island1.getX() == island2.getX()) {
dx = gridDiameter / 6;
dy = 0;
}
// horizontal double bridge
else {
dx = 0;
dy = gridDiameter / 6;
}
g.setColor(color);
g.drawLine((int) p1.getX() - dx, (int) p1.getY() - dy, (int) p2.getX() - dx, (int) p2.getY() - dy);
g.drawLine((int) p1.getX() + dx, (int) p1.getY() + dy, (int) p2.getX() + dx, (int) p2.getY() + dy);
} else {
g.setColor(color);
g.drawLine((int) p1.getX(), (int) p1.getY(),
(int) p2.getX(), (int) p2.getY());
}
}
/**
* (Re)paint all bridges.
*
* @param g - the Graphics instance to draw the bridges on.
*/
private void paintBridges(Graphics g) {
for (Bridge bridge : game.getBridges())
paintBridge(g, bridge, bridgeColor);
// Draw the last bridge over the already drawn bridges.
if (lastBridge != null)
paintBridge(g, lastBridge, lastBridgeColor);
// Draw the planned Bridge over every other bridges.
if (selectedBridge != null)
if (game.isValid(selectedBridge))
paintBridge(g, selectedBridge, plannedBridgeColor);
else
paintBridge(g, selectedBridge, invalidBridgeColor);
}
/**
* Helper method, that draws a String centered around the given position.
*
* @param g - the Graphics instance to draw on.
* @param text - the String to draw.
* @param pixelX - the x coordinate.
* @param pixelY - the y coordinate.
* @param labelColor - the color of the text to draw.
*/
private void drawCenteredString(Graphics g, String text, int pixelX, int pixelY, Color labelColor) {
FontMetrics metrics = g.getFontMetrics();
int width = metrics.stringWidth(text);
int height = metrics.getAscent();
g.setColor(labelColor);
g.drawString(text, pixelX - width / 2, pixelY + height / 2);
}
/**
* Return the centered pixel position of the given board position.
*
* @param boardX - the x coordinate on the board.
* @param boardY - the y coordinate on the board.
* @return The point which represents the given board position on the screen.
*/
private Point getPixelPosition(int boardX, int boardY) {
int x = (int) (MARGIN + gridOffsetX + boardX * gridStep);
int y = (int) (MARGIN + gridOffsetY + boardY * gridStep);
return new Point(x, y);
}
/**
* Return the board position of a given screen position.
*
* @param pixelX - the x coordinate of the screen position.
* @param pixelY - the y coordinate of the screen position.
* @return The point which represents the given pixel position on the board.
*/
private Point getBoardPosition(int pixelX, int pixelY) {
int x = Math.round((pixelX - MARGIN - gridOffsetX) / gridStep);
int y = Math.round((pixelY - MARGIN - gridOffsetY) / gridStep);
return new Point(x, y);
}
/**
* (Re)calculate the board grid.
* <br/><br/>
* Called, when this Canvas is resized.
*/
private void calculateGrid() {
// Get the width and height of the board and
// recalculate the grid.
boardWidth = game.getWidth();
boardHeight = game.getHeight();
int availableWidth = getWidth() - MARGIN * 2;
int availableHeight = getHeight() - MARGIN * 2;
int spacesX = boardWidth;
int spacesY = boardHeight;
float stepX = (float) availableWidth / spacesX;
float stepY = (float) availableHeight / spacesY;
// Set the distance between grid lines to the minimum of available space,
// so the grid fits in x as well as in y direction on the screen.
if (stepX > stepY) {
gridStep = stepY;
gridOffsetX = (int) (availableWidth - gridStep * spacesX) / 2;
gridOffsetY = (int) gridStep / 2;
} else {
gridStep = stepX;
gridOffsetX = (int) gridStep / 2;
gridOffsetY = (int) (availableHeight - gridStep * spacesY) / 2;
}
gridDiameter = (int) (gridStep * 2) / 3;
gridTolerance = (int) gridStep - 1;
// System.out.println("MARGIN: " + MARGIN);
// System.out.println("offsetX: " + gridOffsetX);
// System.out.println("offsetY: " + gridOffsetY);
// System.out.println("Board width (pixel): " + (int) gridStep * spacesX);
// System.out.println("Board height (pixel): " + (int) gridStep * spacesY);
// System.out.println("total width: " + getWidth());
// System.out.println("total height: " + getHeight());
// System.out.println("step: " + gridStep);
}
/**
* Update the BoardCanvas after the game model has been changed.
*
* @param game - the game model, that has been changed.
* @param obj - the changed bridge (or null).
*/
@Override
public void update(Observable game, Object obj) {
if (obj instanceof Bridge)
lastBridge = (Bridge) obj;
else
lastBridge = null;
// Deselect bridge.
selectedBridge = null;
// We have to call calculateGrid, since the whole
// board could have been replaced with a new one.
calculateGrid();
repaint();
}
}
| 982
|
https://github.com/dydzio0614/dydutility/blob/master/dydutilityTests/UtilityTests.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
dydutility
|
dydzio0614
|
C#
|
Code
| 35
| 125
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using dydutility;
namespace dydutility.Tests
{
[TestClass]
public class UtilityTests
{
[TestMethod]
public void TestUtility()
{
Utility test = new Utility();
Assert.AreEqual<string>(test.RemoveColorModifiers("^0Te^2st^1^0 test^22 ^ 2"), "Test test2 ^ 2");
}
}
}
| 14,933
|
https://github.com/byzhang/viaduct/blob/master/compiler/src/main/kotlin/edu/cornell/cs/apl/viaduct/util/Lists.kt
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
viaduct
|
byzhang
|
Kotlin
|
Code
| 162
| 389
|
package edu.cornell.cs.apl.viaduct.util
/**
* Returns the list of all pairs where the first element is from [this] list,
* and the second element is from [other].
*/
internal fun <A, B> List<A>.pairedWith(other: List<B>): List<Pair<A, B>> {
val result = mutableListOf<Pair<A, B>>()
for (a in this) {
for (b in other) {
result += Pair(a, b)
}
}
return result
}
/** Returns all subsequences of this list sorted from the smallest in size to the largest. */
internal fun <E> List<E>.subsequences(): Iterable<List<E>> {
val result = mutableListOf<List<E>>()
for (i in 0..this.size) {
result += this.subsequences(i)
}
return result
}
/** Returns all subsequences of this list of length [length]. */
// TODO: this can be sped up with dynamic programming.
private fun <E> List<E>.subsequences(length: Int): Iterable<List<E>> =
when {
length == 0 ->
listOf(listOf())
length == this.size ->
listOf(this)
length > this.size ->
listOf()
else ->
this.drop(1).let {
it.subsequences(length - 1).map { s -> listOf(this.first()) + s } +
it.subsequences(length)
}
}
| 34,636
|
https://github.com/met5678/dmx-goddess/blob/master/device.js
|
Github Open Source
|
Open Source
|
MIT
| null |
dmx-goddess
|
met5678
|
JavaScript
|
Code
| 219
| 731
|
var serialPort = require('serialport');
var onExit = require('signal-exit');
var START_VAL = 0x7E;
var MSG_TYPE_DMX_OUT = 0x06;
var DMX_STARTCODE = 0x00;
var END_VAL = 0xE7;
var fps = 40;
var dmxPro;
var open = false;
var portOpen = function(err) {
console.log('OPEN');
open = true;
setInterval(dmxLoop, 1000/fps);
}
var portError = function(err) {
console.log('DMX Device error',err);
};
var portClose = function(err) {
open = false;
console.log('DMX Device close',err);
};
var initPort = function(port) {
dmxPro = new serialPort.SerialPort(port.comName, {
baudrate: 57600,
stopBits: 2
});
dmxPro.on('open', portOpen);
dmxPro.on('error', portError);
dmxPro.on('close', portClose);
};
onExit(function() {
if(open) {
console.log('AUTO CLOSING');
dmxPro.close();
}
});
var findAndConnect = function() {
serialPort.list(function (err, ports) {
ports.forEach(function(port) {
console.log(port);
if(port.manufacturer == 'DMXking.com') {
initPort(port);
}
});
});
};
var sendBuffer;
var channels = 0;
var prepareBuffer = function() {
sendBuffer = new Buffer(channels+6);
sendBuffer.fill(0x00);
sendBuffer[0] = START_VAL;
sendBuffer[1] = MSG_TYPE_DMX_OUT;
sendBuffer[2] = (channels+1) & 0xFF;
sendBuffer[3] = (channels+1) >> 8;
sendBuffer[4] = DMX_STARTCODE;
sendBuffer[5 + channels] = END_VAL;
}
var setChannels = function(inBuffer) {
if(inBuffer.length > 512) {
console.log('Too many channels');
return;
}
if(inBuffer.length != channels) {
channels = inBuffer.length;
prepareBuffer();
}
inBuffer.copy(sendBuffer,5);
}
var dmxLoop = function() {
if(sendBuffer && sendBuffer.length > 0) {
dmxPro.write(sendBuffer, onSend);
}
};
var onSend = function(error) {
if(error) {
console.log('Error on SEND',error);
}
};
findAndConnect();
module.exports = {
setChannels: setChannels
};
| 35,598
|
https://github.com/harleydk/dotnet-sftpclient/blob/master/SFTPcommandlineClient/UtilityClasses/FileAvailabilityChecker.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
dotnet-sftpclient
|
harleydk
|
C#
|
Code
| 272
| 868
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
namespace DotNetSftp.UtilityClasses
{
/// <summary>
/// Checks if a file is available and ready to be read.
/// </summary>
/// <remarks>
/// Cannot take credit for this code: thanks, https://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use !
/// </remarks>
public class FileAvailabilityChecker
{
private const int ERROR_SHARING_VIOLATION = 32;
private const int ERROR_LOCK_VIOLATION = 33;
private bool IsFileLocked(Exception exception)
{
int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);
return errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION;
}
/// <summary>
/// Checks the availability of a single file.
/// </summary>
/// <param name="filePath">The path to the file.</param>
/// <returns>A FileAvailabilityCheck object, that informs us of the file's availability at the time the function was run.</returns>
public FileAvailabilityCheck CheckFileAvailability(string filePath)
{
try
{
//The "using" is important because FileStream implements IDisposable and
//"using" will avoid a heap exhaustion situation when too many handles
//are left undisposed.
using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
FileAvailabilityCheck fileWasAvailable = new FileAvailabilityCheck
{
FileName = filePath,
FileAvailabilityResult = FileAvailabilityResult.IsReadable,
Description =
$"At {DateTime.Now.ToShortTimeString()}, {Path.GetFileName(filePath)} was available."
};
return fileWasAvailable;
}
}
catch (IOException ex)
{
if (IsFileLocked(ex))
{
FileAvailabilityCheck notAvailableBecauseLocked = new FileAvailabilityCheck
{
FileName = filePath,
FileAvailabilityResult = FileAvailabilityResult.IsLockedOrShared,
Description =
$"At {DateTime.Now.ToShortTimeString()}, {Path.GetFileName(filePath)} was locked or shared."
};
return notAvailableBecauseLocked;
}
FileAvailabilityCheck notAvailableBecauseOfIoException = new FileAvailabilityCheck
{
FileName = filePath,
FileAvailabilityResult = FileAvailabilityResult.IsLockedOrShared,
Description =
$"At {DateTime.Now.ToShortTimeString()}, {Path.GetFileName(filePath)} was not available. Error: '{ex.Message}'."
};
return notAvailableBecauseOfIoException;
}
catch (UnauthorizedAccessException authEx)
{
FileAvailabilityCheck notavailableBecauseOfAuthenticationProblem = new FileAvailabilityCheck
{
FileName = filePath,
FileAvailabilityResult = FileAvailabilityResult.AccessDenied,
Description = $"At {DateTime.Now.ToShortTimeString()}, {Path.GetFileName(filePath)} was not available. Error: '{authEx.Message}'."
};
return notavailableBecauseOfAuthenticationProblem;
}
}
}
}
| 48,146
|
https://github.com/krung2/DB_Server/blob/master/src/like/like.controller.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
DB_Server
|
krung2
|
TypeScript
|
Code
| 94
| 323
|
import { Controller, Delete, Param, Post, Query, UseGuards } from '@nestjs/common';
import { Token } from 'src/libs/decorator/token.decorator';
import { IUser } from 'src/libs/interface/IUser';
import { returnLib } from 'src/libs/return.lib';
import AuthGaurd from 'src/middleware/auth.middleware';
import { LikeService } from './like.service';
@Controller('like')
export class LikeController {
constructor(
private readonly likeService: LikeService,
) { }
@Post('/:idx')
async addLike(
@Query('token') token: string,
@Param('idx') idx: number,
) {
await this.likeService.addLike(token, idx);
return returnLib(201, '좋아요 성공');
}
@Delete('/:idx')
@UseGuards(new AuthGaurd())
async delLike(
@Token() tokenUser: IUser,
@Param('idx') idx: number,
) {
await this.likeService.delLike(tokenUser, idx);
return returnLib(200, '좋아요 삭제 성공');
}
}
| 6,071
|
https://github.com/SerhiyShamshetdinov/sugar-bms/blob/master/sugar-bms/src/main/scala/sands/sugar/bms/typeclass/BooleanMonad.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
sugar-bms
|
SerhiyShamshetdinov
|
Scala
|
Code
| 475
| 1,311
|
/*
* Statements and Logical Operators on Boolean Monads and Collections
*
* Copyright (c) 2021 Serhiy Shamshetdinov (Kyiv, Ukraine)
*
* 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.
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership and used works.
*/
package sands.sugar.bms.typeclass
import sands.sugar.bms.typeclass.functions._
import sands.sugar.bms.typeclass.instances._
import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.ClassTag
/*
* Created by Serhiy Shamshetdinov
* at 27.07.2021 17:43
*/
trait BooleanMonad[M[_], C] extends BooleanFunctions[M, C] {
def pure[A](a: A): M[A]
val False: M[Boolean] = pure(false)
val True: M[Boolean] = pure(true)
val Unit: M[Unit] = pure[Unit]({})
def map[A, B](ma: M[A], f: A => B)(implicit c: C): M[B]
def flatMap[A, B](ma: M[A], f: A => M[B])(implicit c: C): M[B]
/** returns monadic predicate which stopped the loop: "zero"-elements (error, empty, None, etc.) or one-element `false` inside a monad */
def tailRecLoop(bodyWithCondition: => M[Boolean])(implicit c: C): M[Boolean]
/** Used as predicate of `mIf` & `fmIf` statements and loops. For single element monads it is `identity`.
* For collections it returns reduced collection (1 or 0 elements) with 'true' if collection contains 'true'.
*
* Override it to use another mapping of collection to monadic predicate.
*/
def toMonadicPredicate(mb: M[Boolean])(implicit c: C): M[Boolean] = mb // only for single element monads: override it for collections
}
object BooleanMonad {
def apply[M[_]](implicit BM: BooleanMonad[M, NoContext]): BooleanMonad[M, NoContext] = BM
def apply[M[_], C](implicit BM: BooleanMonad[M, C], c: C): BooleanMonad[M, C] = BM
implicit val futureBooleanMonad: BooleanMonad[Future, ExecutionContext] = new FutureBooleanMonad with SingleElementMonadBooleanFunctions[Future, ExecutionContext]
implicit val listZippingBooleanMonad: BooleanCollectionMonad[List, NoContext] = new ListBooleanCollectionMonad with ZippingCollectionBooleanFunctions[List, NoContext]
implicit val seqZippingBooleanMonad: BooleanCollectionMonad[Seq, NoContext] = new SeqBooleanCollectionMonad with ZippingCollectionBooleanFunctions[Seq, NoContext]
implicit val indexedSeqZippingBooleanMonad: BooleanCollectionMonad[IndexedSeq, NoContext] = new IndexedSeqBooleanCollectionMonad with ZippingCollectionBooleanFunctions[IndexedSeq, NoContext]
implicit val vectorZippingBooleanMonad: BooleanCollectionMonad[Vector, NoContext] = new VectorBooleanCollectionMonad with ZippingCollectionBooleanFunctions[Vector, NoContext]
implicit val iterableZippingBooleanMonad: BooleanCollectionMonad[Iterable, NoContext] = new IterableBooleanCollectionMonad with ZippingCollectionBooleanFunctions[Iterable, NoContext]
implicit val streamZippingBooleanMonad: BooleanCollectionMonad[Stream, NoContext] = new StreamBooleanCollectionMonad with ZippingCollectionBooleanFunctions[Stream, NoContext]
object CollectionsAsMonad {
implicit val listBooleanMonad: BooleanCollectionMonad[List, NoContext] = new ListBooleanCollectionMonad with MonadicCollectionBooleanFunctions[List, NoContext]
implicit val seqBooleanMonad: BooleanCollectionMonad[Seq, NoContext] = new SeqBooleanCollectionMonad with MonadicCollectionBooleanFunctions[Seq, NoContext]
implicit val indexedSeqBooleanMonad: BooleanCollectionMonad[IndexedSeq, NoContext] = new IndexedSeqBooleanCollectionMonad with MonadicCollectionBooleanFunctions[IndexedSeq, NoContext]
implicit val vectorBooleanMonad: BooleanCollectionMonad[Vector, NoContext] = new VectorBooleanCollectionMonad with MonadicCollectionBooleanFunctions[Vector, NoContext]
implicit val iterableBooleanMonad: BooleanCollectionMonad[Iterable, NoContext] = new IterableBooleanCollectionMonad with MonadicCollectionBooleanFunctions[Iterable, NoContext]
implicit val streamBooleanMonad: BooleanCollectionMonad[Stream, NoContext] = new StreamBooleanCollectionMonad with MonadicCollectionBooleanFunctions[Stream, NoContext]
implicit val arrayMonadicBooleanFunctions: BooleanFunctions[Array, ClassTag[Boolean]] = sands.sugar.bms.typeclass.functions.BooleanFunctions.ArrayAsMonad.arrayMonadicBooleanFunctions
}
}
| 8,161
|
https://github.com/naimishmakawana/b2b/blob/master/resources/views/B2BCustomer/edit.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
b2b
|
naimishmakawana
|
PHP
|
Code
| 449
| 2,328
|
@extends('layouts.b2b')
@section('content')
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="card">
{!! Form::model($B2BCustomer, ['method' => 'PATCH','class'=>'form-horizontal','route' => ['B2BCustomer.update', $B2BCustomer->CustomerId]]) !!}
<div class="card-header card-header-text">
<h4 class="card-title">Edit B2B Customer</h4>
</div>
<div class="card-content">
<input type="hidden" name="flag" value="{{ Request::get('flag') }}" />
<!-- <input type="hidden" name="ApplicationOwnerOwnerId" value="1" /> -->
<div class="row">
<label class="col-sm-7 label-on-left">Application Owner : {{$ApplicationOwner->NameOfOrganization}}</label>
</div>
<div class="row">
<label class="col-sm-3 label-on-left">Customer Name</label>
<div class="col-sm-7">
<div class="form-group label-floating">
<label class="control-label"></label>
<input class="form-control" type="text" name="NameOfOrganization" required="true" value="{{$B2BCustomer->NameOfOrganization}}" />
</div>
</div>
<label class="col-sm-2 label-on-right">
<code>required</code>
</label>
</div>
<div class="row">
<label class="col-sm-3 label-on-left">Address Line 1</label>
<div class="col-sm-7">
<div class="form-group label-floating">
<label class="control-label"></label>
<input class="form-control" type="text" name="AddressFirstLine" value="{{$B2BCustomer->AddressFirstLine}}"/>
</div>
</div>
<label class="col-sm-2 label-on-right">
<code>required</code>
</label>
</div>
<div class="row">
<label class="col-sm-3 label-on-left">Address Line 2</label>
<div class="col-sm-7">
<div class="form-group label-floating">
<label class="control-label"></label>
<input class="form-control" type="text" name="AddressSecondLine" value="{{$B2BCustomer->AddressSecondLine}}"/>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-3 label-on-left">City</label>
<div class="col-sm-7">
<div class="form-group label-floating">
<label class="control-label"></label>
<input class="form-control" type="text" name="City" value="{{$B2BCustomer->City}}"/>
</div>
</div>
<label class="col-sm-2 label-on-right">
<code>required</code>
</label>
</div>
<div class="row">
<label class="col-sm-3 label-on-left">State</label>
<div class="col-sm-7">
<div class="form-group label-floating">
<label class="control-label"></label>
<input class="form-control" type="text" name="State" value="{{$B2BCustomer->State}}"/>
</div>
</div>
<label class="col-sm-2 label-on-right">
<code>required</code>
</label>
</div>
<div class="row">
<label class="col-sm-3 label-on-left">Country</label>
<div class="col-sm-7" >
<div class="form-group label-floating">
<select name="CountryId" class="form-control">
@foreach ($Countries as $key => $value)
@if ($value->id == $B2BCustomer->CountryId)
<option selected="selected" value="{{ $value->id }}">{{ $value->CountryName }}</option>
@else
<option value="{{ $value->id }}">{{ $value->CountryName }}</option>
@endif
@endforeach
</select>
</div>
</div>
<label class="col-sm-2 label-on-right">
<code>required</code>
</label>
</div>
<div class="row">
<label class="col-sm-3 label-on-left">Zip/Postal Code</label>
<div class="col-sm-7">
<div class="form-group label-floating">
<label class="control-label"></label>
<input class="form-control" type="text" name="PostalCode" value="{{$B2BCustomer->PostalCode}}" maxlength="10"/>
</div>
</div>
<label class="col-sm-2 label-on-right">
<code>required</code>
</label>
</div>
<div class="row">
<label class="col-sm-3 label-on-left">Contact Person First Name</label>
<div class="col-sm-7">
<div class="form-group label-floating">
<label class="control-label"></label>
<input class="form-control" type="text" name="ContactPersonFirstName" value="{{$B2BCustomer->ContactPersonFirstName}}"/>
</div>
</div>
<label class="col-sm-2 label-on-right">
<code>required</code>
</label>
</div>
<div class="row">
<label class="col-sm-3 label-on-left">Contact Person Last Name</label>
<div class="col-sm-7">
<div class="form-group label-floating">
<label class="control-label"></label>
<input class="form-control" type="text" name="ContactPersonLastName" value="{{$B2BCustomer->ContactPersonLastName}}"/>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-3 label-on-left">Contact E-mail Address</label>
<div class="col-sm-7">
<div class="form-group label-floating">
<label class="control-label"></label>
<input class="form-control" type="text" name="ContactPersonEmailAddress" value="{{$B2BCustomer->ContactPersonEmailAddress}}" />
</div>
</div>
<label class="col-sm-2 label-on-right">
<code>required</code>
</label>
</div>
<div class="row">
<label class="col-sm-3 label-on-left">Contact Person Designation</label>
<div class="col-sm-7">
<div class="form-group label-floating">
<label class="control-label"></label>
<input class="form-control" type="text" name="ContactPersonDesignation" value="{{$B2BCustomer->ContactPersonDesignation}}" />
</div>
</div>
<label class="col-sm-2 label-on-right">
<code>required</code>
</label>
</div>
<div class="row">
<label class="col-sm-3 label-on-left">Active Status</label>
<div class="col-sm-7">
<div class="form-group label-floating">
<label class="control-label"></label>
<div class="checkbox">
<label class="col-md-2">
@if ($B2BCustomer->ActiveStatus == 1)
<input type="checkbox" name="ActiveStatus" value="1" checked="checked"></input>
@else
<input type="checkbox" name="ActiveStatus" value="1"></input>
@endif
</label>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-2 col-md-offset-5">
<button class="btn btn-primary">Submit</button>
</div>
</div>
</div>
<div class="card-footer text-center">
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
@endsection
| 25,594
|
https://github.com/6d6a/hms-personmgr/blob/master/src/main/java/ru/majordomo/hms/personmgr/dto/alerta/AlertaResponse.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
hms-personmgr
|
6d6a
|
Java
|
Code
| 30
| 114
|
package ru.majordomo.hms.personmgr.dto.alerta;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
@Getter
@Setter
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class AlertaResponse extends AlertaResponseStatus {
private String id;
private AlertDto alert;
}
| 50,301
|
https://github.com/buberwa88/iLMS_Repayment/blob/master/backend/modules/report/controllers/ReportController.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
iLMS_Repayment
|
buberwa88
|
PHP
|
Code
| 3,588
| 15,201
|
<?php
namespace backend\modules\report\controllers;
use Yii;
use backend\modules\report\models\Report;
use backend\modules\report\models\ReportSearch;
//use yii\web\Controller;
use common\components\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use mPDF;
/**
* ReportController implements the CRUD actions for Report model.
*/
class ReportController extends Controller {
/**
* @inheritdoc
*/
public $layout = "main_private";
public function behaviors() {
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Report models.
* @return mixed
*/
public function actionIndex() {
$searchModel = new ReportSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionAllReports() {
$searchModel = new ReportSearch();
$dataProvider = $searchModel->searchAllReportFilter(Yii::$app->request->queryParams);
return $this->render('all_reports', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Report model.
* @param string $id
* @return mixed
*/
public function actionView($id) {
$searchModel = new ReportSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('view', [
'model' => $this->findModel($id),
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionViewOperation($id){
$searchModel = new ReportSearch();
$dataProvider = $searchModel->searchAllReportFilter(Yii::$app->request->queryParams);
return $this->render('viewOperation', [
'model' => $this->findModel($id),
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Creates a new Report model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate() {
$model = new Report();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
// var_dump(Yii::$app->request->post());
// exit;
$model->file_name = UploadedFile::getInstance($model, 'file_name');
if ($model->file_name != NULL && $model->file_name != '') {
$report_template_nme=Yii::$app->params['reportTemplate'] . $model->file_name;
//$model->file_name->saveAs(chmod($report_template_nme,0777));
$model->file_name->saveAs($report_template_nme);
$extension = explode(".", $model->file_name);
$model->file_name = $extension[0];
}
if ($model->save()) {
$sms = "<p>Report Created Successful</p>";
Yii::$app->getSession()->setFlash('success', $sms);
return $this->redirect(['index']);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Report model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param string $id
* @return mixed
*/
public function actionUpdate($id) {
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->file_name = UploadedFile::getInstance($model, 'file_name');
if ($model->file_name != NULL && $model->file_name != '') {
$model->file_name->saveAs(Yii::$app->params['reportTemplate'] . $model->file_name);
//$fileField="_formEmployerVerificationCode.php";
$extension = explode(".", $model->file_name);
$model->file_name = $extension[0];
} else {
$getDetails = \backend\modules\report\models\Report::findOne($id);
$model->file_name = $getDetails->file_name;
}
if ($model->save()) {
$sms = "<p>Information Updated Successful</p>";
Yii::$app->getSession()->setFlash('success', $sms);
return $this->redirect(['index']);
}
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Report model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param string $id
* @return mixed
*/
public function actionDelete($id) {
$this->findModel($id)->delete();
\backend\modules\report\models\ReportAccess::deleteAll(['report_id' => $id]);
\backend\modules\report\models\PopularReport::deleteAll(['report_id' => $id]);
return $this->redirect(['index']);
}
/**
* Finds the Report model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param string $id
* @return Report the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id) {
if (($model = Report::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
public function actionPrintReport() {
// $generatedBy = "Printed By " . Yii::$app->user->identity->firstname . " " . Yii::$app->user->identity->surname;
$generatedBy = NULL;
$searchParams = array();
$model = new Report();
//$model->scenario='exportReport';
if ($model->load(Yii::$app->request->post())) {
//var_dump($model->attributes);
// exit;
$category = $model->category;
$id = $model->uniqid;
/*
if (isset($_POST['Report'])) {
$posted_data = Yii::$app->request->post();
$actions = $posted_data['Report']['pageRedirect'];
}
*/
$actions = $model->pageRedirect;
$pageIdentify = $model->pageIdentify;
$exportCategory = $model->exportCategory;
$export_mode = $model->export_mode;
$modelReportTemplate = Report::findOne($id);
$sql = $modelReportTemplate->sql;
$sql_subquery = $modelReportTemplate->sql_subquery;
//return $sql;
$where = $subquery_where = '';
$reportFilter = '';
$reportFilterFinal = '';
$applicantCategorySet = '';
if (!empty($modelReportTemplate->sql_where)) {
$where = ' where ' . $modelReportTemplate->sql_where;
}
if (!empty($modelReportTemplate->sql_subquery_where)) {
$subquery_where = ' where ' . $modelReportTemplate->sql_subquery_where;
}
$results = \backend\modules\report\models\ReportFilterSetting::find()
->select('number_of_rows')
->where(['is_active' => '1'])
->orderBy(['report_filter_setting_id' => SORT_DESC])
->one();
//$number_of_rows=$results->number_of_rows;
$number_of_rows = 15;
for ($i = 1; $i <= $number_of_rows; $i++) {
$attr = 'input' . $i;
$column = 'column' . $i;
$condition = 'condition' . $i;
$type = 'type' . $i;
$field = 'field' . $i;
$typeValue = $modelReportTemplate->$type;
$attrValue = $model->$attr;
//if($attr==input3){
//echo $attrValue;exit;
//}
$conditionValue = $modelReportTemplate->$condition;
$columnValue = $modelReportTemplate->$column;
$fieldValue = $modelReportTemplate->$field;
if ($attrValue !='') {
$value = $model->$attr;
if ($typeValue == 'date')
$value = date('Y-m-d', strtotime($value));
if ($conditionValue == 'like') {
$mysearch = "$columnValue $conditionValue '%" . $value . "%'";
$reportFilter = "$fieldValue $conditionValue $value AND ";
} else {
$mysearch = "$columnValue $conditionValue '$value'";
if ($typeValue == 'date') {
$reportFilter = "$fieldValue $value AND ";
} else {
if ($typeValue == 'applicant_category') {
$applicantCategory = \backend\modules\application\models\ApplicantCategory::findOne($value);
$reportFilter = "$fieldValue : $applicantCategory->applicant_category AND ";
$applicantCategorySet = $value;
$searchParams['applicant_category'] = $value;
} else if ($typeValue == 'sex') {
if ($value == 'M') {
$reportFilter = "$fieldValue : Male AND ";
} else {
$reportFilter = "$fieldValue : Female AND ";
}
$searchParams['sex'] = $value;
} else if ($typeValue == 'institution') {
$institution_name = \frontend\modules\application\models\LearningInstitution::findOne($value);
$reportFilter = "$fieldValue : $institution_name->institution_code AND ";
$searchParams['sex'] = $value;
} else if ($typeValue == 'loan_item') {
$item_name = \backend\modules\allocation\models\LoanItem::findOne($value);
$reportFilter = "$fieldValue : $item_name->item_name AND ";
$searchParams['loan_item']=$value;
} else if ($typeValue == 'country') {
$country_name = \frontend\modules\application\models\Country::findOne($value);
$reportFilter = "$fieldValue : $country_name->country_name AND ";
$searchParams['country']=$value;
} else if ($typeValue == 'programme_group') {
$group_name = \backend\modules\allocation\models\ProgrammeGroup::findOne($value);
$reportFilter = "$fieldValue : $group_name->group_name AND ";
$searchParams['programme_group']=$value;
} else if ($typeValue == 'scholarship_type') {
$scholarship_name = \backend\modules\allocation\models\ScholarshipDefinition::findOne($value);
$reportFilter = "$fieldValue : $scholarship_name->scholarship_name AND ";
$searchParams['scholarship_type']=$value;
} else if ($typeValue == 'academic_year') {
$academic_year = \common\models\AcademicYear::findOne($value);
$reportFilter = "$fieldValue : $academic_year->academic_year AND ";
$searchParams['academic_year']=$value;
} else if ($typeValue == 'allocation_batch') {
$allocation_batch = \backend\modules\allocation\models\AllocationBatch::findOne($value);
$reportFilter = "$fieldValue : $allocation_batch->batch_number AND ";
$searchParams['allocation_batch']=$value;
}else if ($typeValue == 'form_storage') {
$formStorage = \common\models\FormStorage::findOne($value);
$reportFilter = "$fieldValue : $formStorage->folder_number AND ";
$searchParams['folder_number']=$value;
}else if ($typeValue == 'user') {
$userVal = \common\models\User::findOne($value);
$nameUser=$userVal->firstname." ".$userVal->surname;
$reportFilter = "$fieldValue : $nameUser AND ";
$searchParams['user_id']=$value;
}else if ($typeValue == 'gspp_employees_status') {
if($value==0){
$reportFilter = "$fieldValue : Pending AND ";
$searchParams['gspp_employees_status']=$value;
}else if($value==1){
$reportFilter = "$fieldValue : Beneficiary not onrepayment AND ";
$searchParams['gspp_employees_status']=$value;
}else if($value==2){
$reportFilter = "$fieldValue : Beneficiary onrepayment AND ";
$searchParams['gspp_employees_status']=$value;
}else if($value==3){
$reportFilter = "$fieldValue : Nonbeneficiary AND ";
$searchParams['gspp_employees_status']=$value;
}else if($value==4){
$reportFilter = "$fieldValue : Checked employee onrepayment AND ";
$searchParams['gspp_employees_status']=$value;
}
}else if ($typeValue == 'payer_type_employer_treasury') {
if($value==0){
$reportFilter = "$fieldValue : Self Employer AND ";
$searchParams['payer_type_employer_treasury']=$value;
}else if($value==1){
$reportFilter = "$fieldValue : Treasury AND ";
$searchParams['payer_type_employer_treasury']=$value;
}
} else {
$reportFilter = "$fieldValue : $value AND ";
}
}
//$mysearch = "$columnValue $conditionValue '%".$value."%'";
}
if (empty($where)) {
$where = " where $mysearch";
$reportFilterFinal = $reportFilter;
} else {
$where .= " and $mysearch";
$reportFilterFinal.=$reportFilter;
}
if (empty($subquery_where)) {
$subquery_where = " where $mysearch";
} else {
$subquery_where .= " and $mysearch";
}
}
}
$sql .= ' ' . $where;
$sql_subquery .= ' ' . $subquery_where;
if (!empty($modelReportTemplate->sql_group)) {
$sql .= ' group by ' . $modelReportTemplate->sql_group;
}
if (!empty($modelReportTemplate->sql_order)) {
$sql .= ' order by ' . $modelReportTemplate->sql_order;
}
if (!empty($modelReportTemplate->sql_subquery_group)) {
$sql_subquery .= ' group by ' . $modelReportTemplate->sql_subquery_group;
}
if (!empty($modelReportTemplate->sql_subquery_order)) {
$sql_subquery .= ' order by ' . $modelReportTemplate->sql_subquery_order;
}
}
if (empty($reportFilterFinal)) {
$reportFilterFinal_F = "";
} else {
$reportFilterFinal_F = " " . preg_replace('/\W\w+\s*(\W*)$/', '$1', $reportFilterFinal);
}
$file_name = $modelReportTemplate->file_name;
$printed_on = "Printed on " . date('l F d Y H:i A', time());
$reportName = "<strong><center>" . strtoupper($modelReportTemplate->name . " Report <br>" . $reportFilterFinal_F) . "<br/> " . $printed_on . "<center/></strong>";
$reportNameExcel = $modelReportTemplate->name . " Report " . $reportFilterFinal_F;
$reportLabel = "report_" . date("Y_m_d_h_m_s");
$dataExists = count($this->reportGenerate($sql));
if ($dataExists > 0) {
if ($exportCategory == 1) {
// print_r($this->reportGenerate($sql));
// echo "tele";exit;
if ($file_name != '' && $file_name != NULL) {
if($modelReportTemplate->printing_mode ==1){
$this->renderPartial($file_name, ['id' => $id, 'reportData' => $this->reportGenerate($sql), 'reportSubQuery' => $sql_subquery, 'applicantCategory' => $applicantCategorySet, 'reportName' => $reportName, 'searchParams' => $searchParams,'exportCategory'=>$exportCategory]);
}
$htmlContent = $this->renderPartial($file_name, ['id' => $id, 'reportData' => $this->reportGenerate($sql), 'reportSubQuery' => $sql_subquery, 'applicantCategory' => $applicantCategorySet, 'reportName' => $reportName, 'searchParams' => $searchParams,'exportCategory'=>$exportCategory]);
$generated_by = Yii::$app->user->identity->firstname . " " . Yii::$app->user->identity->middlename . " " . Yii::$app->user->identity->surname;
if($export_mode ==1){
$mpdf = new mPDF('c','A4-L','','',5,5,30,25,10,10);
}else{
$mpdf = new mPDF();
}
//$mpdf = new \Mpdf\Mpdf(['orientation' => 'L']);
//$mpdf->showImageErrors = true;
//$mpdf->SetHTMLHeader('','',true);
$mpdf->SetDefaultFontSize(8.0);
$mpdf->useDefaultCSS2 = true;
$mpdf->SetTitle('Report');
$mpdf->SetDisplayMode('fullpage');
$mpdf->setAutoTopMargin = 'stretch';
$mpdf->SetHTMLHeader("<div class='header' style='text-align: center;'><table width='100%'>
<tr>
<td width='100%' style='margin: 1%;text-align: center;'>
<span style='font-weight: bold; font-size: 14pt;'>HIGHER EDUCATION STUDENT'S LOANS BOARD</span><br />
<b><i>(BODI YA MIKOPO YA WANAFUNZI WA ELIMU YA JUU)</i></b><br />
</td>
</tr>
<tr><td width='100%'>$reportName</td></tr>
<tr><td width='100%'></td></tr>
</table></div>");
$mpdf->SetFooter('|Page {PAGENO} of {nbpg}|');
$mpdf->WriteHTML($htmlContent);
return $mpdf->Output($reportLabel . '.pdf', "D");
exit;
} else {
$sms = "<p>Error: No Template Available</p>";
Yii::$app->getSession()->setFlash('danger', $sms);
if ($pageIdentify == '1') {
return $this->redirect([$actions, 'id' => $id]);
} else if ($pageIdentify == '2') {
return $this->redirect([$actions, 'id' => $id]);
} else if ($pageIdentify == '3') {
return $this->redirect([$actions, 'id' => $id]);
}
}
} else if ($exportCategory == 2) {
if ($modelReportTemplate->name != '' && $modelReportTemplate->name != NULL) {
if ($modelReportTemplate->excel_printing_mode ==0) {
ob_start();
$this->GenerateExcel($this->reportGenerateExcel($sql), $reportNameExcel);
ob_clean();
ob_flush();
}else{
$this->renderPartial($file_name, ['id' => $id, 'reportData' => $this->reportGenerate($sql), 'reportSubQuery' => $sql_subquery, 'applicantCategory' => $applicantCategorySet, 'reportName' => $reportName, 'searchParams' => $searchParams,'exportCategory'=>$exportCategory]);
}
} else {
$sms = "<p>Error: Missing Report Name</p>";
Yii::$app->getSession()->setFlash('danger', $sms);
if ($pageIdentify == '1') {
return $this->redirect([$actions, 'id' => $id]);
} else if ($pageIdentify == '2') {
return $this->redirect([$actions, 'id' => $id]);
} else if ($pageIdentify == '3') {
return $this->redirect([$actions, 'id' => $id]);
}
}
} else {
$sms = "<p>Error: Missing Export Category</p>";
Yii::$app->getSession()->setFlash('danger', $sms);
if ($pageIdentify == '1') {
return $this->redirect([$actions, 'id' => $id]);
} else if ($pageIdentify == '2') {
return $this->redirect([$actions, 'id' => $id]);
} else if ($pageIdentify == '3') {
return $this->redirect([$actions, 'id' => $id]);
}
}
} else {
$sms = "<p>No record found</p>";
Yii::$app->getSession()->setFlash('danger', $sms);
if ($pageIdentify == '1') {
return $this->redirect([$actions, 'id' => $id]);
} else if ($pageIdentify == '2') {
return $this->redirect([$actions, 'id' => $id]);
} else if ($pageIdentify == '3') {
return $this->redirect([$actions, 'id' => $id]);
}
}
}
function reportGenerate($sql) {
$command = Yii::$app->db->createCommand($sql);
$reportData = $command->queryAll();
return $reportData;
}
function reportGenerateExcel($sql) {
$command = Yii::$app->db->createCommand($sql);
return $command;
}
function GenerateExcel($command, $name) {
$generatedBy = "Printed By " . Yii::$app->user->identity->firstname . " " . Yii::$app->user->identity->surname;
//ob_start();
$xlsName = "report_" . date("Y_m_d_h_m_s") . ".xls";
//flush();
//require_once('components/Classes/PHPExcel.php');
//$objPHPExcel = new PHPExcel();
$objPHPExcel = new \PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator($generatedBy)
->setLastModifiedBy($generatedBy)
->setTitle($name)
->setSubject($name)
->setDescription("An Excel document, generated from " . $generatedBy . " by " . $generatedBy)
->setKeywords("office Excel report")
->setCategory($generatedBy . " Generated File");
// Add some data
$this->CellCreator($command, $objPHPExcel, $name);
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$xlsName");
header("Pragma: no-cache");
header("Expires: 0");
exit;
//return;
}
function CellCreator($command, $excelObject, $name) {
//$output = array();
$headerReport = strtoupper($name);
$rows = $command->queryOne();
$query = $command->queryAll();
//$columnArray=range('A','Z');
$labelsArray = array_keys($rows);
$excelObject->setActiveSheetIndex(0);
$styleArray = array('font' => array('bold' => true,
)
);
$fromCol = 'A';
$toCol = 'CU';
$fromRow = 2;
$toRow = 2;
$cellRange = $fromCol . $fromRow . ':' . $toCol . $toRow;
$excelObject->getActiveSheet()->SetCellValue('A1', $headerReport);
$excelObject->setActiveSheetIndex(0)->mergeCells('A1:CU1', $headerReport);
$excelObject->getActiveSheet()->getStyle('A1:O1')->getFont()->setBold(true);
$excelObject->getActiveSheet()->fromArray(array_values($labelsArray), NULL, 'A2');
$excelObject->getActiveSheet()->getStyle($cellRange)->applyFromArray($styleArray);
$excelObject->getActiveSheet()->fromArray(array_values($query), NULL, 'A3');
return;
}
// UserController.php
// NOTE: You must set controller access rules for this action
// below to allow only specific user(s) to delete the image
public function actionDeleteImage($id) {
$model = Report::findOne($id);
if ($model->deleteImage()) {
//Yii::$app->session->setFlash('success',
//'Your image was removed successfully. Upload another by clicking Browse below');
$sms = "<p>Your File was removed successfully. Upload another by clicking Browse below</p>";
Yii::$app->getSession()->setFlash('success', $sms);
return $this->redirect(['update', 'id' => $id]);
} else {
Yii::$app->session->setFlash('error', 'Error removing file. Please try again later or contact the system admin.');
}
return $this->render('update', ['model' => $model]);
}
public function actionPrintReportStudents() {
// $generatedBy = "Printed By " . Yii::$app->user->identity->firstname . " " . Yii::$app->user->identity->surname;
$generatedBy = NULL;
$searchParams = array();
$model = new Report();
$modelApplication = new \backend\modules\application\models\Application();
//$model->scenario='exportReport';
//if($modelApplication->load(Yii::$app->request->post())){
if (isset($_POST['Application'])) {
$posted_data = Yii::$app->request->post();
$id = $posted_data['Application']['uniqid'];
$application_id = $posted_data['Application']['application_id'];
$applicant_id = $posted_data['Application']['applicant_id'];
$export_mode = $posted_data['Application']['export_mode'];
if($id==''){
$reportName="";
$htmlContent="";
if($id !=4){
$mpdf = new mPDF();
}else{
$mpdf = new mPDF('c','A4-L','','',5,5,30,25,10,10);
}
//$mpdf = new \Mpdf\Mpdf(['orientation' => 'L']);
//$mpdf->showImageErrors = true;
//$mpdf->SetHTMLHeader('','',true);
$reportLabel='';
$mpdf->SetDefaultFontSize(8.0);
$mpdf->useDefaultCSS2 = true;
$mpdf->SetTitle('Report');
$mpdf->SetDisplayMode('fullpage');
$mpdf->setAutoTopMargin = 'stretch';
$mpdf->SetHTMLHeader("<div class='header' style='text-align: center;'><table width='100%'>
<tr>
<td width='100%' style='margin: 1%;text-align: center;'>
<span style='font-weight: bold; font-size: 14pt;'>HIGHER EDUCATION STUDENT'S LOANS BOARD</span><br />
<b><i>(BODI YA MIKOPO YA WANAFUNZI WA ELIMU YA JUU)</i></b><br />
</td>
</tr>
<tr><td width='100%'>$reportName</td></tr>
<tr><td width='100%'></td></tr>
</table></div>");
$mpdf->SetFooter('|Page {PAGENO} of {nbpg}|');
$mpdf->WriteHTML($htmlContent);
return $mpdf->Output($reportLabel . '.pdf', "I");
exit;
}
//}
//if ($model->load(Yii::$app->request->post())) {
// var_dump($model->attributes);
// exit;
$category = $model->category;
$exportCategory = $posted_data['Application']['exportCategory'];
$pageIdentify = $posted_data['Application']['pageIdentifyStud'];
$applicant_id = $posted_data['Application']['applicant_id'];
$modelReportTemplate = Report::findOne($id);
$sql = $modelReportTemplate->sql;
$sql_subquery = $modelReportTemplate->sql_subquery;
//return $sql;
$where = $subquery_where = '';
$reportFilter = '';
$reportFilterFinal = '';
$applicantCategorySet = '';
$file_name = $modelReportTemplate->file_name;
$printed_on = "Printed on " . date('l F d Y H:i A', time());
$resultsBanks=\backend\modules\repayment\models\BankAccount::find()->joinWith(['bank'])->all();
$desc='';
$count1=0;
foreach($resultsBanks AS $resultsBanksFound){
//if($count1==0){
$desc.=$resultsBanksFound->bank->bank_name." - ".$resultsBanksFound->account_number."<br/>";
//}
/*
if($count1==1){
$desc1=$resultsBanksFound->bank->bank_name." - ".$resultsBanksFound->account_number;
}
if($count1==2){
$desc2=$resultsBanksFound->bank->bank_name." - ".$resultsBanksFound->account_number;
}
*
*/
++$count1;
}
if($id==19){
$custtomerState="<br/><strong>CUSTOMER STATEMENT : REPAYMENTS</strong>";
$pritedOnside=$printed_on;
}else if($id==20){
$custtomerState="<br/><strong>CUSTOMER STATEMENT : REPAYMENT SCHEDULE</strong>";
$pritedOnside=$printed_on;
}else if($id==18){
$custtomerState="<hr>
<strong>CUSTOMER STATEMENT</strong>
<hr>";
$pritedOnside="Loan Collection Acounts:<br/>".$desc."<br/>".$printed_on;
}else{
$custtomerState="<br/><strong>".$modelReportTemplate->name." REPORT"."</strong>";
$pritedOnside=$printed_on;
}
if($modelReportTemplate->printing_mode ==1){
$reportLabel = "report_" . date("Y_m_d_h_m_s");
$printedBy="Printed By: " . Yii::$app->user->identity->firstname . " " . Yii::$app->user->identity->surname."<br/><br/>Verified By : ______________________________________________ ";
$htmlContent = $this->renderPartial($file_name, ['applicant_id' => $applicant_id]);
if($export_mode ==1){
$mpdf = new mPDF('c','A4-L','','',5,5,30,25,10,10);
}else{
$mpdf = new mPDF();
}
//$mpdf = new \Mpdf\Mpdf(['orientation' => 'L']);
//$mpdf->showImageErrors = true;
//$mpdf->SetHTMLHeader('','',true);
$mpdf->SetDefaultFontSize(8.0);
$mpdf->useDefaultCSS2 = true;
$mpdf->SetTitle('Report');
$mpdf->SetDisplayMode('fullpage');
$mpdf->setAutoTopMargin = 'stretch';
$mpdf->setAutoBottomMargin = 'stretch';
$logoHESLB=Yii::$app->params['HESLBlogo'].'logohelsb_new.jpg';
$mpdf->SetHTMLHeader("<div class='header' style='text-align: center;'><table width='100%'>
<tr>
<td width='100%' style='margin: 1%;text-align: center;'>
<span style='font-weight: bold; font-size: 14pt;'>HIGHER EDUCATION STUDENT'S LOANS BOARD</span><br />
<img class='img' src='".$logoHESLB."' alt='' style='height: 70px;width: 70px;'>
<br />
Plot No. 8, Block No. 46; Sam Nujoma Rd; P.O Box 76068 Dar es Salaam, <strong>Tanzania</strong><br/>
<strong>Tel: </strong>(General) +255 22 22772432/22772433; <strong>Fax: </strong> +255 22 2700286; <strong>Email:</strong>repayment@heslb.go.tz;<br/>
<strong>Website:</strong>www.heslb.go.tz
</td>
</tr>
<tr>
<td width='100%' style='margin: 1%;text-align: center;'>
".$custtomerState."
</td>
</tr>
</table></div>");
$mpdf->SetFooter($printedBy.' |Page {PAGENO} of {nbpg} |<div style="text-align:left;font-size: 6pt;">'.$pritedOnside.'</div>');
$mpdf->WriteHTML($htmlContent);
return $mpdf->Output($reportLabel . '.pdf', "I");
exit;
}
//exit;
if (!empty($modelReportTemplate->sql_where)) {
$where = ' where ' . $modelReportTemplate->sql_where.' AND allocation.application_id='.$application_id;
}
if (!empty($modelReportTemplate->sql_subquery_where)) {
$subquery_where = ' where ' . $modelReportTemplate->sql_subquery_where.' AND allocation.application_id='.$application_id;
}
$results = \backend\modules\report\models\ReportFilterSetting::find()
->select('number_of_rows')
->where(['is_active' => '1'])
->orderBy(['report_filter_setting_id' => SORT_DESC])
->one();
$getStudent = \backend\modules\application\models\Application::findBySql('SELECT user.firstname AS firstname,user.middlename,user.surname,education.registration_number AS regNumber,education.completion_year FROM application INNER JOIN applicant ON applicant.applicant_id=application.applicant_id INNER JOIN user ON user.user_id=applicant.user_id INNER JOIN education ON education.application_id=application.application_id WHERE application.application_id = "'.$application_id.'" AND education.application_id ="'.$application_id.'" AND education.level="OLEVEL"')->one();
$fullName="STUDENT NAME: ".$getStudent->firstname." ".$getStudent->middlename." ".$getStudent->surname." : ".$getStudent->regNumber.".".$getStudent->completion_year;
//$number_of_rows=$results->number_of_rows;
$number_of_rows = 15;
$sql .= ' ' . $where;
$sql_subquery .= ' ' . $subquery_where;
if (!empty($modelReportTemplate->sql_group)) {
$sql .= ' group by ' . $modelReportTemplate->sql_group;
}
if (!empty($modelReportTemplate->sql_order)) {
$sql .= ' order by ' . $modelReportTemplate->sql_order;
}
if (!empty($modelReportTemplate->sql_subquery_group)) {
$sql_subquery .= ' group by ' . $modelReportTemplate->sql_subquery_group;
}
if (!empty($modelReportTemplate->sql_subquery_order)) {
$sql_subquery .= ' order by ' . $modelReportTemplate->sql_subquery_order;
}
//}
}
/*
if (empty($reportFilterFinal)) {
$reportFilterFinal_F = "";
} else {
$reportFilterFinal_F = " " . preg_replace('/\W\w+\s*(\W*)$/', '$1', $reportFilterFinal);
}
*
*/
$reportFilterFinal_F=$fullName;
$file_name = $modelReportTemplate->file_name;
$printed_on = "Printed on " . date('l F d Y H:i A', time());
$reportName = "<strong><center>" . strtoupper($modelReportTemplate->name . " Report <br>" . $reportFilterFinal_F) . "<br/> " . $printed_on . "<center/></strong>";
$reportNameExcel = $modelReportTemplate->name . " Report " . $reportFilterFinal_F;
$reportLabel = "report_" . date("Y_m_d_h_m_s");
$dataExists = count($this->reportGenerate($sql));
if ($dataExists > 0) {
if ($exportCategory == 1) {
if ($file_name != '' && $file_name != NULL) {
$htmlContent = $this->renderPartial($file_name, ['id' => $id, 'reportData' => $this->reportGenerate($sql), 'reportSubQuery' => $sql_subquery, 'applicantCategory' => $applicantCategorySet, 'reportName' => $reportName, 'searchParams' => $searchParams]);
$generated_by = Yii::$app->user->identity->firstname . " " . Yii::$app->user->identity->middlename . " " . Yii::$app->user->identity->surname;
if($export_mode ==1){
$mpdf = new mPDF('c','A4-L','','',5,5,30,25,10,10);
}else{
$mpdf = new mPDF();
}
//$mpdf = new \Mpdf\Mpdf(['orientation' => 'L']);
//$mpdf->showImageErrors = true;
//$mpdf->SetHTMLHeader('','',true);
$mpdf->SetDefaultFontSize(8.0);
$mpdf->useDefaultCSS2 = true;
$mpdf->SetTitle('Report');
$mpdf->SetDisplayMode('fullpage');
$mpdf->setAutoTopMargin = 'stretch';
$logoHESLB=Yii::$app->params['HESLBlogo'].'logohelsb_new.jpg';
$mpdf->SetHTMLHeader("<div class='header' style='text-align: center;'><table width='100%'>
<tr>
<td width='5%' style='text-align: left;'>
<img class='img' src='".$logoHESLB."' alt='' style='height: 70px;width: 70px;'><br /></b>
</td>
<td width='95%' style='margin: 1%;text-align: center;'>
<span style='font-weight: bold; font-size: 14pt;'>HIGHER EDUCATION STUDENT'S LOANS BOARD</span><br />
<b><i>(BODI YA MIKOPO YA WANAFUNZI WA ELIMU YA JUU)</i></b><br /><br />
$reportName
</td>
</tr>
</table></div>");
$mpdf->SetFooter('|Page {PAGENO} of {nbpg}|');
$mpdf->WriteHTML($htmlContent);
return $mpdf->Output($reportLabel . '.pdf', "I");
exit;
}
}
} else {
$reportName="";
$htmlContent="";
if($id !=4){
$mpdf = new mPDF();
}else{
$mpdf = new mPDF('c','A4-L','','',5,5,30,25,10,10);
}
//$mpdf = new \Mpdf\Mpdf(['orientation' => 'L']);
//$mpdf->showImageErrors = true;
//$mpdf->SetHTMLHeader('','',true);
$mpdf->SetDefaultFontSize(8.0);
$mpdf->useDefaultCSS2 = true;
$mpdf->SetTitle('Report');
$mpdf->SetDisplayMode('fullpage');
$mpdf->setAutoTopMargin = 'stretch';
$mpdf->SetHTMLHeader("<div class='header' style='text-align: center;'><table width='100%'>
<tr>
<td width='100%' style='margin: 1%;text-align: center;'>
<span style='font-weight: bold; font-size: 14pt;'>HIGHER EDUCATION STUDENT'S LOANS BOARD</span><br />
<b><i>(BODI YA MIKOPO YA WANAFUNZI WA ELIMU YA JUU)</i></b><br />
</td>
</tr>
<tr><td width='100%'>$reportName</td></tr>
<tr><td width='100%'></td></tr>
</table></div>");
$mpdf->SetFooter('|Page {PAGENO} of {nbpg}|');
$mpdf->WriteHTML($htmlContent);
return $mpdf->Output($reportLabel . '.pdf', "I");
exit;
}
}
public function actionPrintReportStudaccount() {
// $generatedBy = "Printed By " . Yii::$app->user->identity->firstname . " " . Yii::$app->user->identity->surname;
$generatedBy = NULL;
$searchParams = array();
$model = new Report();
$modelApplication = new \backend\modules\application\models\Application();
//$model->scenario='exportReport';
//if($modelApplication->load(Yii::$app->request->post())){
if (isset($_POST['Application'])) {
$posted_data = Yii::$app->request->post();
$id = $posted_data['Application']['uniqid'];
$application_id = $posted_data['Application']['application_id'];
$applicant_id = $posted_data['Application']['applicant_id'];
$export_mode = $posted_data['Application']['export_mode'];
$reportLabel='';
if($id==''){
$reportName="";
$htmlContent="";
if($id !=4){
$mpdf = new mPDF();
}else{
$mpdf = new mPDF('c','A4-L','','',5,5,30,25,10,10);
}
//$mpdf = new \Mpdf\Mpdf(['orientation' => 'L']);
//$mpdf->showImageErrors = true;
//$mpdf->SetHTMLHeader('','',true);
$mpdf->SetDefaultFontSize(8.0);
$mpdf->useDefaultCSS2 = true;
$mpdf->SetTitle('Report');
$mpdf->SetDisplayMode('fullpage');
$mpdf->setAutoTopMargin = 'stretch';
$mpdf->SetHTMLHeader("<div class='header' style='text-align: center;'><table width='100%'>
<tr>
<td width='100%' style='margin: 1%;text-align: center;'>
<span style='font-weight: bold; font-size: 14pt;'>HIGHER EDUCATION STUDENT'S LOANS BOARD</span><br />
<b><i>(BODI YA MIKOPO YA WANAFUNZI WA ELIMU YA JUU)</i></b><br />
</td>
</tr>
<tr><td width='100%'>$reportName</td></tr>
<tr><td width='100%'></td></tr>
</table></div>");
$mpdf->SetFooter('|Page {PAGENO} of {nbpg}|');
$mpdf->WriteHTML($htmlContent);
return $mpdf->Output($reportLabel . '.pdf', "I");
exit;
}
//}
//if ($model->load(Yii::$app->request->post())) {
// var_dump($model->attributes);
// exit;
$category = $model->category;
$exportCategory = $posted_data['Application']['exportCategory'];
$pageIdentify = $posted_data['Application']['pageIdentifyStud'];
$applicant_id = $posted_data['Application']['applicant_id'];
$modelReportTemplate = Report::findOne($id);
$sql = $modelReportTemplate->sql;
$sql_subquery = $modelReportTemplate->sql_subquery;
//return $sql;
$where = $subquery_where = '';
$reportFilter = '';
$reportFilterFinal = '';
$applicantCategorySet = '';
$file_name = $modelReportTemplate->file_name;
$printed_on = "Printed on " . date('l F d Y H:i A', time());
$resultsBanks=\backend\modules\repayment\models\BankAccount::find()->joinWith(['bank'])->all();
$desc='';
$count1=0;
foreach($resultsBanks AS $resultsBanksFound){
//if($count1==0){
$desc.=$resultsBanksFound->bank->bank_name." - ".$resultsBanksFound->account_number."<br/>";
//}
/*
if($count1==1){
$desc1=$resultsBanksFound->bank->bank_name." - ".$resultsBanksFound->account_number;
}
if($count1==2){
$desc2=$resultsBanksFound->bank->bank_name." - ".$resultsBanksFound->account_number;
}
*
*/
++$count1;
}
if($id==19){
$custtomerState="<br/><strong>CUSTOMER STATEMENT : REPAYMENTS</strong>";
$pritedOnside=$printed_on;
}else{
$custtomerState="<hr>
<strong>CUSTOMER STATEMENT</strong>
<hr>";
$pritedOnside="Loan Collection Acounts:<br/>".$desc."<br/>".$printed_on;
}
if($modelReportTemplate->printing_mode ==1){
$reportLabel = "report_" . date("Y_m_d_h_m_s");
$printedBy="Printed By: " . Yii::$app->user->identity->firstname . " " . Yii::$app->user->identity->surname."<br/><br/>Verified By : ______________________________________________ ";
$htmlContent = $this->renderPartial($file_name, ['applicant_id' => $applicant_id]);
if($export_mode ==1){
$mpdf = new mPDF('c','A4-L','','',5,5,30,25,10,10);
}else{
$mpdf = new mPDF();
}
//$mpdf = new \Mpdf\Mpdf(['orientation' => 'L']);
//$mpdf->showImageErrors = true;
//$mpdf->SetHTMLHeader('','',true);
$mpdf->SetDefaultFontSize(8.0);
$mpdf->useDefaultCSS2 = true;
$mpdf->SetTitle('Report');
$mpdf->SetDisplayMode('fullpage');
$mpdf->setAutoTopMargin = 'stretch';
$mpdf->setAutoBottomMargin = 'stretch';
$logoHESLB=Yii::$app->params['HESLBlogo'].'logohelsb_new.jpg';
$mpdf->SetHTMLHeader("<div class='header' style='text-align: center;'><table width='100%'>
<tr>
<td width='100%' style='margin: 1%;text-align: center;'>
<span style='font-weight: bold; font-size: 14pt;'>HIGHER EDUCATION STUDENT'S LOANS BOARD</span><br />
<img class='img' src='".$logoHESLB."' alt='' style='height: 70px;width: 70px;'>
<br />
Plot No. 8, Block No. 46; Sam Nujoma Rd; P.O Box 76068 Dar es Salaam, <strong>Tanzania</strong><br/>
<strong>Tel: </strong>(General) +255 22 22772432/22772433; <strong>Fax: </strong> +255 22 2700286; <strong>Email:</strong>repayment@heslb.go.tz;<br/>
<strong>Website:</strong>www.heslb.go.tz
</td>
</tr>
<tr>
<td width='100%' style='margin: 1%;text-align: center;'>
".$custtomerState."
</td>
</tr>
</table></div>");
$mpdf->SetFooter($printedBy.' |Page {PAGENO} of {nbpg} |<div style="text-align:left;font-size: 6pt;">'.$pritedOnside.'</div>');
$mpdf->WriteHTML($htmlContent);
return $mpdf->Output($reportLabel . '.pdf', "I");
exit;
}
//exit;
if (!empty($modelReportTemplate->sql_where)) {
$where = ' where ' . $modelReportTemplate->sql_where.' AND allocation.application_id='.$application_id;
}
if (!empty($modelReportTemplate->sql_subquery_where)) {
$subquery_where = ' where ' . $modelReportTemplate->sql_subquery_where.' AND allocation.application_id='.$application_id;
}
$results = \backend\modules\report\models\ReportFilterSetting::find()
->select('number_of_rows')
->where(['is_active' => '1'])
->orderBy(['report_filter_setting_id' => SORT_DESC])
->one();
/*
$getStudent = \backend\modules\application\models\Application::find()
->select('user.firstname,user.middlename,user.surname,education.registration_number,education.completion_year')
->joinWith('applicant')
->joinWith('applicant.user')
->joinWith('educations')
->where(['application.application_id' => $application_id,'education.application_id'=>$application_id,'education.level'=>'OLEVEL'])
->one();
*
*/
$getStudent = \backend\modules\application\models\Application::findBySql('SELECT user.firstname AS firstname,user.middlename,user.surname,education.registration_number AS regNumber,education.completion_year FROM application INNER JOIN applicant ON applicant.applicant_id=application.applicant_id INNER JOIN user ON user.user_id=applicant.user_id INNER JOIN education ON education.application_id=application.application_id WHERE application.application_id = "'.$application_id.'" AND education.application_id ="'.$application_id.'" AND education.level="OLEVEL"')->one();
$fullName="STUDENT NAME: ".$getStudent->firstname." ".$getStudent->middlename." ".$getStudent->surname." : ".$getStudent->regNumber.".".$getStudent->completion_year;
//$number_of_rows=$results->number_of_rows;
$number_of_rows = 15;
$sql .= ' ' . $where;
$sql_subquery .= ' ' . $subquery_where;
if (!empty($modelReportTemplate->sql_group)) {
$sql .= ' group by ' . $modelReportTemplate->sql_group;
}
if (!empty($modelReportTemplate->sql_order)) {
$sql .= ' order by ' . $modelReportTemplate->sql_order;
}
if (!empty($modelReportTemplate->sql_subquery_group)) {
$sql_subquery .= ' group by ' . $modelReportTemplate->sql_subquery_group;
}
if (!empty($modelReportTemplate->sql_subquery_order)) {
$sql_subquery .= ' order by ' . $modelReportTemplate->sql_subquery_order;
}
//}
}
/*
if (empty($reportFilterFinal)) {
$reportFilterFinal_F = "";
} else {
$reportFilterFinal_F = " " . preg_replace('/\W\w+\s*(\W*)$/', '$1', $reportFilterFinal);
}
*
*/
$reportFilterFinal_F=$fullName;
$file_name = $modelReportTemplate->file_name;
$printed_on = "Printed on " . date('l F d Y H:i A', time());
$reportName = "<strong><center>" . strtoupper($modelReportTemplate->name . " Report <br>" . $reportFilterFinal_F) . "<br/> " . $printed_on . "<center/></strong>";
$reportNameExcel = $modelReportTemplate->name . " Report " . $reportFilterFinal_F;
$reportLabel = "report_" . date("Y_m_d_h_m_s");
$dataExists = count($this->reportGenerate($sql));
if ($dataExists > 0) {
if ($exportCategory == 1) {
if ($file_name != '' && $file_name != NULL) {
$htmlContent = $this->renderPartial($file_name, ['id' => $id, 'reportData' => $this->reportGenerate($sql), 'reportSubQuery' => $sql_subquery, 'applicantCategory' => $applicantCategorySet, 'reportName' => $reportName, 'searchParams' => $searchParams]);
$generated_by = Yii::$app->user->identity->firstname . " " . Yii::$app->user->identity->middlename . " " . Yii::$app->user->identity->surname;
if($export_mode ==1){
$mpdf = new mPDF('c','A4-L','','',5,5,30,25,10,10);
}else{
$mpdf = new mPDF();
}
//$mpdf = new \Mpdf\Mpdf(['orientation' => 'L']);
//$mpdf->showImageErrors = true;
//$mpdf->SetHTMLHeader('','',true);
$mpdf->SetDefaultFontSize(8.0);
$mpdf->useDefaultCSS2 = true;
$mpdf->SetTitle('Report');
$mpdf->SetDisplayMode('fullpage');
$mpdf->setAutoTopMargin = 'stretch';
$logoHESLB=Yii::$app->params['HESLBlogo'].'logohelsb_new.jpg';
$mpdf->SetHTMLHeader("<div class='header' style='text-align: center;'><table width='100%'>
<tr>
<td width='5%' style='text-align: left;'>
<img class='img' src='".$logoHESLB."' alt='' style='height: 70px;width: 70px;'><br /></b>
</td>
<td width='95%' style='margin: 1%;text-align: center;'>
<span style='font-weight: bold; font-size: 14pt;'>HIGHER EDUCATION STUDENT'S LOANS BOARD</span><br />
<b><i>(BODI YA MIKOPO YA WANAFUNZI WA ELIMU YA JUU)</i></b><br /><br />
$reportName
</td>
</tr>
</table></div>");
$mpdf->SetFooter('|Page {PAGENO} of {nbpg}|');
$mpdf->WriteHTML($htmlContent);
return $mpdf->Output($reportLabel . '.pdf', "I");
exit;
}
}
} else {
$reportName="";
$htmlContent="";
if($id !=4){
$mpdf = new mPDF();
}else{
$mpdf = new mPDF('c','A4-L','','',5,5,30,25,10,10);
}
//$mpdf = new \Mpdf\Mpdf(['orientation' => 'L']);
//$mpdf->showImageErrors = true;
//$mpdf->SetHTMLHeader('','',true);
$mpdf->SetDefaultFontSize(8.0);
$mpdf->useDefaultCSS2 = true;
$mpdf->SetTitle('Report');
$mpdf->SetDisplayMode('fullpage');
$mpdf->setAutoTopMargin = 'stretch';
$mpdf->SetHTMLHeader("<div class='header' style='text-align: center;'><table width='100%'>
<tr>
<td width='100%' style='margin: 1%;text-align: center;'>
<span style='font-weight: bold; font-size: 14pt;'>HIGHER EDUCATION STUDENT'S LOANS BOARD</span><br />
<b><i>(BODI YA MIKOPO YA WANAFUNZI WA ELIMU YA JUU)</i></b><br />
</td>
</tr>
<tr><td width='100%'>$reportName</td></tr>
<tr><td width='100%'></td></tr>
</table></div>");
$mpdf->SetFooter('|Page {PAGENO} of {nbpg}|');
$mpdf->WriteHTML($htmlContent);
return $mpdf->Output($reportLabel . '.pdf', "I");
exit;
}
}
}
| 16,222
|
https://github.com/Faborah-of-Sarthe/Minimit/blob/master/resources/lang/en/poster.php
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
Minimit
|
Faborah-of-Sarthe
|
PHP
|
Code
| 194
| 496
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Poster Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used for user poster page.
|
*/
'add_image' => "Add an image",
'add_title' => "Create a poster",
'ajax_error' => "A parameter is missing",
'close-solution' => "Close",
'creation_success_message' => "The poster has been created",
'delete_image' => "Delete the image",
'delete_image_confirmation_message' => "Are you sure you want to delete this image. Pay attention, for this is irreversible !",
'delete_image_confirmation_poster' => "Are you sure you want to delete this poster. Pay attention, for this is irreversible !",
'edit_success_message' => "The poster has been saved !",
'edit_title' => "Edit a poster",
'empty_oeuvre_error' => "You must select an oeuvre",
'empty_posters_error' => "You must add at least one image",
'label_oeuvre_title_en' => 'EN :',
'label_oeuvre_title_fr' => 'FR :',
'label_oeuvre_title_ov' => 'OV :',
'list_all' => "All the posters",
'list_empty' => "No posters found",
'next_button' => 'Next',
'no_images' => "No image has been sent for now",
'oeuvre' => "Oeuvre",
'owner_error' => "You are not allowed to edit that poster",
'poster_by' => 'Poster by :author',
'poster_delete' => "Delete the poster",
'prev_button' => 'Previous',
'random_poster_title' => 'Random poster',
'show-solution' => 'Solution',
'submit' => "Save",
'upload_image' => "Send",
];
| 31,236
|
https://github.com/mohamedalzahaby/renovame/blob/master/resources/views/html/pricing.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
renovame
|
mohamedalzahaby
|
PHP
|
Code
| 178
| 733
|
@extends('layouts.app')
@section('content')
<section class="section pagegrey">
<div class="container">
<div class="title-area text-center">
<h2>Our Pricing <small>Trending stock photos, freebies and more..</small></h2>
<div class="bread">
<ol class="breadcrumb">
<li><a href="/home">Home</a></li>
<li class="active">Pricing</li>
</ol>
</div><!-- end bread -->
</div><!-- /.pull-right -->
</div><!-- end container -->
</section>
<section class="section">
<div class="container">
<div class="content">
<div class="row pricing-tables text-center">
@forelse ($memberships as $membership)
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="pricing-box">
<div class="pricing-header">
<h3><i class="icon icon-flag"></i>{{$membership->name}}</h3>
</div>
<div class="pricing-price">
<p><sub>$</sub>{{ $membership->price }}</p>
</div><!-- end price -->
<div class="pricing-desc text-center">
<p> {{ $membership->description }} </p>
</div><!-- end desc -->
<div class="panel-group" id="accordion1" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<p >Number Of Free Downloads: {{$membership->number_of_downloads}} </p>
</h4>
</div><!-- end heading -->
</div><!-- end panel -->
</div><!-- end panel-group -->
<div class="pricing-footer text-center">
<a href="/purchase/{{$membership->id}}" data-scroll class="btn btn-primary">Order Now</a>
@if ($admin)
<a href="/membership/edit/{{ $membership->id }}" data-scroll class="btn btn-primary">Edit membership</a>
@endif
</div><!-- end desc -->
</div><!-- end pricing-box -->
</div><!-- end col -->
@empty
<div class="container" >
<label>No Packages Available</label>
</div>
@endforelse
</div><!-- end row -->
</div><!-- end content -->
</div>
</section>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/custom.js"></script>
@endsection
| 29,240
|
https://github.com/ProjectSidewalk/access-score-viz/blob/master/streetviz/street-viz-fulldc-probcount+severity/visproto.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
access-score-viz
|
ProjectSidewalk
|
JavaScript
|
Code
| 101
| 452
|
function drawNeighborhoods() {
// North Cleveland Park - 205
// Hillsdale - 231
console.log("drawNeighborhoods");
d3.json("http://localhost:8000/data/neighborhoods.json", function (err, data) {
map.addSource("neighborhoods", {
"type": "geojson",
"data": data
});
// Border layer
map.addLayer({
'id': 'neighborhood-border',
'type': 'line',
'source': 'neighborhoods',
'paint': {
'line-color': '#ffffff', // Dark: '#ffffff' //Light: '#606C38',
'line-width': 1,
'line-opacity': 0.9,
'line-dasharray': [2, 4]
}
});
});
}
function drawStreetLayerProblemCount() {
d3.json("http://localhost:8000/data/result-trial1.geojson", function (err, data) {
map.addSource("streets-with-scores", {
"type": "geojson",
"data": data
});
map.addLayer({
'id': 'streets-by-combined',
'type': 'line',
'source': 'streets-with-scores',
'paint': {
'line-color': [
"interpolate",
["linear"],
["get", "scoreByCombined"],
0,
"#ffeee0",
0.007,
"#ff8b0f",
.3,
"#e00000"
],
'line-width': 1,
'line-opacity': 0.9,
}
});
});
}
| 752
|
https://github.com/rclone/rclone/blob/master/backend/local/about_windows.go
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
rclone
|
rclone
|
Go
|
Code
| 137
| 417
|
//go:build windows
// +build windows
package local
import (
"context"
"fmt"
"syscall"
"unsafe"
"github.com/rclone/rclone/fs"
)
var getFreeDiskSpace = syscall.NewLazyDLL("kernel32.dll").NewProc("GetDiskFreeSpaceExW")
// About gets quota information
func (f *Fs) About(ctx context.Context) (*fs.Usage, error) {
var available, total, free int64
root, e := syscall.UTF16PtrFromString(f.root)
if e != nil {
return nil, fmt.Errorf("failed to read disk usage: %w", e)
}
_, _, e1 := getFreeDiskSpace.Call(
uintptr(unsafe.Pointer(root)),
uintptr(unsafe.Pointer(&available)), // lpFreeBytesAvailable - for this user
uintptr(unsafe.Pointer(&total)), // lpTotalNumberOfBytes
uintptr(unsafe.Pointer(&free)), // lpTotalNumberOfFreeBytes
)
if e1 != syscall.Errno(0) {
return nil, fmt.Errorf("failed to read disk usage: %w", e1)
}
usage := &fs.Usage{
Total: fs.NewUsageValue(total), // quota of bytes that can be used
Used: fs.NewUsageValue(total - free), // bytes in use
Free: fs.NewUsageValue(available), // bytes which can be uploaded before reaching the quota
}
return usage, nil
}
// check interface
var _ fs.Abouter = &Fs{}
| 33,422
|
https://github.com/andy521/coadmin/blob/master/sql/coadmin-struct.sql
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
coadmin
|
andy521
|
SQL
|
Code
| 2,564
| 9,404
|
/*
SQLyog Community v13.1.6 (64 bit)
MySQL - 8.0.12 : Database - coadmin
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`coadmin` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci */;
USE `coadmin`;
/*Table structure for table `code_column_config` */
DROP TABLE IF EXISTS `code_column_config`;
CREATE TABLE `code_column_config` (
`id` bigint(20) NOT NULL COMMENT 'ID',
`table_name` varchar(255) NOT NULL,
`column_name` varchar(255) NOT NULL,
`column_type` varchar(255) NOT NULL,
`dict_name` varchar(255) DEFAULT NULL,
`extra` varchar(255) DEFAULT NULL,
`form_show` bit(1) DEFAULT NULL,
`form_type` varchar(255) DEFAULT NULL,
`key_type` varchar(255) DEFAULT NULL,
`list_show` bit(1) DEFAULT NULL,
`not_null` bit(1) DEFAULT NULL,
`query_type` varchar(255) DEFAULT NULL,
`remark` varchar(255) DEFAULT NULL,
`date_annotation` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
KEY `idx_table_name` (`table_name`(191))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='代码生成字段信息存储';
/*Table structure for table `code_gen_config` */
DROP TABLE IF EXISTS `code_gen_config`;
CREATE TABLE `code_gen_config` (
`id` bigint(20) NOT NULL COMMENT 'ID',
`table_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '表名',
`author` varchar(255) DEFAULT NULL COMMENT '作者',
`cover` bit(1) DEFAULT NULL COMMENT '是否覆盖',
`module_name` varchar(255) DEFAULT NULL COMMENT '模块名称',
`pack` varchar(255) DEFAULT NULL COMMENT '至于哪个包下',
`path` varchar(255) DEFAULT NULL COMMENT '前端代码生成的路径',
`api_path` varchar(255) DEFAULT NULL COMMENT '前端Api文件路径',
`prefix` varchar(255) DEFAULT NULL COMMENT '表前缀',
`api_alias` varchar(255) DEFAULT NULL COMMENT '接口名称',
`menu_pid` bigint(20) DEFAULT NULL COMMENT '父级菜单(用于自动生成sql)',
PRIMARY KEY (`id`) USING BTREE,
KEY `idx_table_name` (`table_name`(100))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='代码生成器配置';
/*Table structure for table `mnt_app` */
DROP TABLE IF EXISTS `mnt_app`;
CREATE TABLE `mnt_app` (
`id` bigint(20) NOT NULL COMMENT 'ID',
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '应用名称',
`upload_path` varchar(255) DEFAULT NULL COMMENT '上传目录',
`deploy_path` varchar(255) DEFAULT NULL COMMENT '部署路径',
`backup_path` varchar(255) DEFAULT NULL COMMENT '备份路径',
`port` int(11) DEFAULT NULL COMMENT '应用端口',
`start_script` varchar(4000) DEFAULT NULL COMMENT '启动脚本',
`deploy_script` varchar(4000) DEFAULT NULL COMMENT '部署脚本',
`create_by` varchar(255) DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) DEFAULT NULL COMMENT '更新者',
`create_time` datetime DEFAULT NULL COMMENT '创建日期',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='应用管理';
/*Table structure for table `mnt_database` */
DROP TABLE IF EXISTS `mnt_database`;
CREATE TABLE `mnt_database` (
`id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'ID',
`name` varchar(255) NOT NULL COMMENT '名称',
`jdbc_url` varchar(255) NOT NULL COMMENT 'jdbc连接',
`user_name` varchar(255) NOT NULL COMMENT '账号',
`pwd` varchar(255) NOT NULL COMMENT '密码',
`create_by` varchar(255) DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) DEFAULT NULL COMMENT '更新者',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='数据库管理';
/*Table structure for table `mnt_deploy` */
DROP TABLE IF EXISTS `mnt_deploy`;
CREATE TABLE `mnt_deploy` (
`id` bigint(20) NOT NULL COMMENT 'ID',
`app_id` bigint(20) DEFAULT NULL COMMENT '应用编号',
`create_by` varchar(255) DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) DEFAULT NULL COMMENT '更新者',
`create_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
KEY `FK6sy157pseoxx4fmcqr1vnvvhy` (`app_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='部署管理';
/*Table structure for table `mnt_deploy_history` */
DROP TABLE IF EXISTS `mnt_deploy_history`;
CREATE TABLE `mnt_deploy_history` (
`id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'ID',
`app_name` varchar(255) NOT NULL COMMENT '应用名称',
`deploy_date` datetime NOT NULL COMMENT '部署日期',
`deploy_user` varchar(50) NOT NULL COMMENT '部署用户',
`ip` varchar(20) NOT NULL COMMENT '服务器IP',
`deploy_id` bigint(20) DEFAULT NULL COMMENT '部署编号',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='部署历史管理';
/*Table structure for table `mnt_deploy_server` */
DROP TABLE IF EXISTS `mnt_deploy_server`;
CREATE TABLE `mnt_deploy_server` (
`deploy_id` bigint(20) NOT NULL COMMENT '部署ID',
`server_id` bigint(20) NOT NULL COMMENT '服务ID',
PRIMARY KEY (`deploy_id`,`server_id`) USING BTREE,
KEY `FKeaaha7jew9a02b3bk9ghols53` (`server_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='应用与服务器关联';
/*Table structure for table `mnt_server` */
DROP TABLE IF EXISTS `mnt_server`;
CREATE TABLE `mnt_server` (
`id` bigint(20) NOT NULL COMMENT 'ID',
`account` varchar(50) DEFAULT NULL COMMENT '账号',
`ip` varchar(20) DEFAULT NULL COMMENT 'IP地址',
`name` varchar(100) DEFAULT NULL COMMENT '名称',
`password` varchar(100) DEFAULT NULL COMMENT '密码',
`port` int(11) DEFAULT NULL COMMENT '端口',
`create_by` varchar(255) DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) DEFAULT NULL COMMENT '更新者',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
KEY `idx_ip` (`ip`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='服务器管理';
/*Table structure for table `sys_dept` */
DROP TABLE IF EXISTS `sys_dept`;
CREATE TABLE `sys_dept` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`pid` bigint(20) NOT NULL COMMENT '上级id',
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '机构名称',
`name_letter` varchar(150) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '名称首字母',
`sort` int(11) NOT NULL DEFAULT '999' COMMENT '本节点排序',
`dept_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '机构编码',
`tree_pids` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '所有上级id,''/''分隔',
`tree_names` varchar(5000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '含所有父节点的名称,''/''分隔',
`tree_names_letter` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '首字母',
`tree_sorts` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '含所有父节点的排序,''/''分隔',
`tree_level` int(11) NOT NULL COMMENT '层级,从0开始',
`tree_leaf` bit(1) NOT NULL COMMENT '是否叶子节点1=是0=否',
`enabled` bit(1) NOT NULL COMMENT '状态',
`create_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '更新者',
`create_time` datetime NOT NULL COMMENT '创建日期',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
KEY `inx_pid` (`pid`),
KEY `inx_enabled` (`enabled`)
) ENGINE=InnoDB AUTO_INCREMENT=56 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=COMPACT COMMENT='公司&部门';
/*Table structure for table `sys_dict` */
DROP TABLE IF EXISTS `sys_dict`;
CREATE TABLE `sys_dict` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(255) NOT NULL COMMENT '字典名称',
`description` varchar(255) DEFAULT NULL COMMENT '描述',
`create_by` varchar(255) DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) DEFAULT NULL COMMENT '更新者',
`create_time` datetime DEFAULT NULL COMMENT '创建日期',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='数据字典';
/*Table structure for table `sys_dict_detail` */
DROP TABLE IF EXISTS `sys_dict_detail`;
CREATE TABLE `sys_dict_detail` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`dict_id` bigint(20) DEFAULT NULL COMMENT '字典id',
`label` varchar(255) NOT NULL COMMENT '字典标签',
`value` varchar(255) NOT NULL COMMENT '字典值',
`sort` int(11) DEFAULT NULL COMMENT '排序',
`create_by` varchar(255) DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) DEFAULT NULL COMMENT '更新者',
`create_time` datetime DEFAULT NULL COMMENT '创建日期',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
KEY `FK5tpkputc6d9nboxojdbgnpmyb` (`dict_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='数据字典详情';
/*Table structure for table `sys_job` */
DROP TABLE IF EXISTS `sys_job`;
CREATE TABLE `sys_job` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(150) NOT NULL COMMENT '岗位名称',
`enabled` bit(1) NOT NULL COMMENT '岗位状态',
`sort` int(11) DEFAULT NULL COMMENT '排序',
`create_by` varchar(255) DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) DEFAULT NULL COMMENT '更新者',
`create_time` datetime DEFAULT NULL COMMENT '创建日期',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `uniq_name` (`name`),
KEY `inx_enabled` (`enabled`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='岗位';
/*Table structure for table `sys_log` */
DROP TABLE IF EXISTS `sys_log`;
CREATE TABLE `sys_log` (
`id` bigint(20) NOT NULL COMMENT 'ID',
`description` varchar(255) DEFAULT NULL,
`log_type` varchar(255) DEFAULT NULL,
`method` varchar(255) DEFAULT NULL,
`params` text,
`request_ip` varchar(255) DEFAULT NULL,
`time` bigint(20) DEFAULT NULL,
`username` varchar(255) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
`browser` varchar(255) DEFAULT NULL,
`exception_detail` text,
`create_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
KEY `log_create_time_index` (`create_time`),
KEY `inx_log_type` (`log_type`(191))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='系统日志';
/*Table structure for table `sys_menu` */
DROP TABLE IF EXISTS `sys_menu`;
CREATE TABLE `sys_menu` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`pid` bigint(20) DEFAULT NULL COMMENT '上级菜单ID',
`sub_count` int(11) DEFAULT '0' COMMENT '子菜单数目',
`type` int(11) DEFAULT NULL COMMENT '0=目录,1=菜单,2=按钮',
`title` varchar(150) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '菜单标题',
`title_letter` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '标题首字母',
`component_name` varchar(150) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '组件名称',
`component` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '组件',
`sort` int(11) DEFAULT NULL COMMENT '排序',
`icon` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '图标',
`path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '链接地址',
`i_frame` bit(1) DEFAULT NULL COMMENT '是否外链',
`cache` bit(1) DEFAULT b'0' COMMENT '缓存',
`hidden` bit(1) DEFAULT b'0' COMMENT '隐藏',
`permission` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '权限',
`create_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '更新者',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建日期',
`update_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `uniq_title` (`title`),
UNIQUE KEY `uniq_name` (`component_name`),
KEY `inx_pid` (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=165 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=COMPACT COMMENT='系统菜单';
/*Table structure for table `sys_quartz_job` */
DROP TABLE IF EXISTS `sys_quartz_job`;
CREATE TABLE `sys_quartz_job` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`bean_name` varchar(255) DEFAULT NULL COMMENT 'Spring Bean名称',
`cron_expression` varchar(255) DEFAULT NULL COMMENT 'cron 表达式',
`is_pause` bit(1) DEFAULT NULL COMMENT '状态:1暂停、0启用',
`job_name` varchar(255) DEFAULT NULL COMMENT '任务名称',
`method_name` varchar(255) DEFAULT NULL COMMENT '方法名称',
`params` varchar(255) DEFAULT NULL COMMENT '参数',
`description` varchar(255) DEFAULT NULL COMMENT '备注',
`person_in_charge` varchar(100) DEFAULT NULL COMMENT '负责人',
`email` varchar(100) DEFAULT NULL COMMENT '报警邮箱',
`sub_task` varchar(100) DEFAULT NULL COMMENT '子任务ID',
`pause_after_failure` bit(1) DEFAULT NULL COMMENT '任务失败后是否暂停',
`create_by` varchar(255) DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) DEFAULT NULL COMMENT '更新者',
`create_time` datetime DEFAULT NULL COMMENT '创建日期',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
KEY `inx_is_pause` (`is_pause`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='定时任务';
/*Table structure for table `sys_quartz_log` */
DROP TABLE IF EXISTS `sys_quartz_log`;
CREATE TABLE `sys_quartz_log` (
`id` bigint(20) NOT NULL COMMENT 'ID',
`bean_name` varchar(255) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`cron_expression` varchar(255) DEFAULT NULL,
`exception_detail` text,
`is_success` bit(1) DEFAULT NULL,
`job_name` varchar(255) DEFAULT NULL,
`method_name` varchar(255) DEFAULT NULL,
`params` varchar(255) DEFAULT NULL,
`time` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='定时任务日志';
/*Table structure for table `sys_role` */
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(150) NOT NULL COMMENT '名称',
`name_letter` varchar(100) DEFAULT NULL COMMENT '名称首字母',
`level` int(11) DEFAULT NULL COMMENT '角色级别',
`description` varchar(255) DEFAULT NULL COMMENT '描述',
`data_scope` varchar(255) DEFAULT NULL COMMENT '数据权限',
`create_by` varchar(255) DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) DEFAULT NULL COMMENT '更新者',
`create_time` datetime DEFAULT NULL COMMENT '创建日期',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `uniq_name` (`name`),
KEY `role_name_index` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='角色表';
/*Table structure for table `sys_roles_depts` */
DROP TABLE IF EXISTS `sys_roles_depts`;
CREATE TABLE `sys_roles_depts` (
`role_id` bigint(20) NOT NULL,
`dept_id` bigint(20) NOT NULL,
PRIMARY KEY (`role_id`,`dept_id`) USING BTREE,
KEY `FK7qg6itn5ajdoa9h9o78v9ksur` (`dept_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='角色-机构关联';
/*Table structure for table `sys_roles_menus` */
DROP TABLE IF EXISTS `sys_roles_menus`;
CREATE TABLE `sys_roles_menus` (
`menu_id` bigint(20) NOT NULL COMMENT '菜单ID',
`role_id` bigint(20) NOT NULL COMMENT '角色ID',
PRIMARY KEY (`menu_id`,`role_id`) USING BTREE,
KEY `FKcngg2qadojhi3a651a5adkvbq` (`role_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='角色菜单关联';
/*Table structure for table `sys_user` */
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` bigint(20) NOT NULL COMMENT 'ID',
`username` varchar(150) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '用户名',
`username_letter` varchar(100) DEFAULT NULL COMMENT '用户名首字母',
`nick_name` varchar(255) DEFAULT NULL COMMENT '昵称',
`gender` varchar(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '性别',
`phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '手机号码',
`email` varchar(150) DEFAULT NULL COMMENT '邮箱',
`avatar_name` varchar(255) DEFAULT NULL COMMENT '头像地址',
`avatar_path` varchar(255) DEFAULT NULL COMMENT '头像真实路径',
`password` varchar(255) DEFAULT NULL COMMENT '密码',
`is_admin` bit(1) DEFAULT b'0' COMMENT '是否为admin账号',
`enabled` bigint(20) NOT NULL COMMENT '状态:1启用、0禁用',
`create_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '创建者',
`update_by` varchar(255) DEFAULT NULL COMMENT '更新着',
`pwd_reset_time` datetime DEFAULT NULL COMMENT '修改密码的时间',
`create_time` datetime NOT NULL COMMENT '创建日期',
`update_time` datetime NOT NULL COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `uniq_username` (`username`),
UNIQUE KEY `uniq_email` (`email`),
KEY `inx_enabled` (`enabled`),
KEY `key_avatar_name` (`avatar_name`(191))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='系统用户';
/*Table structure for table `sys_users_depts` */
DROP TABLE IF EXISTS `sys_users_depts`;
CREATE TABLE `sys_users_depts` (
`user_id` bigint(20) NOT NULL,
`dept_id` bigint(20) NOT NULL,
PRIMARY KEY (`user_id`,`dept_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='用户-机构关联';
/*Table structure for table `sys_users_jobs` */
DROP TABLE IF EXISTS `sys_users_jobs`;
CREATE TABLE `sys_users_jobs` (
`user_id` bigint(20) NOT NULL COMMENT '用户ID',
`job_id` bigint(20) NOT NULL COMMENT '岗位ID',
PRIMARY KEY (`user_id`,`job_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*Table structure for table `sys_users_roles` */
DROP TABLE IF EXISTS `sys_users_roles`;
CREATE TABLE `sys_users_roles` (
`user_id` bigint(20) NOT NULL COMMENT '用户ID',
`role_id` bigint(20) NOT NULL COMMENT '角色ID',
PRIMARY KEY (`user_id`,`role_id`) USING BTREE,
KEY `FKq4eq273l04bpu4efj0jd0jb98` (`role_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='用户角色关联';
/*Table structure for table `test_person` */
DROP TABLE IF EXISTS `test_person`;
CREATE TABLE `test_person` (
`id` bigint(20) NOT NULL,
`name` varchar(200) NOT NULL COMMENT '姓名',
`gender` varchar(8) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '性别(男、女、未知)',
`birthday` date DEFAULT NULL COMMENT '出生日期',
`create_time` datetime NOT NULL COMMENT '创建时间',
`create_by` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '创建人',
`update_time` datetime DEFAULT NULL COMMENT '修改时间',
`update_by` varchar(100) DEFAULT NULL COMMENT '修改人',
`remarks` varchar(200) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='测试表';
/*Table structure for table `tool_alipay_config` */
DROP TABLE IF EXISTS `tool_alipay_config`;
CREATE TABLE `tool_alipay_config` (
`id` bigint(20) NOT NULL COMMENT 'ID',
`app_id` varchar(255) DEFAULT NULL COMMENT '应用ID',
`charset` varchar(255) DEFAULT NULL COMMENT '编码',
`format` varchar(255) DEFAULT NULL COMMENT '类型 固定格式json',
`gateway_url` varchar(255) DEFAULT NULL COMMENT '网关地址',
`notify_url` varchar(255) DEFAULT NULL COMMENT '异步回调',
`private_key` text COMMENT '私钥',
`public_key` text COMMENT '公钥',
`return_url` varchar(255) DEFAULT NULL COMMENT '回调地址',
`sign_type` varchar(255) DEFAULT NULL COMMENT '签名方式',
`sys_service_provider_id` varchar(255) DEFAULT NULL COMMENT '商户号',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='支付宝配置类';
/*Table structure for table `tool_email_config` */
DROP TABLE IF EXISTS `tool_email_config`;
CREATE TABLE `tool_email_config` (
`id` bigint(20) NOT NULL COMMENT 'ID',
`from_user` varchar(255) DEFAULT NULL COMMENT '收件人',
`host` varchar(255) DEFAULT NULL COMMENT '邮件服务器SMTP地址',
`pass` varchar(255) DEFAULT NULL COMMENT '密码',
`port` varchar(255) DEFAULT NULL COMMENT '端口',
`user` varchar(255) DEFAULT NULL COMMENT '发件者用户名',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='邮箱配置';
/*Table structure for table `tool_local_storage` */
DROP TABLE IF EXISTS `tool_local_storage`;
CREATE TABLE `tool_local_storage` (
`id` bigint(20) NOT NULL COMMENT 'ID',
`real_name` varchar(255) DEFAULT NULL COMMENT '文件真实的名称',
`name` varchar(255) DEFAULT NULL COMMENT '文件名',
`suffix` varchar(255) DEFAULT NULL COMMENT '后缀',
`path` varchar(255) DEFAULT NULL COMMENT '路径',
`type` varchar(255) DEFAULT NULL COMMENT '类型',
`size` varchar(100) DEFAULT NULL COMMENT '大小',
`create_by` varchar(255) DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) DEFAULT NULL COMMENT '更新者',
`create_time` datetime DEFAULT NULL COMMENT '创建日期',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='本地存储';
/*Table structure for table `tool_qiniu_config` */
DROP TABLE IF EXISTS `tool_qiniu_config`;
CREATE TABLE `tool_qiniu_config` (
`id` bigint(20) NOT NULL COMMENT 'ID',
`access_key` text COMMENT 'accessKey',
`bucket` varchar(255) DEFAULT NULL COMMENT 'Bucket 识别符',
`host` varchar(255) NOT NULL COMMENT '外链域名',
`secret_key` text COMMENT 'secretKey',
`type` varchar(255) DEFAULT NULL COMMENT '空间类型',
`zone` varchar(255) DEFAULT NULL COMMENT '机房',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='七牛云配置';
/*Table structure for table `tool_qiniu_content` */
DROP TABLE IF EXISTS `tool_qiniu_content`;
CREATE TABLE `tool_qiniu_content` (
`id` bigint(20) NOT NULL COMMENT 'ID',
`bucket` varchar(255) DEFAULT NULL COMMENT 'Bucket 识别符',
`name` varchar(150) DEFAULT NULL COMMENT '文件名称',
`size` varchar(255) DEFAULT NULL COMMENT '文件大小',
`type` varchar(255) DEFAULT NULL COMMENT '文件类型:私有或公开',
`url` varchar(255) DEFAULT NULL COMMENT '文件url',
`suffix` varchar(255) DEFAULT NULL COMMENT '文件后缀',
`update_time` datetime DEFAULT NULL COMMENT '上传或同步的时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `uniq_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT COMMENT='七牛云文件存储';
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
| 1
|
https://github.com/segoja/ember-cli-markdown-editor/blob/master/app/components/markdown-editor.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
ember-cli-markdown-editor
|
segoja
|
JavaScript
|
Code
| 6
| 24
|
export { default } from 'ember-cli-markdown-editor/components/markdown-editor';
| 41,595
|
https://github.com/molecular-workflow-repository/molflow/blob/master/molflow/info.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
molflow
|
molecular-workflow-repository
|
Python
|
Code
| 282
| 782
|
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import collections
from termcolor import cprint
from past.builtins import basestring
from . import config, formatting
def list_workflows(args):
from . import config
from termcolor import colored, cprint
cfg = config.configuration
for config_path in cfg.config_paths:
workflows = cfg.get_local_workflows_by_config_path( config_path )
if len(workflows) > 0:
print('Workflow location: {}'.format(formatting.pretty_path(config_path)))
for workflow in workflows:
meta = workflow.metadata
if not meta.matches(args.keywords):
continue
cprint(' - {name} ({version}): {description}'.format(
name=colored(meta.metadata.get('name',workflow.name+' [Unnamed]'), 'green'),
description=meta.metadata.get('description','No Description'),
version=colored( workflow.versions.default_version()[0], 'red' )))
if args.verbose:
cprint(workflow.versions.format_versions(offset=3))
print('')
def print_metadata(args):
cfg = config.configuration
workflow_config = config.configuration.get_workflow_by_name( args.workflow_name )
workflow = workflow_config.workflow # This is important though unused, as having the actual workflow loads extra data about inputs and outputs into the metadata.
wflowdata = workflow_config.metadata
writedata = collections.OrderedDict()
written = set()
for key in WRITEORDER:
written.add(key)
writekey = key.capitalize()
if key in ('inputs', 'outputs'):
writedata[writekey] = getattr(wflowdata, key, 'not provided')
else:
data = wflowdata.metadata.get(key, 'not provided')
if isinstance(data, basestring):
data = data.strip()
writedata[writekey] = data
if key == 'name':
writedata['Default Version'] = workflow_config.versions.default_version()[0]
for key, value in wflowdata.metadata.items():
if key not in written:
writedata[key] = value
ss = formatting.yml_dump_color(writedata)
cprint(ss)
return
WRITEORDER = ['name', 'inputs', 'outputs', 'description', 'workflow_authors',
'method_authors', 'methods', 'citations']
| 25,143
|
https://github.com/mingwayXue/learning/blob/master/springboot2.0/stream/src/stream/StreamDemo1.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
learning
|
mingwayXue
|
Java
|
Code
| 66
| 259
|
package stream;
import java.util.stream.IntStream;
/**
* Created by mingway on Date:2018-11-29 9:25.
* 修改记录
* 修改后版本: 修改人: 修改日期: 修改内容:
*/
public class StreamDemo1 {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
//外部迭代
int sum1 = 0;
for (int i : nums) {
sum1 += i;
}
System.out.println(sum1);
//内部迭代(使用stream)
//其中map就是中间操作(返回stream流的操作)
//sum为终止操作
int sum2 = IntStream.of(nums).map(i -> i * 2).sum();
System.out.println(sum2);
}
}
| 8,129
|
https://github.com/ericraffin/givemetime/blob/master/server/migration/sqls/20160609212958-project-table-test.sql
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
givemetime
|
ericraffin
|
PLpgSQL
|
Code
| 165
| 786
|
BEGIN;
select no_plan();
set search_path to give_me_time_public, "$user", public, tap;
select has_table('project'::name);
select has_pk('project'::name);
select has_column('project'::name, 'id'::name);
select col_type_is('project'::name, 'id'::name, 'integer');
select col_has_default('project'::name, 'id'::name);
select col_is_pk('project'::name, 'id'::name);
select has_column('project'::name, 'author_id'::name);
select col_type_is('project'::name, 'author_id'::name, 'integer');
select col_hasnt_default('project'::name, 'author_id'::name);
select col_not_null('project'::name, 'author_id'::name);
select col_is_fk('project'::name, 'author_id');
select has_column('project'::name, 'title'::name);
select col_type_is('project'::name, 'title'::name, 'character varying');
select col_hasnt_default('project'::name, 'title'::name);
select col_not_null('project'::name, 'title'::name);
select has_column('project'::name, 'description'::name);
select col_type_is('project'::name, 'description'::name, 'text');
select col_hasnt_default('project'::name, 'description'::name);
select col_is_null('project'::name, 'description'::name);
select has_column('project'::name, 'estimate'::name);
select col_type_is('project'::name, 'estimate'::name, 'integer');
select col_hasnt_default('project'::name, 'estimate'::name);
select col_not_null('project'::name, 'estimate'::name);
select col_has_check('project'::name, 'estimate'::name);
select has_column('project'::name, 'acquired'::name);
select col_type_is('project'::name, 'acquired'::name, 'integer');
select col_has_default('project'::name, 'acquired'::name);
select col_default_is('project'::name, 'acquired'::name, 0);
select col_not_null('project'::name, 'acquired'::name);
select col_has_check('project'::name, 'acquired'::name);
-- author mock
insert into give_me_time_public.person (id, fullname, credit)
values (1, 'abc', 12);
-- valid insert
insert into give_me_time_public.project (author_id, title, estimate, acquired)
values (1, 'abc', 12, 6), (1, 'abc', 1, 0), (1, 'abc', 12, 12);
-- invalid insert
prepare invalid_insert as
insert into give_me_time_public.project (author_id, title, estimate, acquired)
values (1, 'abc', 12, 25);
select throws_ok('invalid_insert');
select finish();
ROLLBACK;
| 44,177
|
https://github.com/celandro/pogoprotos-java/blob/master/src/main/java/POGOProtos/Rpc/GetImagesForPoiOutProtoOrBuilder.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,020
|
pogoprotos-java
|
celandro
|
Java
|
Code
| 112
| 626
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos.Rpc.proto
package POGOProtos.Rpc;
public interface GetImagesForPoiOutProtoOrBuilder extends
// @@protoc_insertion_point(interface_extends:POGOProtos.Rpc.GetImagesForPoiOutProto)
com.google.protobuf.MessageOrBuilder {
/**
* <code>.POGOProtos.Rpc.GetImagesForPoiOutProto.Status status = 1;</code>
* @return The enum numeric value on the wire for status.
*/
int getStatusValue();
/**
* <code>.POGOProtos.Rpc.GetImagesForPoiOutProto.Status status = 1;</code>
* @return The status.
*/
POGOProtos.Rpc.GetImagesForPoiOutProto.Status getStatus();
/**
* <code>repeated .POGOProtos.Rpc.GameClientPhotoGalleryPoiImageProto photo_gallery_poi_images = 2;</code>
*/
java.util.List<POGOProtos.Rpc.GameClientPhotoGalleryPoiImageProto>
getPhotoGalleryPoiImagesList();
/**
* <code>repeated .POGOProtos.Rpc.GameClientPhotoGalleryPoiImageProto photo_gallery_poi_images = 2;</code>
*/
POGOProtos.Rpc.GameClientPhotoGalleryPoiImageProto getPhotoGalleryPoiImages(int index);
/**
* <code>repeated .POGOProtos.Rpc.GameClientPhotoGalleryPoiImageProto photo_gallery_poi_images = 2;</code>
*/
int getPhotoGalleryPoiImagesCount();
/**
* <code>repeated .POGOProtos.Rpc.GameClientPhotoGalleryPoiImageProto photo_gallery_poi_images = 2;</code>
*/
java.util.List<? extends POGOProtos.Rpc.GameClientPhotoGalleryPoiImageProtoOrBuilder>
getPhotoGalleryPoiImagesOrBuilderList();
/**
* <code>repeated .POGOProtos.Rpc.GameClientPhotoGalleryPoiImageProto photo_gallery_poi_images = 2;</code>
*/
POGOProtos.Rpc.GameClientPhotoGalleryPoiImageProtoOrBuilder getPhotoGalleryPoiImagesOrBuilder(
int index);
}
| 43,467
|
https://github.com/borodust/skia/blob/master/tests/sksl/intrinsics/MinFloat.asm.frag
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
skia
|
borodust
|
GLSL
|
Code
| 943
| 2,727
|
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %_entrypoint "_entrypoint" %sk_FragColor %sk_Clockwise
OpExecutionMode %_entrypoint OriginUpperLeft
OpName %sk_FragColor "sk_FragColor"
OpName %sk_Clockwise "sk_Clockwise"
OpName %_UniformBuffer "_UniformBuffer"
OpMemberName %_UniformBuffer 0 "testInputs"
OpMemberName %_UniformBuffer 1 "colorGreen"
OpMemberName %_UniformBuffer 2 "colorRed"
OpName %_entrypoint "_entrypoint"
OpName %main "main"
OpDecorate %sk_FragColor RelaxedPrecision
OpDecorate %sk_FragColor Location 0
OpDecorate %sk_FragColor Index 0
OpDecorate %sk_Clockwise RelaxedPrecision
OpDecorate %sk_Clockwise BuiltIn FrontFacing
OpMemberDecorate %_UniformBuffer 0 Offset 0
OpMemberDecorate %_UniformBuffer 0 RelaxedPrecision
OpMemberDecorate %_UniformBuffer 1 Offset 16
OpMemberDecorate %_UniformBuffer 1 RelaxedPrecision
OpMemberDecorate %_UniformBuffer 2 Offset 32
OpMemberDecorate %_UniformBuffer 2 RelaxedPrecision
OpDecorate %_UniformBuffer Block
OpDecorate %10 Binding 0
OpDecorate %10 DescriptorSet 0
OpDecorate %26 RelaxedPrecision
OpDecorate %35 RelaxedPrecision
OpDecorate %38 RelaxedPrecision
OpDecorate %49 RelaxedPrecision
OpDecorate %52 RelaxedPrecision
OpDecorate %62 RelaxedPrecision
OpDecorate %63 RelaxedPrecision
OpDecorate %73 RelaxedPrecision
OpDecorate %77 RelaxedPrecision
OpDecorate %85 RelaxedPrecision
OpDecorate %88 RelaxedPrecision
OpDecorate %97 RelaxedPrecision
OpDecorate %100 RelaxedPrecision
OpDecorate %110 RelaxedPrecision
OpDecorate %112 RelaxedPrecision
OpDecorate %124 RelaxedPrecision
OpDecorate %127 RelaxedPrecision
OpDecorate %128 RelaxedPrecision
%float = OpTypeFloat 32
%v4float = OpTypeVector %float 4
%_ptr_Output_v4float = OpTypePointer Output %v4float
%sk_FragColor = OpVariable %_ptr_Output_v4float Output
%bool = OpTypeBool
%_ptr_Input_bool = OpTypePointer Input %bool
%sk_Clockwise = OpVariable %_ptr_Input_bool Input
%_UniformBuffer = OpTypeStruct %v4float %v4float %v4float
%_ptr_Uniform__UniformBuffer = OpTypePointer Uniform %_UniformBuffer
%10 = OpVariable %_ptr_Uniform__UniformBuffer Uniform
%void = OpTypeVoid
%15 = OpTypeFunction %void
%18 = OpTypeFunction %v4float
%false = OpConstantFalse %bool
%_ptr_Uniform_v4float = OpTypePointer Uniform %v4float
%int = OpTypeInt 32 1
%int_0 = OpConstant %int 0
%float_0_5 = OpConstant %float 0.5
%float_n1_25 = OpConstant %float -1.25
%v2float = OpTypeVector %float 2
%float_0 = OpConstant %float 0
%40 = OpConstantComposite %v2float %float_n1_25 %float_0
%v2bool = OpTypeVector %bool 2
%v3float = OpTypeVector %float 3
%53 = OpConstantComposite %v3float %float_n1_25 %float_0 %float_0_5
%v3bool = OpTypeVector %bool 3
%64 = OpConstantComposite %v4float %float_n1_25 %float_0 %float_0_5 %float_0_5
%v4bool = OpTypeVector %bool 4
%int_1 = OpConstant %int 1
%102 = OpConstantComposite %v3float %float_n1_25 %float_0 %float_0
%float_1 = OpConstant %float 1
%114 = OpConstantComposite %v4float %float_n1_25 %float_0 %float_0 %float_1
%_ptr_Function_v4float = OpTypePointer Function %v4float
%int_2 = OpConstant %int 2
%_entrypoint = OpFunction %void None %15
%16 = OpLabel
%17 = OpFunctionCall %v4float %main
OpStore %sk_FragColor %17
OpReturn
OpFunctionEnd
%main = OpFunction %v4float None %18
%19 = OpLabel
%118 = OpVariable %_ptr_Function_v4float Function
%22 = OpAccessChain %_ptr_Uniform_v4float %10 %int_0
%26 = OpLoad %v4float %22
%27 = OpCompositeExtract %float %26 0
%21 = OpExtInst %float %1 FMin %27 %float_0_5
%30 = OpFOrdEqual %bool %21 %float_n1_25
OpSelectionMerge %32 None
OpBranchConditional %30 %31 %32
%31 = OpLabel
%34 = OpAccessChain %_ptr_Uniform_v4float %10 %int_0
%35 = OpLoad %v4float %34
%36 = OpVectorShuffle %v2float %35 %35 0 1
%38 = OpCompositeConstruct %v2float %float_0_5 %float_0_5
%33 = OpExtInst %v2float %1 FMin %36 %38
%41 = OpFOrdEqual %v2bool %33 %40
%43 = OpAll %bool %41
OpBranch %32
%32 = OpLabel
%44 = OpPhi %bool %false %19 %43 %31
OpSelectionMerge %46 None
OpBranchConditional %44 %45 %46
%45 = OpLabel
%48 = OpAccessChain %_ptr_Uniform_v4float %10 %int_0
%49 = OpLoad %v4float %48
%50 = OpVectorShuffle %v3float %49 %49 0 1 2
%52 = OpCompositeConstruct %v3float %float_0_5 %float_0_5 %float_0_5
%47 = OpExtInst %v3float %1 FMin %50 %52
%54 = OpFOrdEqual %v3bool %47 %53
%56 = OpAll %bool %54
OpBranch %46
%46 = OpLabel
%57 = OpPhi %bool %false %32 %56 %45
OpSelectionMerge %59 None
OpBranchConditional %57 %58 %59
%58 = OpLabel
%61 = OpAccessChain %_ptr_Uniform_v4float %10 %int_0
%62 = OpLoad %v4float %61
%63 = OpCompositeConstruct %v4float %float_0_5 %float_0_5 %float_0_5 %float_0_5
%60 = OpExtInst %v4float %1 FMin %62 %63
%65 = OpFOrdEqual %v4bool %60 %64
%67 = OpAll %bool %65
OpBranch %59
%59 = OpLabel
%68 = OpPhi %bool %false %46 %67 %58
OpSelectionMerge %70 None
OpBranchConditional %68 %69 %70
%69 = OpLabel
%72 = OpAccessChain %_ptr_Uniform_v4float %10 %int_0
%73 = OpLoad %v4float %72
%74 = OpCompositeExtract %float %73 0
%75 = OpAccessChain %_ptr_Uniform_v4float %10 %int_1
%77 = OpLoad %v4float %75
%78 = OpCompositeExtract %float %77 0
%71 = OpExtInst %float %1 FMin %74 %78
%79 = OpFOrdEqual %bool %71 %float_n1_25
OpBranch %70
%70 = OpLabel
%80 = OpPhi %bool %false %59 %79 %69
OpSelectionMerge %82 None
OpBranchConditional %80 %81 %82
%81 = OpLabel
%84 = OpAccessChain %_ptr_Uniform_v4float %10 %int_0
%85 = OpLoad %v4float %84
%86 = OpVectorShuffle %v2float %85 %85 0 1
%87 = OpAccessChain %_ptr_Uniform_v4float %10 %int_1
%88 = OpLoad %v4float %87
%89 = OpVectorShuffle %v2float %88 %88 0 1
%83 = OpExtInst %v2float %1 FMin %86 %89
%90 = OpFOrdEqual %v2bool %83 %40
%91 = OpAll %bool %90
OpBranch %82
%82 = OpLabel
%92 = OpPhi %bool %false %70 %91 %81
OpSelectionMerge %94 None
OpBranchConditional %92 %93 %94
%93 = OpLabel
%96 = OpAccessChain %_ptr_Uniform_v4float %10 %int_0
%97 = OpLoad %v4float %96
%98 = OpVectorShuffle %v3float %97 %97 0 1 2
%99 = OpAccessChain %_ptr_Uniform_v4float %10 %int_1
%100 = OpLoad %v4float %99
%101 = OpVectorShuffle %v3float %100 %100 0 1 2
%95 = OpExtInst %v3float %1 FMin %98 %101
%103 = OpFOrdEqual %v3bool %95 %102
%104 = OpAll %bool %103
OpBranch %94
%94 = OpLabel
%105 = OpPhi %bool %false %82 %104 %93
OpSelectionMerge %107 None
OpBranchConditional %105 %106 %107
%106 = OpLabel
%109 = OpAccessChain %_ptr_Uniform_v4float %10 %int_0
%110 = OpLoad %v4float %109
%111 = OpAccessChain %_ptr_Uniform_v4float %10 %int_1
%112 = OpLoad %v4float %111
%108 = OpExtInst %v4float %1 FMin %110 %112
%115 = OpFOrdEqual %v4bool %108 %114
%116 = OpAll %bool %115
OpBranch %107
%107 = OpLabel
%117 = OpPhi %bool %false %94 %116 %106
OpSelectionMerge %122 None
OpBranchConditional %117 %120 %121
%120 = OpLabel
%123 = OpAccessChain %_ptr_Uniform_v4float %10 %int_1
%124 = OpLoad %v4float %123
OpStore %118 %124
OpBranch %122
%121 = OpLabel
%125 = OpAccessChain %_ptr_Uniform_v4float %10 %int_2
%127 = OpLoad %v4float %125
OpStore %118 %127
OpBranch %122
%122 = OpLabel
%128 = OpLoad %v4float %118
OpReturnValue %128
OpFunctionEnd
| 25,821
|
https://github.com/pangPython/pms/blob/master/src/main/java/cc/mrbird/febs/pms/entity/ProjectMember.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
pms
|
pangPython
|
Java
|
Code
| 41
| 176
|
package cc.mrbird.febs.pms.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
/**
* 项目成员实体类
* @author pangPython
*/
@Data
@TableName("project_member")
public class ProjectMember implements Serializable {
private static final long serialVersionUID = 7477252506301604997L;
@TableId("project_id")
private Long projectId;
@TableId("user_id")
private Long userId;
}
| 24,770
|
https://github.com/msyml/site/blob/master/src/views/Main.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
site
|
msyml
|
Vue
|
Code
| 292
| 1,012
|
<template>
<div class="main">
<div class="header">
<span
class="btn"
:class="{ check: item.path === checkItem }"
@click="handleClick(item)"
v-for="item in menuList"
:key="item.label"
>{{ item.label }}</span
>
</div>
<router-view class="routerBody" />
<div class="footer">
<p>浙ICP备2021005058号</p>
<div class="gongan">
<img src="../assets/beian.png" />
<span>浙公网安备 33032402002173号</span>
</div>
<p>© Copyright 2021 抹上一抹凉</p>
</div>
</div>
</template>
<script>
import { onMounted, reactive, toRefs } from "vue";
import { useRouter, useRoute } from "vue-router";
export default {
name: "Main",
setup() {
const router = useRouter();
const route = useRoute();
const state = reactive({
checkItem: "/home",
menuList: [
{
label: "关于",
active: "jump",
path: "/aboutMe",
icon: "iconfont icon-aboutme",
},
{
label: "博客",
active: "jump",
path: "/blog",
icon: "iconfont icon-boke",
},
// {
// label: "码云",
// active: "open",
// path: "https://gitee.com/a-little-cool",
// icon: "iconfont icon-mayun",
// },
{
label: "首页",
active: "jump",
path: "/home",
icon: "iconfont icon-home",
},
],
});
onMounted(() => {
checkRoute();
});
const handleClick = (item) => {
if (item.active == "open") {
window.open(item.path);
} else {
state.checkItem = item.path;
router.push(item.path);
}
};
const checkRoute = () => {
if (route.path) {
state.checkItem = route.path;
}
};
return {
...toRefs(state),
handleClick,
checkRoute,
};
},
};
</script>
<style scoped lang="scss">
.main {
display: flex;
min-height: 100%;
flex-direction: column;
.header {
display: flex;
flex-direction: row-reverse;
position: fixed;
left: 0;
z-index: 5;
right: 0;
background: white;
top: 0;
padding: 8px 0;
border-bottom: 1px solid #eee;
.btn {
color: #2e62cd;
margin: 0 24px;
padding: 4px;
cursor: pointer;
}
.check {
background-color: #2e62cd;
color: white;
border-radius: 8px;
}
}
.routerBody {
padding: 50px 0;
flex: 1;
}
.footer {
display: flex;
position: fixed;
z-index: 5;
right: 0;
width: 100%;
bottom: 0;
justify-content: space-around;
background: white;
border-top: 1px solid #eee;
align-items: center;
flex-direction: row;
font-size: 12px;
color: #aaaabd;
line-height: 16px;
img {
width: 16px;
height: 16px;
}
}
}
</style>
| 50,227
|
https://github.com/OldBeafantles/Discode/blob/master/bot.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Discode
|
OldBeafantles
|
Python
|
Code
| 795
| 2,875
|
"""The bot"""
import asyncio
import aiohttp
from datetime import datetime, timedelta
import discord
from discord.ext import commands
import importlib
from modules.utils import utils
import os
import sys
# Useful functions
if sys.platform == "win32" or sys.platform == "win64":
def clear():
return os.system("cls")
else:
def clear():
return os.system("clear")
def _prefix_callable(bot, msg):
return [
"<@!" + str(bot.user.id) + "> ", "<@" + str(bot.user.id) + "> ",
bot.prefix
]
class Discode(commands.Bot):
"""The bot class"""
def load_config(self):
"""Loads self.config_file_path, gets the infos if the file
doesn't exists"""
if not os.path.exists(self.config_file_path):
json_data = {}
token = input("Please put your bot's token here:\n> ")
print("DO NOT SPREAD YOUR bot'S TOKEN TO ANYONE. NEVER.\n")
prefix = input("\n\nPlease put your bot's prefix here:\n> ")
description = input("\n\nPlease put a little description "
"for your bot (optionnal)\n> ")
if description == "":
description = ("A bot that runs code.\nIf you have any "
"problem with Discode or if you just want "
"to be in the development server, you can "
"join it using this link: discord.gg/UpYc98d")
owner_id = int(input("\n\nPlease put your ID:\n> "))
json_data["token"] = token
json_data["prefix"] = prefix
json_data["description"] = description
json_data["owner id"] = owner_id
self.token = token
self.prefix = prefix
self.description = description
self.config_owner_id = owner_id
if not os.path.isdir("settings"):
os.makedirs("settings")
utils.save_json(json_data, self.config_file_path)
else:
json_data = utils.load_json(self.config_file_path)
if "token" not in json_data or "prefix" not in json_data \
or "description" not in json_data \
or "owner id" not in json_data:
print("\"settings/config.json\" is incorrect! "
"The bot will be reseted, "
"please restart the bot!")
os.remove(self.config_file_path)
sys.exit(1)
else:
self.token = json_data["token"]
self.prefix = json_data["prefix"]
self.description = json_data["description"]
self.config_owner_id = json_data["owner id"]
def reset_infos(self):
"""Resets bot's info"""
json_data = {}
json_data["created at"] = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
json_data["total commands"] = 0
json_data["total runtime"] = 0
self.created_at = datetime.now()
self.total_commands = 0
self.total_runtime = timedelta(seconds=0)
# Shouldn't be call, except if the user deletes this folder
if not os.path.isdir("settings"):
os.makedirs("settings")
utils.save_json(json_data, self.info_file_path)
def load_infos(self):
"""Load bot's info"""
if not os.path.exists(self.info_file_path):
self.reset_infos()
else:
json_data = utils.load_json(self.info_file_path)
if "created at" not in json_data or "total commands" \
not in json_data or "total runtime" not in json_data:
print("\"settings/infos.json\" is incorrect! The info of "
"the bot will be reseted!")
self.reset_infos()
else:
self.created_at = datetime.strptime(json_data["created at"],
"%d/%m/%Y %H:%M:%S")
self.total_commands = json_data["total commands"]
self.total_runtime = timedelta(
seconds=json_data["total runtime"])
def load_blacklist(self):
"""Loads the blacklist"""
if not os.path.exists(self.blacklist_file_path):
if not os.path.isdir("settings"):
os.makedirs("settings")
utils.save_json(self.blacklist, self.blacklist_file_path)
else:
self.blacklist = utils.load_json(self.blacklist_file_path)
def load_modules(self):
"""Loads the bot modules"""
if not os.path.exists(self.modules_file_path):
json_data = self.default_modules
self.modules = self.default_modules
utils.save_json(json_data, self.modules_file_path)
print("\n\n")
self.modules = set(utils.load_json(self.modules_file_path))
to_remove = []
for mod in self.modules:
module_path = "modules/" + mod + ".py"
module_name = module_path.replace('/', '.')[:-3]
if not os.path.exists(module_path):
print("\n\nThe module \"" + mod + "\" doesn't exist!")
to_remove.append(mod)
else:
try:
if mod not in self.loaded_modules:
print("Loading " + mod + " module...")
module = importlib.import_module(
module_path.replace('/', '.')[:-3])
importlib.reload(module)
super().load_extension(module_name)
self.loaded_modules.append(mod)
except SyntaxError as ex:
print("Error in " + mod + " module:\n\n" + str(ex) + "\n\n")
to_remove.append(mod)
for mod in to_remove:
self.modules.remove(mod)
utils.save_json(list(self.modules), self.modules_file_path)
def init_data(self):
if not os.path.isdir("data"):
os.makedirs("data")
def __init__(self, loop):
clear()
self.token = ""
self.prefix = ""
self.description = ""
self.config_owner_id = -1
self.config_file_path = "settings/config.json"
self.load_config()
self.created_at = None
self.total_commands = 0
self.total_runtime = None
self.info_file_path = "settings/infos.json"
self.load_infos()
self.bot = discord.Client()
self.default_modules = ["base", "admin", "code"]
self.loaded_modules = []
self.modules_file_path = "settings/modules.json"
self.blacklist_file_path = "settings/blacklist.json"
self.blacklist = []
self.load_blacklist()
self.init_data()
self.invite_link = ""
self.modules = []
self.version = "1.1.0"
self.launched_at = datetime.now()
super().__init__(command_prefix=_prefix_callable,
description=self.description,
loop=loop)
self.session = aiohttp.ClientSession(loop=loop)
self.dev_server_invitation_link = "discord.gg/UpYc98d"
clear()
async def close(self):
await super().close()
await self.session.close()
def run_bot():
"""Runs the bot"""
loop = asyncio.get_event_loop()
bot = Discode(loop)
@bot.event
async def on_ready():
"""Triggers when the bot just logged in"""
print("Logged in as " + bot.user.name + "#" + bot.user.discriminator)
print(str(len(bot.guilds)) + " servers")
print(str(len(set(bot.get_all_channels()))) + " channels")
print(str(len(set(bot.get_all_members()))) + " members")
bot.invite_link = "https://discordapp.com/oauth2/authorize?client_id="\
+ str(bot.user.id) + "&scope=bot"
print("\nHere's the invitation link for your bot: " + bot.invite_link)
bot.load_modules()
bot.launched_at = datetime.now()
print("\n" + str(len(bot.loaded_modules)) + " modules loaded.")
@bot.event
async def on_command(ctx):
"""Triggers AFTER a command is called"""
bot.total_commands += 1
@bot.event
async def on_message(message):
"""Triggers when the bot reads a new message"""
if message.author.id not in bot.blacklist:
if message.content.startswith(bot.prefix + "code```"):
await bot.send_message(
destination=message.channel,
content="https://i.imgur.com/eGMJXqg.png")
else:
await bot.process_commands(message)
@bot.event
async def on_command_error(ctx, error):
await ctx.message.channel.send(error)
try:
bot.run(bot.token, reconnect=True)
except discord.LoginFailure:
print("Couldn't log in, your bot's token might be incorrect! "
"If it's not, then check Discord's status here: "
"https://status.discordapp.com/")
answer = input("Do you want to change your bot's token? (yes/no)\n> ")
if answer.upper() == "YES":
token = input("\n\nPlease put your new bot's token here:\n> ")
json_data = utils.load_json("settings/infos.json")
json_data["token"] = token
bot.token = token
utils.save_json(json_data, "settings/infos.json")
except KeyboardInterrupt:
loop.run_util_complete(bot.close())
except discord.GatewayNotFound:
print("Gateway not found! The problem comes from Discord.")
sys.exit(1)
except discord.ConnectionClosed:
print("No more connection.")
loop.run_util_complete(bot.close())
sys.exit(1)
except discord.HTTPException:
print("HTTP Error.")
loop.run_util_complete(bot.close())
sys.exit(1)
except Exception as e:
print(e)
loop.run_util_complete(bot.close())
sys.exit(1)
finally:
loop.close()
| 38,590
|
https://github.com/chumakovvchuma/smooth.js/blob/master/packages/smooth/src/graphql/definitions/index.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
smooth.js
|
chumakovvchuma
|
JavaScript
|
Code
| 76
| 148
|
import * as Date from './Date'
import * as directives from './directives'
import * as Media from './Media'
import * as Image from './Image'
import * as Link from './Link'
import * as Metadata from './Metadata'
import * as Mutation from './Mutation'
import * as Query from './Query'
import * as schema from './schema'
import * as Upload from './Upload'
export const definitions = [
Date,
Upload,
directives,
Media,
Image,
Link,
Metadata,
Mutation,
Query,
schema,
]
| 15,804
|
https://github.com/maxbyz/hydra/blob/master/src/event.js
|
Github Open Source
|
Open Source
|
MIT
| 2,013
|
hydra
|
maxbyz
|
JavaScript
|
Code
| 286
| 900
|
//
// Hydra - HTML5 mobile game engine
// https://github.com/aduros/hydra/blob/master/LICENSE.txt
goog.provide("hydra.EventDispatcher");
goog.provide("hydra.ListenerManager");
goog.require("hydra.array");
/** @constructor */
hydra.EventDispatcher = function () {
/**
* @private
*/
this.listenerMap = {};
}
hydra.EventDispatcher.prototype.addEventListener = function (name, handler) {
var handlers = this.listenerMap[name];
if (handlers == null) {
this.listenerMap[name] = [ handler ];
} else {
hydra.array.push(handlers, handler);
}
}
hydra.EventDispatcher.prototype.removeEventListener = function (name, handler) {
var handlers = this.listenerMap[name];
if (handlers != null) {
hydra.array.remove(handlers, handler);
}
}
/**
* @param {string|number} name
* @param {...*} var_args
*/
hydra.EventDispatcher.prototype.dispatchEvent = function (name, var_args) {
var handlers = this.listenerMap[name];
if (handlers != null) {
var args = hydra.array.fromArgs(arguments);
args.shift();
for (var ii = 0; ii < handlers.length; ++ii) {
var handler = handlers[ii];
handler.apply(undefined, args);
}
}
}
/**
* @constructor
*/
hydra.ListenerManager = function () {
/**
* @type Array.<hydra.RegisteredListener>
* @private
*/
this.listeners = [];
}
/**
* @param {EventTarget|hydra.EventDispatcher} dispatcher
* @param {string|number} eventName
*/
hydra.ListenerManager.prototype.registerListener = function (dispatcher, eventName, handler) {
hydra.array.push(this.listeners, new hydra.RegisteredListener(dispatcher, eventName, handler));
dispatcher.addEventListener(eventName, handler, false);
}
/**
* @param {EventTarget|hydra.EventDispatcher} dispatcher
* @param {string|number} eventName
*/
hydra.ListenerManager.prototype.unregisterListener = function (dispatcher, eventName, handler) {
for (var ii = 0; ii < this.listeners.length; ++ii) {
var listener = this.listeners[ii];
if (listener.dispatcher == dispatcher &&
listener.eventName == eventName &&
listener.handler == handler) {
this.listeners.splice(ii, 1);
break;
}
}
dispatcher.removeEventListener(eventName, handler, false);
}
hydra.ListenerManager.prototype.unregisterAllListeners = function () {
//for (var ii = 0, ll = this.listeners.length; ii < ll; ++ii) {
for (var ii = 0; ii < this.listeners.length; ++ii) {
var listener = this.listeners[ii];
listener.dispatcher.removeEventListener(listener.eventName, listener.handler, false);
}
this.listeners = [];
}
/**
* @constructor
* @private
*/
hydra.RegisteredListener = function (dispatcher, eventName, handler) {
this.dispatcher = dispatcher;
this.eventName = eventName;
this.handler = handler;
}
| 27,201
|
https://github.com/dfilitto/ProjetosXamarinForms/blob/master/InglesCriancas/InglesCriancas/InglesCriancas.UWP/CloseApplication.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
ProjetosXamarinForms
|
dfilitto
|
C#
|
Code
| 29
| 95
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
namespace InglesCriancas.UWP
{
public class CloseApplication : ICloseApplication
{
public void closeApplication()
{
Application.Current.Exit();
}
}
}
| 12,966
|
https://github.com/edgardozoppi/analysis-net/blob/master/Backend/Analysis/ReachingDefinitionsAnalysis.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
analysis-net
|
edgardozoppi
|
C#
|
Code
| 567
| 1,985
|
// Copyright (c) Edgardo Zoppi. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information.
using Backend.ThreeAddressCode;
using Backend.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Backend.ThreeAddressCode.Instructions;
using Backend.ThreeAddressCode.Values;
namespace Backend.Analysis
{
public class ReachingDefinitionsAnalysis : ForwardDataFlowAnalysis<Subset<DefinitionInstruction>>
{
private DefinitionInstruction[] definitions;
private IDictionary<IVariable, Subset<DefinitionInstruction>> variable_definitions;
private DataFlowAnalysisResult<Subset<DefinitionInstruction>>[] result;
private MapList<DefinitionInstruction, Instruction> def_use;
private MapList<Instruction, DefinitionInstruction> use_def;
private Subset<DefinitionInstruction>[] GEN;
private Subset<DefinitionInstruction>[] KILL;
public ReachingDefinitionsAnalysis(ControlFlowGraph cfg)
: base(cfg)
{
}
public MapList<DefinitionInstruction, Instruction> DefinitionUses
{
get { return def_use; }
}
public MapList<Instruction, DefinitionInstruction> UseDefinitions
{
get { return use_def; }
}
public void ComputeDefUseAndUseDefChains()
{
if (this.result == null) throw new InvalidOperationException("Analysis result not available.");
this.def_use = new MapList<DefinitionInstruction, Instruction>();
this.use_def = new MapList<Instruction, DefinitionInstruction>();
foreach (var node in this.cfg.Nodes)
{
var input = new HashSet<DefinitionInstruction>();
var node_result = this.result[node.Id];
if (node_result.Input != null)
{
node_result.Input.ToSet(input);
}
var definitions = input.ToMapSet(def => def.Result);
foreach (var instruction in node.Instructions)
{
// use-def
foreach (var variable in instruction.UsedVariables)
{
if (definitions.ContainsKey(variable))
{
var var_defs = definitions[variable];
foreach (var definition in var_defs)
{
def_use.Add(definition, instruction);
use_def.Add(instruction, definition);
}
}
else
{
// Add all uses, even those with no reaching definitions.
use_def.Add(instruction);
}
}
// def-use
if (instruction is DefinitionInstruction)
{
var definition = instruction as DefinitionInstruction;
if (definition.HasResult)
{
var variable = definition.Result;
definitions.Remove(variable);
definitions.Add(variable, definition);
// Add all definitions, even those with no uses.
def_use.Add(definition);
}
}
}
}
}
public override DataFlowAnalysisResult<Subset<DefinitionInstruction>>[] Analyze()
{
this.ComputeDefinitions();
this.ComputeGen();
this.ComputeKill();
var result = base.Analyze();
this.result = result;
this.definitions = null;
this.variable_definitions = null;
this.GEN = null;
this.KILL = null;
return result;
}
protected override Subset<DefinitionInstruction> InitialValue(CFGNode node)
{
return GEN[node.Id];
}
protected override bool Compare(Subset<DefinitionInstruction> left, Subset<DefinitionInstruction> right)
{
return left.Equals(right);
}
protected override Subset<DefinitionInstruction> Join(Subset<DefinitionInstruction> left, Subset<DefinitionInstruction> right)
{
var result = left.Clone();
result.Union(right);
return result;
}
protected override Subset<DefinitionInstruction> Flow(CFGNode node, Subset<DefinitionInstruction> input)
{
var output = input.Clone();
var kill = KILL[node.Id];
var gen = GEN[node.Id];
output.Except(kill);
output.Union(gen);
return output;
}
private void ComputeDefinitions()
{
var result = new List<DefinitionInstruction>();
foreach (var node in this.cfg.Nodes)
{
foreach (var instruction in node.Instructions)
{
if (instruction is DefinitionInstruction)
{
var definition = instruction as DefinitionInstruction;
if (definition.HasResult)
{
result.Add(definition);
}
}
}
}
this.definitions = result.ToArray();
this.variable_definitions = new Dictionary<IVariable, Subset<DefinitionInstruction>>();
for (var i = 0; i < this.definitions.Length; ++i)
{
var definition = this.definitions[i];
Subset<DefinitionInstruction> defs = null;
if (variable_definitions.ContainsKey(definition.Result))
{
defs = variable_definitions[definition.Result];
}
else
{
defs = this.definitions.ToEmptySubset();
variable_definitions[definition.Result] = defs;
}
defs.Add(i);
}
}
private void ComputeGen()
{
GEN = new Subset<DefinitionInstruction>[this.cfg.Nodes.Count];
var index = 0;
foreach (var node in this.cfg.Nodes)
{
var defined = new Dictionary<IVariable, int>();
foreach (var instruction in node.Instructions)
{
if (instruction is DefinitionInstruction)
{
var definition = instruction as DefinitionInstruction;
if (definition.HasResult)
{
defined[definition.Result] = index;
index++;
}
}
}
// We only add to gen those definitions of node
// that reach the end of the basic block
var gen = this.definitions.ToEmptySubset();
foreach (var def in defined.Values)
{
gen.Add(def);
}
GEN[node.Id] = gen;
}
}
private void ComputeKill()
{
KILL = new Subset<DefinitionInstruction>[this.cfg.Nodes.Count];
foreach (var node in this.cfg.Nodes)
{
// We add to kill all definitions of the variables defined at node
var kill = this.definitions.ToEmptySubset();
foreach (var instruction in node.Instructions)
{
if (instruction is DefinitionInstruction)
{
var definition = instruction as DefinitionInstruction;
if (definition.HasResult)
{
var defs = this.variable_definitions[definition.Result];
kill.Union(defs);
}
}
}
KILL[node.Id] = kill;
}
}
}
}
| 2,818
|
https://github.com/matzegoebel/run_wrf/blob/master/run_wrf/tests/test_submit.py
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,021
|
run_wrf
|
matzegoebel
|
Python
|
Code
| 1,091
| 4,293
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 26 12:26:51 2019
Test launch_jobs function
@author: Matthias Göbel
"""
import os
from run_wrf.launch_jobs import launch_jobs
import pytest
from run_wrf.tools import Capturing
from collections import Counter
import run_wrf.configs.test.config_test as conf
import shutil
import time
import xarray as xr
from run_wrf import tools, get_namelist, vertical_grid
import glob
import pandas as pd
from pathlib import Path
end_time = "2018-06-20_07:06:00"
success = {True: 'wrf: SUCCESS COMPLETE IDEAL INIT',
False: 'd01 {} wrf: SUCCESS COMPLETE WRF'.format(end_time)}
params = conf.params
outd = params["outpath"]
rund = params["run_path"]
test_dir = os.getcwd()
code_dir = "/".join(test_dir.split("/")[:-1])
batch_dict = {"slurm": "sbatch", "sge": "qsub"}
# %%tests
def test_basic():
"""
Test basic submit functionality.
Initialize and run WRF; Check behaviour when run already exists
Restart run; Check that errors are raised
"""
# run wrf
launch_jobs(init=True, exist="o", config_file="test.config_test")
combs = launch_jobs(init=False, verbose=True, wait=True, exist="o",
config_file="test.config_test")
# test namelist
rpath = combs["run_dir"][0] + "_0"
ID = "_".join(rpath.split("/")[-1].split("_")[1:])
namelists = []
namelists.append(get_namelist.namelist_to_dict(rpath + "/namelist.input"))
namelists.append(get_namelist.namelist_to_dict("./tests/test_data/namelists/namelist.{}".format(ID)))
for key in set([*namelists[0].keys(), *namelists[1].keys()]):
if "_outname" not in key:
equal = namelists[0][key] == namelists[1][key]
if not equal:
print("unequal namelist settings:", key, namelists[0][key], namelists[1][key])
assert equal
input_sounding = tools.read_file(rpath + "/input_sounding")
build = os.path.join(combs["build_path"][0], combs["parallel_build"][0], "test", "em_les")
input_sounding_corr = tools.read_file(build + "/input_sounding_meanwind")
assert input_sounding == input_sounding_corr
# check output data
for run in os.listdir(outd):
outfiles = sorted(os.listdir(os.path.join(outd, run)))
outfiles_corr = ['fastout_d01_2018-06-20_07:00:00', 'wrfout_d01_2018-06-20_07:00:00']
assert outfiles_corr == outfiles
for f, freq in zip(outfiles, ["1", "2"]):
ds = xr.open_dataset(os.path.join(outd, run, f), decode_times=False, engine="scipy")
t = tools.extract_times(ds)
t_corr = pd.date_range(start="2018-06-20T07:00:00", end=end_time.replace("_", "T"),
freq=freq + "min")
assert (len(t) == len(t_corr)) and (t == t_corr).all()
# test behaviour if run already exists
for run in os.listdir(rund):
file = "{}/{}/wrfinput_d01".format(rund, run)
if os.path.isfile(file):
os.remove(file)
exist_message = (("s", "Redoing initialization..."), ("s", "Skipping..."),
("o", "Overwriting..."), ("b", "Creating backup..."))
for init in [True, False]:
for i, (exist, message) in enumerate(exist_message):
if init or i > 0:
print("\n\n")
print(exist, message)
combs, output = capture_submit(init=init, exist=exist, wait=True,
config_file="test.config_test")
print("\n".join(output))
count = Counter(output)
assert count[message] == combs["n_rep"].sum()
if "Skipping..." not in message:
assert count[success[init]] == combs["n_rep"].sum()
# backup created?
bak = ['fastout_d01_2018-06-20_07:00:00_bak_0',
'wrfout_d01_2018-06-20_07:00:00_bak_0']
for run in os.listdir(outd):
outfiles = sorted(os.listdir(os.path.join(outd, run, "bak")))
assert outfiles == bak
with pytest.raises(ValueError, match="Value 'a' for -e option not defined!"):
combs = launch_jobs(init=True, exist="a", config_file="test.config_test")
_, output = capture_submit(init=False, exist="r", wait=True,
config_file="test.config_test_rst")
count = Counter(output)
print("\n".join(output))
for m in ["Restart run from 2018-06-20 07:04:00",
'd01 2018-06-20_07:08:00 wrf: SUCCESS COMPLETE WRF']:
assert count[m] == combs["n_rep"].sum()
outfiles_corr = ['bak',
'fastout_d01_2018-06-20_07:00:00',
'fastout_d01_2018-06-20_07:05:00',
'wrfout_d01_2018-06-20_07:00:00',
'wrfout_d01_2018-06-20_07:06:00']
# check output
for run in os.listdir(outd):
outfiles = sorted(os.listdir(os.path.join(outd, run)))
assert outfiles == outfiles_corr
# concat output and check
tools.concat_output("test.config_test")
for run in os.listdir(outd):
outfiles = sorted(os.listdir(os.path.join(outd, run)))
outfiles_corr = ['fastout_d01_2018-06-20_07:00:00', 'wrfout_d01_2018-06-20_07:00:00']
assert outfiles_corr == outfiles[1:]
for f, freq in zip(outfiles_corr, ["1", "2"]):
ds = xr.open_dataset(os.path.join(outd, run, f), decode_times=False, engine="scipy")
t = tools.extract_times(ds)
t_corr = pd.date_range(start="2018-06-20T07:00:00", end='2018-06-20T07:08:00',
freq=freq + "min")
assert (len(t) == len(t_corr)) and (t == t_corr).all()
def test_repeats():
"""Test config repetitions functionality."""
combs = launch_jobs(init=True, exist="o", config_file="test.config_test_reps")
_, output = capture_submit(init=False, wait=True, exist="o",
config_file="test.config_test_reps")
print("\n".join(output))
count = Counter(output)
assert count[success[False]] == combs["n_rep"].sum()
def test_mpi_and_batch():
"""Test MPI runs and check commands generated for job schedulers (without running them)"""
combs = launch_jobs(init=True, wait=True, exist="o", config_file="test.config_test_mpi")
_, output = capture_submit(init=False, pool_jobs=True, wait=True, exist="o",
config_file="test.config_test_mpi")
print("\n".join(output))
count = Counter(output)
m = "Submit IDs: ['pytest_mp_physics=eta_0', 'pytest_mp_physics=lin_0']"
assert count[m] == 1
m = success[False]
assert count[m] == combs["n_rep"].sum()
rundirs = []
for rundir in combs["run_dir"]:
rundir += "_0"
rundirs.append(rundir)
runlogs = glob.glob(rundir + "/run*.*") + glob.glob(rundir + "/rsl.error.0000")
for runlog in runlogs:
os.remove(runlog)
shutil.copy("tests/test_data/resources.info", rundir)
shutil.copy("tests/test_data/runs/WRF_pytest_eta_0/run_2018-04-10T06:13:14.log", rundir)
# test SGE
_, output = capture_submit(init=False, check_args=True, verbose=True, use_job_scheduler=True,
exist="o", config_file="test.config_test_sge")
print("\n".join(output))
count = Counter(output)
c = output[-1]
batch_comm = "qsub -cwd -q std.q -o {0}/logs/run_pytest_$JOB_ID.out "\
"-e {0}/logs/run_pytest_$JOB_ID.err -l h_rt=000:01:31 "\
" -pe openmpi-fillup 2 -M test@test.com -m ea -N run_pytest -V "\
"-l h_vmem=85M run_wrf.job".format(rund)
assert batch_comm == c
messages = ['Get runtime from previous runs', 'Get vmem from previous runs',
'Use vmem per slot: 85.6M']
for m in messages:
assert count[m] == combs["n_rep"].sum()
rundirs_0 = combs["run_dir"].values + "_0"
timing = tools.get_runtime_all(rundirs_0, all_times=False)["timing"].values
message_rt = "Runtime per time step: {0:.5f} s".format(timing[0])
assert count[message_rt] == 2
# test SLURM
_, output = capture_submit(init=False, check_args=True, verbose=True, use_job_scheduler=True,
exist="o", config_file="test.config_test_slurm")
print("\n".join(output))
count = Counter(output)
c = output[-1]
batch_comm = "sbatch -p mem_0064 -o {0}/logs/run_pytest_%j.out -e {0}/logs/run_pytest_%j.err "\
"--time=000:01:31 --ntasks-per-node=4 -N 1 "\
"--mail-user=test@test.com --mail-type=END,FAIL -J run_pytest "\
"--export=ALL --qos=normal_0064 run_wrf.job".format(rund)
assert batch_comm == c
assert count['Get runtime from previous runs'] == combs["n_rep"].sum()
assert count[message_rt] == 2
# TODO: also check environment variables
def test_scheduler_full():
"""Test runs using a job scheduler if available"""
# Check if job scheduler is available
if ("job_scheduler" in dir(conf)) and \
os.popen("command -v {}".format(batch_dict[conf.job_scheduler])).read() != "":
combs = launch_jobs(init=True, exist="o", config_file="test.config_test_mpi")
_, output = capture_submit(init=False, use_job_scheduler=True, test_run=True, exist="o",
verbose=True, config_file="test.config_test_mpi")
print("\n".join(output))
job_sched = conf.job_scheduler.lower()
if job_sched == "slurm":
comm = "squeue -n "
elif job_sched == "sge":
comm = "qstat -j "
else:
raise ValueError("Job scheduler {} not known!".format(job_sched))
finished = False
first_loop = True
while not finished:
finished = True
status = os.popen(comm + "run_pytest").read().split("\n")
status = tools.remove_empty_str(status)
if "Following jobs do not exist:" in status:
pass
if len(status) > 1:
finished = False
elif first_loop:
raise RuntimeError("Batch job was not submitted!")
time.sleep(5)
first_loop = False
rundirs = combs["run_dir"].values + "_0"
print(rundirs)
for rundir in rundirs:
runlog = glob.glob(rundir + "/run_*.log")[0]
runlog = tools.read_file(runlog)
m = success[False]
assert m in runlog
def test_vgrid():
"""Test vertical grid creation.
Actual vertical grid spacings should be close to desired ones (within +- 1 m).
"""
combs = launch_jobs(init=True, exist="o", config_file="test.config_test_vgrid")
rpath = combs["run_dir"][0] + "_0"
wrfinput = xr.open_dataset(rpath + "/wrfinput_d01", engine="scipy").isel(Time=0)
z = (wrfinput["PHB"] + wrfinput["PH"]) / 9.81
z = z.mean(["west_east", "south_north"])
dz = z.diff("bottom_top_stag")
c = combs.iloc[0]
grid = vertical_grid.create_levels(ztop=c["ztop"], dz0=c["dz0"], method=c["vgrid_method"],
dzmax=c["dzmax"], nz=c["nz"])
err = dz - grid.dz[:-1].values
assert all(abs(err) < 1)
# %%helper functions
@pytest.fixture(autouse=True)
def run_around_tests():
"""Delete test data before and after every test and transfer test namelist and iofiles before the tests"""
# Code that will run before each test
os.chdir(code_dir)
# remove test data
for d in [outd, rund]:
if os.path.isdir(d):
shutil.rmtree(d)
# copy namelist and io file for tests
for build in [params["parallel_build"], params["serial_build"]]:
target_dir = "{}/{}/test/{}/".format(params["build_path"], build, params["ideal_case_name"])
shutil.copy("{}/test_data/IO_test.txt".format(test_dir), target_dir)
shutil.copy("{}/test_data/input_sounding_cops".format(test_dir), target_dir)
shutil.copy("{}/test_data/namelists/namelist.input".format(test_dir), target_dir)
# check skipping non-initialized runs
_, output = capture_submit(init=False, config_file="test.config_test")
assert Counter(output)["Run not initialized yet! Skipping..."] == 2
# A test function will be run at this point
yield
# Code that will run after each test
for d in [outd, rund]:
if os.path.isdir(d):
shutil.rmtree(d)
os.chdir(Path(__file__).parent)
def capture_submit(*args, **kwargs):
try:
with Capturing() as output:
combs = launch_jobs(*args, **kwargs)
except Exception as e:
print(output)
raise(e)
return combs, output
| 24,468
|
https://github.com/erikkaBaguio/web-communicationaid/blob/master/app/static/js/enroll1.js
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
web-communicationaid
|
erikkaBaguio
|
JavaScript
|
Code
| 134
| 511
|
function goto_enroll(form) {
xhr = new XMLHttpRequest();
var url = "https://cryptic-fjord-60133.herokuapp.com/api/add_class";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.form.classname.value);
}
}
var json =JSON.stringify({"classname":form.classname.value});
console.log(json)
xhr.send(json);
location="enroll_home.html";
alert("Thanks " + form.classname.value + "! Successfully added.");
}
function goto_home() {
location = "enroll_home.html";
}
function goto_class2() {
location="addclass.html";
}
function goto_classpage() {
location="class_page.html";
}
function delete_class(val){
if (confirm("Are you sure you want to DELETE?")) {
var url = "https://cryptic-fjord-60133.herokuapp.com/api/del_class="+val;
var xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "200") {
alert('Successfully deleted');
location = "enroll_home.html"
} else {
alert('error')
}
}
xhr.send(null);
}
}
function goto_enroll1() {
location="enroll.html";
}
function classpage() {
location="class_page.html";
}
| 26,571
|
https://github.com/red-gate/ngit/blob/master/NGit/NGit.Patch/HunkHeader.cs
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
ngit
|
red-gate
|
C#
|
Code
| 1,722
| 4,967
|
/*
This code is derived from jgit (http://eclipse.org/jgit).
Copyright owners are documented in jgit's IP log.
This program and the accompanying materials are made available
under the terms of the Eclipse Distribution License v1.0 which
accompanies this distribution, is reproduced below, and is
available at http://www.eclipse.org/org/documents/edl-v10.php
All rights reserved.
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.
- Neither the name of the Eclipse Foundation, Inc. nor the
names of its contributors may be used to endorse or promote
products derived from this software without specific prior
written permission.
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 OWNER 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.
*/
using System.Text;
using NGit;
using NGit.Diff;
using NGit.Internal;
using NGit.Patch;
using NGit.Util;
using Sharpen;
namespace NGit.Patch
{
/// <summary>Hunk header describing the layout of a single block of lines</summary>
public class HunkHeader
{
/// <summary>Details about an old image of the file.</summary>
/// <remarks>Details about an old image of the file.</remarks>
public abstract class OldImage
{
/// <summary>First line number the hunk starts on in this file.</summary>
/// <remarks>First line number the hunk starts on in this file.</remarks>
internal int startLine;
/// <summary>Total number of lines this hunk covers in this file.</summary>
/// <remarks>Total number of lines this hunk covers in this file.</remarks>
internal int lineCount;
/// <summary>Number of lines deleted by the post-image from this file.</summary>
/// <remarks>Number of lines deleted by the post-image from this file.</remarks>
internal int nDeleted;
/// <summary>Number of lines added by the post-image not in this file.</summary>
/// <remarks>Number of lines added by the post-image not in this file.</remarks>
internal int nAdded;
/// <returns>first line number the hunk starts on in this file.</returns>
public virtual int GetStartLine()
{
return startLine;
}
/// <returns>total number of lines this hunk covers in this file.</returns>
public virtual int GetLineCount()
{
return lineCount;
}
/// <returns>number of lines deleted by the post-image from this file.</returns>
public virtual int GetLinesDeleted()
{
return nDeleted;
}
/// <returns>number of lines added by the post-image not in this file.</returns>
public virtual int GetLinesAdded()
{
return nAdded;
}
/// <returns>object id of the pre-image file.</returns>
public abstract AbbreviatedObjectId GetId();
}
internal readonly FileHeader file;
/// <summary>
/// Offset within
/// <see cref="file">file</see>
/// .buf to the "@@ -" line.
/// </summary>
internal readonly int startOffset;
/// <summary>
/// Position 1 past the end of this hunk within
/// <see cref="file">file</see>
/// 's buf.
/// </summary>
internal int endOffset;
private readonly HunkHeader.OldImage old;
/// <summary>First line number in the post-image file where the hunk starts</summary>
internal int newStartLine;
/// <summary>Total number of post-image lines this hunk covers (context + inserted)</summary>
internal int newLineCount;
/// <summary>Total number of lines of context appearing in this hunk</summary>
internal int nContext;
private EditList editList;
internal HunkHeader(FileHeader fh, int offset) : this(fh, offset, new _OldImage_122
(fh))
{
}
private sealed class _OldImage_122 : HunkHeader.OldImage
{
public _OldImage_122(FileHeader fh)
{
this.fh = fh;
}
public override AbbreviatedObjectId GetId()
{
return fh.GetOldId();
}
private readonly FileHeader fh;
}
internal HunkHeader(FileHeader fh, int offset, HunkHeader.OldImage oi)
{
file = fh;
startOffset = offset;
old = oi;
}
internal HunkHeader(FileHeader fh, EditList editList) : this(fh, fh.buf.Length)
{
this.editList = editList;
endOffset = startOffset;
nContext = 0;
if (editList.IsEmpty())
{
newStartLine = 0;
newLineCount = 0;
}
else
{
newStartLine = editList[0].GetBeginB();
Edit last = editList[editList.Count - 1];
newLineCount = last.GetEndB() - newStartLine;
}
}
/// <returns>header for the file this hunk applies to</returns>
public virtual FileHeader GetFileHeader()
{
return file;
}
/// <returns>the byte array holding this hunk's patch script.</returns>
public virtual byte[] GetBuffer()
{
return file.buf;
}
/// <returns>
/// offset the start of this hunk in
/// <see cref="GetBuffer()">GetBuffer()</see>
/// .
/// </returns>
public virtual int GetStartOffset()
{
return startOffset;
}
/// <returns>
/// offset one past the end of the hunk in
/// <see cref="GetBuffer()">GetBuffer()</see>
/// .
/// </returns>
public virtual int GetEndOffset()
{
return endOffset;
}
/// <returns>information about the old image mentioned in this hunk.</returns>
public virtual HunkHeader.OldImage GetOldImage()
{
return old;
}
/// <returns>first line number in the post-image file where the hunk starts</returns>
public virtual int GetNewStartLine()
{
return newStartLine;
}
/// <returns>Total number of post-image lines this hunk covers</returns>
public virtual int GetNewLineCount()
{
return newLineCount;
}
/// <returns>total number of lines of context appearing in this hunk</returns>
public virtual int GetLinesContext()
{
return nContext;
}
/// <returns>a list describing the content edits performed within the hunk.</returns>
public virtual EditList ToEditList()
{
if (editList == null)
{
editList = new EditList();
byte[] buf = file.buf;
int c = RawParseUtils.NextLF(buf, startOffset);
int oLine = old.startLine;
int nLine = newStartLine;
Edit @in = null;
for (; c < endOffset; c = RawParseUtils.NextLF(buf, c))
{
switch (buf[c])
{
case (byte)(' '):
case (byte)('\n'):
{
@in = null;
oLine++;
nLine++;
continue;
goto case (byte)('-');
}
case (byte)('-'):
{
if (@in == null)
{
@in = new Edit(oLine - 1, nLine - 1);
editList.AddItem(@in);
}
oLine++;
@in.ExtendA();
continue;
goto case (byte)('+');
}
case (byte)('+'):
{
if (@in == null)
{
@in = new Edit(oLine - 1, nLine - 1);
editList.AddItem(@in);
}
nLine++;
@in.ExtendB();
continue;
goto case (byte)('\\');
}
case (byte)('\\'):
{
// Matches "\ No newline at end of file"
continue;
goto default;
}
default:
{
goto SCAN_break;
break;
}
}
SCAN_continue: ;
}
SCAN_break: ;
}
return editList;
}
internal virtual void ParseHeader()
{
// Parse "@@ -236,9 +236,9 @@ protected boolean"
//
byte[] buf = file.buf;
MutableInteger ptr = new MutableInteger();
ptr.value = RawParseUtils.NextLF(buf, startOffset, ' ');
old.startLine = -RawParseUtils.ParseBase10(buf, ptr.value, ptr);
if (buf[ptr.value] == ',')
{
old.lineCount = RawParseUtils.ParseBase10(buf, ptr.value + 1, ptr);
}
else
{
old.lineCount = 1;
}
newStartLine = RawParseUtils.ParseBase10(buf, ptr.value + 1, ptr);
if (buf[ptr.value] == ',')
{
newLineCount = RawParseUtils.ParseBase10(buf, ptr.value + 1, ptr);
}
else
{
newLineCount = 1;
}
}
internal virtual int ParseBody(NGit.Patch.Patch script, int end)
{
byte[] buf = file.buf;
int c = RawParseUtils.NextLF(buf, startOffset);
int last = c;
old.nDeleted = 0;
old.nAdded = 0;
for (; c < end; last = c, c = RawParseUtils.NextLF(buf, c))
{
switch (buf[c])
{
case (byte)(' '):
case (byte)('\n'):
{
nContext++;
continue;
goto case (byte)('-');
}
case (byte)('-'):
{
old.nDeleted++;
continue;
goto case (byte)('+');
}
case (byte)('+'):
{
old.nAdded++;
continue;
goto case (byte)('\\');
}
case (byte)('\\'):
{
// Matches "\ No newline at end of file"
continue;
goto default;
}
default:
{
goto SCAN_break;
break;
}
}
SCAN_continue: ;
}
SCAN_break: ;
if (last < end && nContext + old.nDeleted - 1 == old.lineCount && nContext + old.
nAdded == newLineCount && (RawParseUtils.Match(buf, last, Patch.SIG_FOOTER
) >= 0 || RawParseUtils.Match(buf, last, Patch.SIG_FOOTER_WINDOWS) >= 0))
{
// This is an extremely common occurrence of "corruption".
// Users add footers with their signatures after this mark,
// and git diff adds the git executable version number.
// Let it slide; the hunk otherwise looked sound.
//
old.nDeleted--;
return last;
}
if (nContext + old.nDeleted < old.lineCount)
{
int missingCount = old.lineCount - (nContext + old.nDeleted);
script.Error(buf, startOffset, MessageFormat.Format(JGitText.Get().truncatedHunkOldLinesMissing
, Sharpen.Extensions.ValueOf(missingCount)));
}
else
{
if (nContext + old.nAdded < newLineCount)
{
int missingCount = newLineCount - (nContext + old.nAdded);
script.Error(buf, startOffset, MessageFormat.Format(JGitText.Get().truncatedHunkNewLinesMissing
, Sharpen.Extensions.ValueOf(missingCount)));
}
else
{
if (nContext + old.nDeleted > old.lineCount || nContext + old.nAdded > newLineCount)
{
string oldcnt = old.lineCount + ":" + newLineCount;
string newcnt = (nContext + old.nDeleted) + ":" + (nContext + old.nAdded);
script.Warn(buf, startOffset, MessageFormat.Format(JGitText.Get().hunkHeaderDoesNotMatchBodyLineCountOf
, oldcnt, newcnt));
}
}
}
return c;
}
/// <exception cref="System.IO.IOException"></exception>
internal virtual void ExtractFileLines(OutputStream[] @out)
{
byte[] buf = file.buf;
int ptr = startOffset;
int eol = RawParseUtils.NextLF(buf, ptr);
if (endOffset <= eol)
{
return;
}
// Treat the hunk header as though it were from the ancestor,
// as it may have a function header appearing after it which
// was copied out of the ancestor file.
//
@out[0].Write(buf, ptr, eol - ptr);
for (ptr = eol; ptr < endOffset; ptr = eol)
{
eol = RawParseUtils.NextLF(buf, ptr);
switch (buf[ptr])
{
case (byte)(' '):
case (byte)('\n'):
case (byte)('\\'):
{
@out[0].Write(buf, ptr, eol - ptr);
@out[1].Write(buf, ptr, eol - ptr);
break;
}
case (byte)('-'):
{
@out[0].Write(buf, ptr, eol - ptr);
break;
}
case (byte)('+'):
{
@out[1].Write(buf, ptr, eol - ptr);
break;
}
default:
{
goto SCAN_break;
break;
}
}
SCAN_continue: ;
}
SCAN_break: ;
}
internal virtual void ExtractFileLines(StringBuilder sb, string[] text, int[] offsets
)
{
byte[] buf = file.buf;
int ptr = startOffset;
int eol = RawParseUtils.NextLF(buf, ptr);
if (endOffset <= eol)
{
return;
}
CopyLine(sb, text, offsets, 0);
for (ptr = eol; ptr < endOffset; ptr = eol)
{
eol = RawParseUtils.NextLF(buf, ptr);
switch (buf[ptr])
{
case (byte)(' '):
case (byte)('\n'):
case (byte)('\\'):
{
CopyLine(sb, text, offsets, 0);
SkipLine(text, offsets, 1);
break;
}
case (byte)('-'):
{
CopyLine(sb, text, offsets, 0);
break;
}
case (byte)('+'):
{
CopyLine(sb, text, offsets, 1);
break;
}
default:
{
goto SCAN_break;
break;
}
}
SCAN_continue: ;
}
SCAN_break: ;
}
internal virtual void CopyLine(StringBuilder sb, string[] text, int[] offsets, int
fileIdx)
{
string s = text[fileIdx];
int start = offsets[fileIdx];
int end = s.IndexOf('\n', start);
if (end < 0)
{
end = s.Length;
}
else
{
end++;
}
sb.AppendRange(s, start, end);
offsets[fileIdx] = end;
}
internal virtual void SkipLine(string[] text, int[] offsets, int fileIdx)
{
string s = text[fileIdx];
int end = s.IndexOf('\n', offsets[fileIdx]);
offsets[fileIdx] = end < 0 ? s.Length : end + 1;
}
public override string ToString()
{
StringBuilder buf = new StringBuilder();
buf.Append("HunkHeader[");
buf.Append(GetOldImage().GetStartLine());
buf.Append(',');
buf.Append(GetOldImage().GetLineCount());
buf.Append("->");
buf.Append(GetNewStartLine()).Append(',').Append(GetNewLineCount());
buf.Append(']');
return buf.ToString();
}
}
}
| 26,381
|
https://github.com/Aayush-Ankit/puma-simulator/blob/master/Security/IAuth.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
puma-simulator
|
Aayush-Ankit
|
Python
|
Code
| 69
| 190
|
# Designed by - Guilherme Maurer
# Miguel Xavier
# Plinio Silveira
# Yago Liborio
# Pontifical Catholic University of Rio Grande do Sul
#
# IAuth - Defines the interface used to authenticate models and input
#
#****************************************************************************************
from abc import ABCMeta, abstractmethod
class IAuth:
__metaclass__ = ABCMeta
@abstractmethod
def generateMACModel(self,path): raise NotImplementedError
@abstractmethod
def generateMACInput(self,path): raise NotImplementedError
@abstractmethod
def authenticateModel(self,path): raise NotImplementedError
@abstractmethod
def authenticateInput(self,path): raise NotImplementedError
| 3,327
|
https://github.com/yarhrn/loco/blob/master/core/src/test/scala/loco/repository/InMemoryRepositoryTest.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
loco
|
yarhrn
|
Scala
|
Code
| 134
| 517
|
package loco.repository
import cats.data.NonEmptyList
import cats.effect.IO
import loco.domain._
import cats.implicits._
import loco.IncrementFixture.IncrementEvent
import loco.repository.EventsRepository.ConcurrentModificationException
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class InMemoryRepositoryTest extends AnyFlatSpec with Matchers with TestDomainData {
trait ctx {
val repository = InMemoryRepository.unsafeCreate[IO, ForumPostEvent]
}
"InMemoryRepository" should "store events" in new ctx {
val metaEvent = getMetaEvent(AggregateVersion(1), "Hello world", Users.john)
val result = repository.saveEvents(NonEmptyList.one(metaEvent)).flatMap(_ => repository.fetchEvents(metaEvent.aggregateId).compile.toList)
result.unsafeRunSync().head shouldBe metaEvent
}
it should "throw exception in case of same version is saved" in new ctx {
val metaEvent = getMetaEvent(AggregateVersion(1), "Hello world", Users.john)
val savingEvents = repository.saveEvents(NonEmptyList.one(metaEvent))
assertThrows[ConcurrentModificationException[IncrementEvent]] {
(savingEvents, savingEvents).tupled.unsafeRunSync()
}
repository.fetchEvents(metaEvent.aggregateId).compile.toList.unsafeRunSync().head shouldBe metaEvent
}
it should "not throw exception but return empty list" in new ctx{
repository.fetchEvents(AggregateId.random).compile.toList.unsafeRunSync() shouldBe List()
}
def getMetaEvent(version: AggregateVersion[ForumPostEvent], content: String, author: User): MetaEvent[ForumPostEvent] = {
val postCreated = ForumPostEvents.PostCreated(nextVal(), content, author)
MetaEvent[ForumPostEvent](postCreated.id, postCreated, postCreated.created, version)
}
}
| 44,396
|
https://github.com/appsignal/appsignal-ruby/blob/master/lib/appsignal/integrations/sinatra.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
appsignal-ruby
|
appsignal
|
Ruby
|
Code
| 27
| 141
|
# frozen_string_literal: true
require "appsignal"
require "appsignal/rack/sinatra_instrumentation"
Appsignal.logger.debug("Loading Sinatra (#{Sinatra::VERSION}) integration")
app_settings = ::Sinatra::Application.settings
Appsignal.config = Appsignal::Config.new(
app_settings.root || Dir.pwd,
app_settings.environment
)
Appsignal.start_logger
Appsignal.start
::Sinatra::Base.use(Appsignal::Rack::SinatraBaseInstrumentation) if Appsignal.active?
| 45,574
|
https://github.com/emlid/publicrepo1/blob/master/devlib/native/macos_utils/auth_open.cpp
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,020
|
publicrepo1
|
emlid
|
C++
|
Code
| 441
| 1,538
|
/*
* SPDX-License-Identifier: Apache-2.0
* Copyright (C) 2020 Raspberry Pi (Trading) Limited
*/
/**
* authOpenStorageDevice implementation based on authOpen function from RPI-Imager
* https://github.com/raspberrypi/rpi-imager/blob/qml/mac/macfile.cpp
* Anohin Igor <igor.anohin@emlid.com>, 2021
*/
#include "macos_utils.h"
#include <sys/socket.h>
#include <security/Authorization.h>
namespace {
using authorization_uptr = std::unique_ptr<std::remove_pointer<AuthorizationRef>::type,
std::function<void(AuthorizationRef)>>;
auto createFileAuthorization(const QByteArray & filename) -> authorization_uptr {
QByteArray right = "sys.openfile.readwrite." + filename;
AuthorizationItem item = {right, 0, nullptr, 0};
AuthorizationFlags flags = kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights
| kAuthorizationFlagPreAuthorize;
AuthorizationRights rights = {1, &item};
auto authsDestructor = [](AuthorizationRef authRef) {
if (authRef != nullptr) {
AuthorizationFree(authRef, 0);
}
};
AuthorizationRef authRef = nullptr;
if (AuthorizationCreate(&rights, nullptr, flags, &authRef) != 0) {
return nullptr;
}
return authorization_uptr{authRef, authsDestructor};
}
void handleChildProcess(const char * filename, int * pipe, int * stdinpipe)
{
// Close unused pipes
::close(pipe[0]);
::close(stdinpipe[1]);
// Assign pipes with std in/out
::dup2(pipe[1], STDOUT_FILENO);
::dup2(stdinpipe[0], STDIN_FILENO);
const char * cmd = "/usr/libexec/authopen";
QByteArray mode = QByteArray::number(O_RDWR);
::execl(cmd, cmd, "-stdoutpipe", "-extauth", "-o", mode.data(), filename, nullptr);
// Exit with error code -1 in case of execl error
::exit(-1);
}
auto receiveFdFromChildProcess(const int & fromChildToParentPipe) -> int
{
const size_t bufSize = CMSG_SPACE(sizeof(int));
char buf[bufSize];
struct iovec io_vec[1];
io_vec[0].iov_base = buf;
io_vec[0].iov_len = bufSize;
const size_t cmsgSize = CMSG_SPACE(sizeof(int));
char cmsg[cmsgSize];
struct msghdr msg = {0};
msg.msg_iov = io_vec;
msg.msg_iovlen = 1;
msg.msg_control = cmsg;
msg.msg_controllen = cmsgSize;
ssize_t size;
do {
size = recvmsg(fromChildToParentPipe, &msg, 0);
} while (size == -1 && errno == EINTR);
if (size > 0) {
struct cmsghdr * chdr = CMSG_FIRSTHDR(&msg);
if (chdr && chdr->cmsg_type == SCM_RIGHTS) {
qCDebug(macos_utils::macxlog()) << "SCMRIGHTS";
return *((int *)(CMSG_DATA(chdr)));
} else {
qCDebug(macos_utils::macxlog()) << "NOT SCMRIGHTS";
return -1;
}
}
return -2;
}
auto waitForChildProcessToFinish(const int & processId) -> int
{
pid_t wpid;
int status;
do {
wpid = ::waitpid(processId, &status, 0);
} while (wpid == -1 && errno == EINTR);
if (wpid == -1) {
qCDebug(macos_utils::macxlog()) << "waitpid() failed executing authopen";
return -2;
}
if (WEXITSTATUS(status)) {
qCDebug(macos_utils::macxlog()) << "authopen returned failure code" << WEXITSTATUS(status);
return -3;
}
return 0;
}
}
namespace macos_utils {
auto authOpenStorageDevice(const QByteArray & filename) -> int
{
auto authorizationUPtr = createFileAuthorization(filename);
if (!authorizationUPtr) {
return -1;
}
AuthorizationExternalForm externalForm;
if (AuthorizationMakeExternalForm(authorizationUPtr.get(), &externalForm) != 0) {
return -1;
}
int fd = -1;
int pipe[2];
int stdinpipe[2];
::socketpair(AF_UNIX, SOCK_STREAM, 0, pipe);
::pipe(stdinpipe);
auto pid = ::fork();
if (pid == 0) {
handleChildProcess(filename.data(), pipe, stdinpipe);
} else {
// Close unused pipes
::close(pipe[1]);
::close(stdinpipe[0]);
// Send AuthorizationExternalForm structure, because "extauth" was used in authopen
::write(stdinpipe[1], externalForm.bytes, sizeof(externalForm.bytes));
::close(stdinpipe[1]);
fd = receiveFdFromChildProcess(pipe[0]);
auto exitCode = waitForChildProcessToFinish(pid);
if (exitCode != 0) {
return exitCode;
}
qCDebug(macxlog()) << "fd received:" << fd;
}
return fd;
}
}
| 34,945
|
https://github.com/yoPCix/nodatime.serialization/blob/master/src/NodaTime.Serialization.Benchmarks/JsonNet/NodaConverterBaseBenchmarks.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
nodatime.serialization
|
yoPCix
|
C#
|
Code
| 183
| 695
|
// Copyright 2017 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using BenchmarkDotNet.Attributes;
using Newtonsoft.Json;
using NodaTime.Serialization.JsonNet;
using System.IO;
namespace NodaTime.Serialization.Benchmarks.JsonNet
{
public class NodaConverterBaseBenchmarks
{
private readonly NodaConverterBase<int> int32Converter = new DummyConverter<int>();
private readonly NodaConverterBase<string> stringConverter = new DummyConverter<string>();
private readonly NodaConverterBase<Stream> streamConverter = new DummyConverter<Stream>();
// Value types
[Benchmark]
public bool CanConvert_Int32_Int32() => int32Converter.CanConvert(typeof(int));
[Benchmark]
public bool CanConvert_Int32_NullableInt32() => int32Converter.CanConvert(typeof(int?));
[Benchmark]
public bool CanConvert_Int32_Object() => int32Converter.CanConvert(typeof(object));
[Benchmark]
public bool CanConvert_Int32_String() => int32Converter.CanConvert(typeof(string));
[Benchmark]
public bool CanConvert_Int32_UInt32() => int32Converter.CanConvert(typeof(uint));
// Sealed classes
[Benchmark]
public bool CanConvert_String_String() => stringConverter.CanConvert(typeof(string));
[Benchmark]
public bool CanConvert_String_Object() => stringConverter.CanConvert(typeof(object));
[Benchmark]
public bool CanConvert_String_UInt32() => stringConverter.CanConvert(typeof(uint));
// Unsealed classes
[Benchmark]
public bool CanConvert_Stream_Stream() => streamConverter.CanConvert(typeof(Stream));
[Benchmark]
public bool CanConvert_Stream_MemoryStream() => streamConverter.CanConvert(typeof(MemoryStream));
[Benchmark]
public bool CanConvert_Stream_Object() => streamConverter.CanConvert(typeof(object));
[Benchmark]
public bool CanConvert_Stream_String() => streamConverter.CanConvert(typeof(string));
[Benchmark]
public bool CanConvert_Stream_UInt32() => streamConverter.CanConvert(typeof(uint));
private class DummyConverter<T> : NodaConverterBase<T>
{
protected override T ReadJsonImpl(JsonReader reader, JsonSerializer serializer) => default(T);
protected override void WriteJsonImpl(JsonWriter writer, T value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
}
}
}
| 395
|
https://github.com/benchmark-gl/benchmark.gl/blob/master/index.js
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
benchmark.gl
|
benchmark-gl
|
JavaScript
|
Code
| 67
| 272
|
var data = require("./dist.json");
var platform = require("platform");
exports.calibrate = function(){
var canvas = document.createElement("canvas");
var gl = (
canvas.getContext("webgl") ||
canvas.getContext("webgl-experimental") ||
canvas.getContext("experimental-webgl")
);
if (!gl) {
return 0;
}
var renderer;
var dbgRenderInfo = gl.getExtension("WEBGL_debug_renderer_info");
if (dbgRenderInfo != null) {
renderer = gl.getParameter(dbgRenderInfo.UNMASKED_RENDERER_WEBGL);
}
canvas.remove();
console.log("renderer", renderer);
console.log("data", data);
console.log("platform", platform);
Object.keys(data).forEach(function(val){
for (var i=0, iLen=data[val].length; i<iLen; i++) {
//find your values
}
});
}
| 17,342
|
https://github.com/AII-G2/ToFilms/blob/master/ToFilms/scrapping/scrappingWeb.py
|
Github Open Source
|
Open Source
|
MIT
| null |
ToFilms
|
AII-G2
|
Python
|
Code
| 249
| 1,117
|
# encoding:utf-8
import codecs
import sys
import urllib2
from bs4 import BeautifulSoup
def extrae_datos_pagina():
file = open('datos.txt', 'r')
lines = file.readlines()
for i in lines:
data_bruto = eval(i)
url = data_bruto[1]
try:
html = urllib2.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
pelicula = soup.find('td', {"valign": "top"})
pelicula = pelicula.find_all('td', {"valign": "top"})
datos_pelicula = pelicula[2]
img_src = datos_pelicula.find('img')['src']
actores = ''
genero = ''
director = ''
fecha = ''
formato = ''
tamanyo = ''
descargas = ''
anyo = ''
for i in datos_pelicula.find_all('b'):
if 'Actores' in i.text:
actores = str(i.next_sibling.encode("utf-8")).strip()
if u'G\xe9nero:' in i.text:
genero = str(i.next_sibling.encode("utf-8")).strip()
if 'Director:' in i.text:
director = str(i.next_sibling.encode("utf-8")).strip()
if u'A\xf1o:' in i.text:
anyo = str(i.next_sibling.encode("utf-8")).strip()
if 'Fecha:' in i.text:
fecha = str(i.next_sibling.encode("utf-8")).strip()
if 'Formato:' in i.text:
formato = str(i.next_sibling.encode("utf-8")).strip()
if u'Tama\xf1o:' in i.text:
tamanyo = str(i.next_sibling.encode("utf-8")).strip()
if 'Total Descargas:' in i.text:
descargas = str(i.next_sibling.encode("utf-8")).strip()
descripcion = datos_pelicula.find('div', align='justify')
descripcion = descripcion.text.split('\n')[0]
enlace_torrent = 'http://www.tumeURL.com/' + datos_pelicula.a['href']
titulo = datos_pelicula.find('span', style='font-size:18px;')
titulo = str(titulo.text.encode("utf-8")).strip()
data = [titulo, img_src, actores, genero, director, descripcion, anyo, fecha, formato, tamanyo, descargas,
enlace_torrent]
file_exito = open('file_exito.txt', 'a')
file_exito.write(str(data) + '\n')
file_exito.close()
except:
file_error = open('file_error.txt', 'a')
file_error.write(i)
file_error.close()
def download_final_data():
file = open('datos2.txt', 'r')
lines = file.readlines()
for i in lines:
data_bruto = eval(i)
url = data_bruto[-1]
try:
html = urllib2.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
pelicula = soup.find('td', {"valign": "top"})
pelicula = pelicula.find_all('td', {"valign": "top"})
datos_pelicula = pelicula[2]
url_download = 'http://www.tumeURL.com' + str(datos_pelicula.find('a')['href'])
data_bruto.append(url_download)
file_exito = open('file_exito.txt', 'a')
file_exito.write(str(data_bruto) + '\n')
file_exito.close()
except:
file_error = open('file_error.txt', 'a')
file_error.write(i)
file_error.close()
| 32,769
|
https://github.com/pulumi/pulumi-aws-native/blob/master/sdk/dotnet/Ec2/Outputs/SpotFleetRequestConfigData.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
pulumi-aws-native
|
pulumi
|
C#
|
Code
| 263
| 1,259
|
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AwsNative.Ec2.Outputs
{
[OutputType]
public sealed class SpotFleetRequestConfigData
{
public readonly Pulumi.AwsNative.Ec2.SpotFleetRequestConfigDataAllocationStrategy? AllocationStrategy;
public readonly string? Context;
public readonly Pulumi.AwsNative.Ec2.SpotFleetRequestConfigDataExcessCapacityTerminationPolicy? ExcessCapacityTerminationPolicy;
public readonly string IamFleetRole;
public readonly Pulumi.AwsNative.Ec2.SpotFleetRequestConfigDataInstanceInterruptionBehavior? InstanceInterruptionBehavior;
public readonly int? InstancePoolsToUseCount;
public readonly ImmutableArray<Outputs.SpotFleetLaunchSpecification> LaunchSpecifications;
public readonly ImmutableArray<Outputs.SpotFleetLaunchTemplateConfig> LaunchTemplateConfigs;
public readonly Outputs.SpotFleetLoadBalancersConfig? LoadBalancersConfig;
public readonly string? OnDemandAllocationStrategy;
public readonly string? OnDemandMaxTotalPrice;
public readonly int? OnDemandTargetCapacity;
public readonly bool? ReplaceUnhealthyInstances;
public readonly Outputs.SpotFleetSpotMaintenanceStrategies? SpotMaintenanceStrategies;
public readonly string? SpotMaxTotalPrice;
public readonly string? SpotPrice;
public readonly ImmutableArray<Outputs.SpotFleetTagSpecification> TagSpecifications;
public readonly int TargetCapacity;
public readonly Pulumi.AwsNative.Ec2.SpotFleetRequestConfigDataTargetCapacityUnitType? TargetCapacityUnitType;
public readonly bool? TerminateInstancesWithExpiration;
public readonly Pulumi.AwsNative.Ec2.SpotFleetRequestConfigDataType? Type;
public readonly string? ValidFrom;
public readonly string? ValidUntil;
[OutputConstructor]
private SpotFleetRequestConfigData(
Pulumi.AwsNative.Ec2.SpotFleetRequestConfigDataAllocationStrategy? allocationStrategy,
string? context,
Pulumi.AwsNative.Ec2.SpotFleetRequestConfigDataExcessCapacityTerminationPolicy? excessCapacityTerminationPolicy,
string iamFleetRole,
Pulumi.AwsNative.Ec2.SpotFleetRequestConfigDataInstanceInterruptionBehavior? instanceInterruptionBehavior,
int? instancePoolsToUseCount,
ImmutableArray<Outputs.SpotFleetLaunchSpecification> launchSpecifications,
ImmutableArray<Outputs.SpotFleetLaunchTemplateConfig> launchTemplateConfigs,
Outputs.SpotFleetLoadBalancersConfig? loadBalancersConfig,
string? onDemandAllocationStrategy,
string? onDemandMaxTotalPrice,
int? onDemandTargetCapacity,
bool? replaceUnhealthyInstances,
Outputs.SpotFleetSpotMaintenanceStrategies? spotMaintenanceStrategies,
string? spotMaxTotalPrice,
string? spotPrice,
ImmutableArray<Outputs.SpotFleetTagSpecification> tagSpecifications,
int targetCapacity,
Pulumi.AwsNative.Ec2.SpotFleetRequestConfigDataTargetCapacityUnitType? targetCapacityUnitType,
bool? terminateInstancesWithExpiration,
Pulumi.AwsNative.Ec2.SpotFleetRequestConfigDataType? type,
string? validFrom,
string? validUntil)
{
AllocationStrategy = allocationStrategy;
Context = context;
ExcessCapacityTerminationPolicy = excessCapacityTerminationPolicy;
IamFleetRole = iamFleetRole;
InstanceInterruptionBehavior = instanceInterruptionBehavior;
InstancePoolsToUseCount = instancePoolsToUseCount;
LaunchSpecifications = launchSpecifications;
LaunchTemplateConfigs = launchTemplateConfigs;
LoadBalancersConfig = loadBalancersConfig;
OnDemandAllocationStrategy = onDemandAllocationStrategy;
OnDemandMaxTotalPrice = onDemandMaxTotalPrice;
OnDemandTargetCapacity = onDemandTargetCapacity;
ReplaceUnhealthyInstances = replaceUnhealthyInstances;
SpotMaintenanceStrategies = spotMaintenanceStrategies;
SpotMaxTotalPrice = spotMaxTotalPrice;
SpotPrice = spotPrice;
TagSpecifications = tagSpecifications;
TargetCapacity = targetCapacity;
TargetCapacityUnitType = targetCapacityUnitType;
TerminateInstancesWithExpiration = terminateInstancesWithExpiration;
Type = type;
ValidFrom = validFrom;
ValidUntil = validUntil;
}
}
}
| 7,444
|
https://github.com/pesout/xcorejs-ui/blob/master/src/components/Typography/index.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
xcorejs-ui
|
pesout
|
TypeScript
|
Code
| 134
| 355
|
import { composedTextBase, TextBaseProps } from 'bases';
import React, { forwardRef, ReactNode } from 'react';
import styled from 'styled-components';
import useTheme from 'useTheme';
import useMerge from 'utils/useMerge';
import { typeVariant } from 'utils/variant';
import { shouldForwardProp } from 'utils/withConfig';
import { TypographyAs, TypographyVariant } from './theme';
export type TypographyProps = TextBaseProps;
export type ExtendedTypographyProps =
{
variant?: TypographyVariant;
v?: TypographyVariant;
as?: TypographyAs;
}
& TypographyProps;
const Typography = forwardRef<HTMLDivElement, ExtendedTypographyProps>(({ as: _as, ...p }, ref) => {
const { typography } = useTheme();
const type = p.variant ?? p.v ?? 'p';
const as: TypographyAs = _as ?? (type === 'lead' ? 'p' : type);
const props = useMerge(
p,
typeVariant(typography, 'p', p),
typography.default
);
return (
<TypographyStyle {...props} as={as} ref={ref} />
);
});
export default Typography;
const TypographyStyle = styled.p.withConfig<TypographyProps>({ shouldForwardProp })`
${composedTextBase}
`;
| 10,411
|
https://github.com/kollaprasannakrishna/tangerinecloud/blob/master/resources/views/pages/about.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
tangerinecloud
|
kollaprasannakrishna
|
PHP
|
Code
| 8
| 96
|
@extends('main')
@section('content')
@include('main.about.abt-description')
{{--@include('main.about.abt-counter')--}}
{{--@include('main.about.abt-historyArea')--}}
@include('main.about.abt-teamArea')
{{--@include('main.testimonials')--}}
@endsection
| 39,366
|
https://github.com/leocavalcante/hyperf/blob/master/src/resource-grpc/tests/Stubs/Grpc/GPBMetadata/Grpc/Grpc.php
|
Github Open Source
|
Open Source
|
Apache-2.0, MIT
| 2,022
|
hyperf
|
leocavalcante
|
PHP
|
Code
| 85
| 676
|
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
# source: Grpc/grpc.proto
namespace HyperfTest\ResourceGrpc\Stubs\Grpc\GPBMetadata\Grpc;
class Grpc
{
public static $is_initialized = false;
public static function initOnce()
{
$pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
if (static::$is_initialized == true) {
return;
}
$pool->internalAddGeneratedFile(hex2bin(
'0afd020a0f477270632f677270632e70726f746f12224879706572665465' .
'73742e5265736f75726365477270632e53747562732e4772706322230a06' .
'486955736572120c0a046e616d65180120012809120b0a03736578180220' .
'01280522540a0748695265706c79120f0a076d6573736167651801200128' .
'0912380a047573657218022001280b322a2e487970657266546573742e52' .
'65736f75726365477270632e53747562732e477270632e48695573657222' .
'560a08416c6c5265706c79120f0a076d6573736167651801200128091239' .
'0a05757365727318022003280b322a2e487970657266546573742e526573' .
'6f75726365477270632e53747562732e477270632e486955736572326b0a' .
'02686912650a0873617948656c6c6f122a2e487970657266546573742e52' .
'65736f75726365477270632e53747562732e477270632e4869557365721a' .
'2b2e487970657266546573742e5265736f75726365477270632e53747562' .
'732e477270632e48695265706c792200620670726f746f33'
), true);
static::$is_initialized = true;
}
}
| 255
|
https://github.com/FalyaCharisma/proyek-pasar-sayur/blob/master/app/Models/PesananDetail.php
|
Github Open Source
|
Open Source
|
MIT
| null |
proyek-pasar-sayur
|
FalyaCharisma
|
PHP
|
Code
| 25
| 118
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class PesananDetail extends Model
{
public function sayur(){
return $this->belongsTo('App\Sayur','sayur_id','id');
}
public function pesanan(){
return $this->belongsTo('App\Pesanan','pesanan_id','id');
}
}
| 38,564
|
https://github.com/telegraph/acs-aem-commons/blob/master/bundle/src/main/java/com/adobe/acs/commons/version/EvolutionEntry.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
acs-aem-commons
|
telegraph
|
Java
|
Code
| 45
| 150
|
package com.adobe.acs.commons.version;
public interface EvolutionEntry {
int getDepth();
String getName();
String getStatus();
EvolutionEntryType getType();
String getUniqueName();
String getValueString();
String getValueStringShort();
boolean isAdded();
boolean isChanged();
boolean isCurrent();
boolean isResource();
boolean isWillBeRemoved();
/**
* The available entry types.
*/
public enum EvolutionEntryType {
RESOURCE, PROPERTY
}
}
| 5,670
|
https://github.com/Fatizel/EightQueensPuzzle/blob/master/python/equeenInput.py
|
Github Open Source
|
Open Source
|
MIT
| null |
EightQueensPuzzle
|
Fatizel
|
Python
|
Code
| 311
| 811
|
import datetime
#import library for conection db
from sqlalchemy import create_engine
# Funtion for define if exist a queen in the dashboard
def verification(row, col, queens):
if not len(queens): return False
for queen in queens:
if not len(queen):
continue
r,c = queen
if r == row: return True # Check row
if c == col: return True # Check column
if (col-c) == (row-r): return True # Check left diagonal
if (col-c) == -(row-r): return True # Check right diagonal
return False
#Funtion for iterate in the rows solution.
def research(n):
numSolution = 0;
solutions = None
for row in range(1, n+1):
# for each row, check all valid column
solutions, numSolution = inspection(solutions, row, n, numSolution)
return solutions, numSolution
# Funtion that evaluate the solution for iteration
def inspection(solutions, row, n, numSolution):
#Matrix for solutions
nSolution = []
#Num of solution for iteration
numSolution = 0
for col in range(1, n+1):
if not solutions or not len(solutions):
nSolution.append([] + [(row, col)])
else:
for solution in solutions:
if not verification(row, col, solution):
numSolution = numSolution + 1
nSolution.append(solution + [(row, col)])
return nSolution, numSolution
#Funtion for database conect
def dbconect(userN, pw, host, port,tName):
dbString = "postgresql://"+userN+":"+pw+"@"+host+":"+port;
db = create_engine(dbString)
db.execute("DROP TABLE IF EXISTS " + tName )
db.execute("DROP SCHEMA IF EXISTS "+ tName)
db.execute("CREATE TABLE IF NOT EXISTS "+ tName +"(queen text,iter text,dx text,dy text)")
return db
#Funtion for add data in table
def dbinsert(db,tName, queen, itera, dx, dy):
db.execute("INSERT INTO "+ tName +" (queen, iter, dx, dy) VALUES ("+queen+", "+itera+", "+dx+","+dy+")")
#reader = db.execute("SELECT * FROM "+ tName)
#for r in reader:
# print(r)
tName = "queenR"
queen = int(8)
current_time = datetime.datetime.now()
print(current_time)
db = dbconect("postgres","mysecretpassword","localhost","5432", tName)
solution, numSolution = research(queen)
a = solution
iTb = 0
for row in a:
iTb = iTb +1
for elem in row:
dbinsert(db,tName,str(queen),str(iTb),str(elem[0]),str(elem[1]))
current_time = datetime.datetime.now()
print(current_time)
print("Soluciones almacenadas: " + str(numSolution))
| 4,328
|
https://github.com/EBIvariation/metadata-ws/blob/master/metadata-load/src/main/java/uk/ac/ebi/ampt2d/metadata/importer/api/ReferenceSequenceXmlRetrieverThroughEntrezApi.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
metadata-ws
|
EBIvariation
|
Java
|
Code
| 441
| 1,264
|
/*
*
* Copyright 2019 EMBL - European Bioinformatics Institute
*
* 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 uk.ac.ebi.ampt2d.metadata.importer.api;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.web.client.RestTemplate;
public class ReferenceSequenceXmlRetrieverThroughEntrezApi {
private static final String ID_START_TAG = "<Id>";
private static final String ID_END_TAG = "</Id>";
private static final String ASSEMBLY_ID_START_TAG = "<DocumentSummary uid=\"";
private static final String ASSEMBLY_ID_END_TAG = "\">\n\t<RsUid>";
private static final String ENTREZ_API_KEY_QUERY = "&api_key={entrezApiKey}";
/*
* URL to obtain an internal Entrez ID from, given an NCBI database and a sequence accession
*/
private String entrezApiIdRetrievalUrl =
"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db={entrezDatabase}&term={accession}";
/*
* URL to obtain assembly metadata from, given its internal Entrez ID.
*/
private String entrezApiAssemblyRetrievalUrl =
"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db={entrezDatabase}&id={id}";
private RestTemplate restTemplate = new RestTemplate();
private String entrezApiKey;
public ReferenceSequenceXmlRetrieverThroughEntrezApi(String entrezApiKey) {
if (entrezApiKey != null && !entrezApiKey.isEmpty()) {
this.entrezApiKey = entrezApiKey;
entrezApiIdRetrievalUrl = entrezApiIdRetrievalUrl + ENTREZ_API_KEY_QUERY;
entrezApiAssemblyRetrievalUrl = entrezApiAssemblyRetrievalUrl + ENTREZ_API_KEY_QUERY;
}
}
private String fetchEntrezId(String accession, String entrezDatabase) {
return restTemplate.getForEntity(entrezApiIdRetrievalUrl, String.class, entrezDatabase, accession,
entrezApiKey).getBody();
}
private String fetchEntrezData(String id, String entrezDatabase) {
return restTemplate.getForEntity(entrezApiAssemblyRetrievalUrl, String.class, entrezDatabase, id,
entrezApiKey).getBody();
}
@Retryable(maxAttemptsExpression="#{${entrez.api.attempts}}",
backoff=@Backoff(delayExpression="#{${entrez.api.delay}}"))
public String getXml(String accession, String entrezDatabase) {
// First we query the appropriate Entrez database with an accession to find out the corresponding internal ID.
// For example, if we have AJPT01332946.1 and query the nuccore database, it'll return an ID of 428325741.
String idXml = fetchEntrezId(accession, entrezDatabase);
String id = idXml.substring(idXml.indexOf(ID_START_TAG) + ID_START_TAG.length(), idXml.indexOf(ID_END_TAG));
// Now, having an internal ID, we query the corresponding Entrez database to get the necessary data.
String dataXml = fetchEntrezData(id, entrezDatabase);
boolean isAssembly = entrezDatabase.equals("assembly");
String DATA_ID_START_TAG = isAssembly ? ASSEMBLY_ID_START_TAG : ID_START_TAG;
String DATA_ID_END_TAG = isAssembly ? ASSEMBLY_ID_END_TAG : ID_END_TAG;
String idFromData = dataXml.substring(dataXml.indexOf(DATA_ID_START_TAG) + DATA_ID_START_TAG.length(),
dataXml.indexOf(DATA_ID_END_TAG));
if (idFromData.isEmpty()) {
// This check is here to ensure that the result which Entrez returns is actually meaningful. Sometimes,
// rarely and sporadically, Entrez does return either an empty XML, or an XML complaining about
// backend error, without any actual information. The exception below is thrown so that the @Retryable
// annotation can kick in and resolve the issue.
throw new AssertionError("Entrez error: received a malformed XML for accession " + accession);
}
return dataXml;
}
}
| 3,523
|
https://github.com/cheng219/tianyu/blob/master/Assets/Protocol/pt_guild_item_info_d379.cs
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
tianyu
|
cheng219
|
C#
|
Code
| 162
| 670
|
using System.Collections;
using System.Collections.Generic;
public class pt_guild_item_info_d379 : st.net.NetBase.Pt {
public pt_guild_item_info_d379()
{
Id = 0xD379;
}
public override st.net.NetBase.Pt createNew()
{
return new pt_guild_item_info_d379();
}
public List<int> emptys = new List<int>();
public List<st.net.NetBase.item_des> guld_items = new List<st.net.NetBase.item_des>();
public override void fromBinary(byte[] binary)
{
reader = new st.net.NetBase.ByteReader(binary);
ushort lenemptys = reader.Read_ushort();
emptys = new List<int>();
for(int i_emptys = 0 ; i_emptys < lenemptys ; i_emptys ++)
{
int listData = reader.Read_int();
emptys.Add(listData);
}
ushort lenguld_items = reader.Read_ushort();
guld_items = new List<st.net.NetBase.item_des>();
for(int i_guld_items = 0 ; i_guld_items < lenguld_items ; i_guld_items ++)
{
st.net.NetBase.item_des listData = new st.net.NetBase.item_des();
listData.fromBinary(reader);
guld_items.Add(listData);
}
}
public override byte[] toBinary()
{
writer = new st.net.NetBase.ByteWriter();
ushort lenemptys = (ushort)emptys.Count;
writer.write_short(lenemptys);
for(int i_emptys = 0 ; i_emptys < lenemptys ; i_emptys ++)
{
int listData = emptys[i_emptys];
writer.write_int(listData);
}
ushort lenguld_items = (ushort)guld_items.Count;
writer.write_short(lenguld_items);
for(int i_guld_items = 0 ; i_guld_items < lenguld_items ; i_guld_items ++)
{
st.net.NetBase.item_des listData = guld_items[i_guld_items];
listData.toBinary(writer);
}
return writer.data;
}
}
| 17,403
|
https://github.com/liquality/atomicagent/blob/master/src/worker/queues/update-market-data.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
atomicagent
|
liquality
|
JavaScript
|
Code
| 47
| 166
|
require('../../utils/sentry')
const mongo = require('../../utils/mongo')
const debug = require('debug')('liquality:agent:worker:update-market-data')
const Market = require('../../models/Market')
async function process(job) {
debug('Running....', job.id)
await Market.updateAllMarketData()
return {
next: [
{
name: 'UpdateMarketData'
}
]
}
}
module.exports = (job) => {
return mongo
.connect()
.then(() => process(job))
.finally(() => mongo.disconnect())
}
| 41,349
|
https://github.com/dayupu/acme/blob/master/assist/src/main/java/com/magic/acme/assist/jpa/xtt/entity/HandshakeNoCargo.java
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
acme
|
dayupu
|
Java
|
Code
| 206
| 679
|
package com.magic.acme.assist.jpa.xtt.entity;
// Generated 2017-6-22 10:27:00 by Hibernate Tools 5.2.0.CR1
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* HandshakeNoCargo generated by hbm2java
*/
@Entity
@Table(name = "handshake_no_cargo", schema = "public")
public class HandshakeNoCargo implements java.io.Serializable {
private long id;
private String handshakeId;
private String comment;
private Integer orderLineIndex;
private Integer pickedQuantity;
private Handshake handshake;
public HandshakeNoCargo() {
}
@Id
@Column(name = "id", unique = true, nullable = false)
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
@Column(name = "handshake_id", insertable = false, updatable = false)
public String getHandshakeId() {
return this.handshakeId;
}
public void setHandshakeId(String handshakeId) {
this.handshakeId = handshakeId;
}
@Column(name = "comment", nullable = false)
public String getComment() {
return this.comment;
}
public void setComment(String comment) {
this.comment = comment;
}
@Column(name = "order_line_index")
public Integer getOrderLineIndex() {
return this.orderLineIndex;
}
public void setOrderLineIndex(Integer orderLineIndex) {
this.orderLineIndex = orderLineIndex;
}
@Column(name = "picked_quantity")
public Integer getPickedQuantity() {
return this.pickedQuantity;
}
public void setPickedQuantity(Integer pickedQuantity) {
this.pickedQuantity = pickedQuantity;
}
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "handshake_id", nullable = false)
public Handshake getHandshake() {
return handshake;
}
public void setHandshake(Handshake handshake) {
this.handshake = handshake;
}
}
| 37,838
|
https://github.com/bgvmysore/miniproject_stepin/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
miniproject_stepin
|
bgvmysore
|
Ignore List
|
Code
| 9
| 86
|
.vscode/
3_Implementation/*.exe
3_Implementation/*.out
3_Implementation/gnuplot_tmpdatafile_*
3_Implementation/*.csv
6_ImagesAndVideos/*.drawio
3_Implementation/test/*.exe
3_Implementation/test/*.out
3_Implementation/*.gcov
| 36,039
|
https://github.com/m4tx/chombot/blob/master/src/kcc3/data_types.rs
|
Github Open Source
|
Open Source
|
MIT
| null |
chombot
|
m4tx
|
Rust
|
Code
| 293
| 1,083
|
use std::fmt::{Debug, Display, Formatter};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
#[derive(Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize, Debug)]
pub struct PlayerId(pub String);
#[derive(Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize, Debug)]
pub struct DiscordId(pub String);
impl Display for DiscordId {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Player {
pub id: PlayerId,
#[serde(default)]
pub first_name: String,
#[serde(default)]
pub last_name: String,
#[serde(default)]
pub nickname: String,
pub discord_id: DiscordId,
}
impl Player {
pub fn new_from_discord(id: PlayerId, nickname: String, discord_id: DiscordId) -> Self {
Self {
id,
first_name: Default::default(),
last_name: Default::default(),
nickname,
discord_id,
}
}
pub fn short_name(&self) -> String {
if !self.nickname.is_empty() {
self.nickname.clone()
} else {
format!("{} {}", self.first_name, self.last_name)
}
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Chombo {
pub timestamp: DateTime<Utc>,
pub player: PlayerId,
#[serde(default)]
pub comment: String,
}
impl Chombo {
pub fn new(timestamp: DateTime<Utc>, player: &PlayerId, comment: &str) -> Self {
Self {
timestamp,
player: player.to_owned(),
comment: comment.to_owned(),
}
}
}
#[cfg(test)]
mod tests {
use crate::kcc3::data_types::Player;
#[test]
fn name_should_return_full_name_with_nickname() {
let player = Player {
id: Default::default(),
first_name: "A".to_string(),
last_name: "B".to_string(),
nickname: "C".to_string(),
discord_id: Default::default(),
};
assert_eq!(player.name(), "A B (C)");
}
#[test]
fn name_should_return_full_name() {
let player = Player {
id: Default::default(),
first_name: "A".to_string(),
last_name: "B".to_string(),
nickname: "".to_string(),
discord_id: Default::default(),
};
assert_eq!(player.name(), "A B");
}
#[test]
fn name_should_return_nickname() {
let player = Player {
id: Default::default(),
first_name: "".to_string(),
last_name: "".to_string(),
nickname: "C".to_string(),
discord_id: Default::default(),
};
assert_eq!(player.name(), "C");
}
#[test]
fn short_name_should_return_nickname() {
let player = Player {
id: Default::default(),
first_name: "A".to_string(),
last_name: "B".to_string(),
nickname: "C".to_string(),
discord_id: Default::default(),
};
assert_eq!(player.short_name(), "C");
}
#[test]
fn short_name_should_return_full_name() {
let player = Player {
id: Default::default(),
first_name: "A".to_string(),
last_name: "B".to_string(),
nickname: "".to_string(),
discord_id: Default::default(),
};
assert_eq!(player.short_name(), "A B");
}
}
| 24,903
|
https://github.com/vmandal/rif-identity-manager/blob/master/src/app/Authenticated/AuthenticatedContainer.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
rif-identity-manager
|
vmandal
|
TypeScript
|
Code
| 224
| 660
|
import { connect } from 'react-redux'
import { ThunkDispatch } from 'redux-thunk'
import { AnyAction } from 'redux'
import DataVaultWebClient from '@rsksmart/ipfs-cpinner-client'
import { stateInterface } from '../state/configureStore'
import AuthenticatedComponent from './AuthenticatedComponent'
import { decryptMultipleKeys, modifyMultipleItems } from '../state/operations/datavault'
import { DataVaultKey } from '../state/reducers/datavault'
import { logout, resetReducers } from '../state/operations/identity'
import { ENCRYPTED } from '../DataVault/types'
/**
* Get items that are specifically to the Persona from the DataVault collection
* @param data Data from the datavault
*/
export const getPersonaDeclarativeDetails = (data: DataVaultKey) => {
const personaItems = ['DD_NAME', 'DD_EMAIL', 'DD_ADDRESS', 'DD_IDNUMBER', 'DD_PHONE', 'DD_BIRTHDATE']
const returnValueOrEmpty = (key: string) => {
// key is set and data is decrypted
if (data[key] && data[key][0]) {
return data[key]
}
// key is loaded, but no content
if (data[key] && !data[key][0]) {
return [{ id: '', content: ENCRYPTED }]
}
// no key
return [{ id: '', content: '' }]
}
const values: DataVaultKey = {}
personaItems.forEach((key: string) => {
values[key] = returnValueOrEmpty(key)
})
return values
}
const mapStateToProps = (state: stateInterface) => ({
address: state.identity.address,
chainId: state.identity.chainId,
persona: getPersonaDeclarativeDetails(state.datavault.declarativeDetails)
})
const mapDispatchToProps = (dispatch: ThunkDispatch<stateInterface, {}, AnyAction>) => ({
modifyMultipleItems: (client: DataVaultWebClient, items: DataVaultKey) =>
dispatch(modifyMultipleItems(client, items)),
decryptPersona: (client: DataVaultWebClient | null, keys: string[]) => client && dispatch(decryptMultipleKeys(client, keys)),
logoutOrSwitchAccounts: (isLoggingOut: boolean) => isLoggingOut ? dispatch(logout()) : dispatch(resetReducers())
})
export default connect(mapStateToProps, mapDispatchToProps)(AuthenticatedComponent)
| 275
|
https://github.com/weenong/Taroco/blob/master/taroco-run-zipkin.sh
|
Github Open Source
|
Open Source
|
Apache-2.0, MIT
| 2,019
|
Taroco
|
weenong
|
Shell
|
Code
| 59
| 176
|
#!/bin/bash
echo -- -- begin init taroco eureka... -- --
COMPOSE_FILE=./taroco-docs/docker/docker-compose-zipkin.yml
echo -- -- stop and remove old docker-compose containers -- --
if docker-compose -f ${COMPOSE_FILE} ps
then
docker-compose -f ${COMPOSE_FILE} stop
docker-compose -f ${COMPOSE_FILE} rm --force
fi
echo -- -- run docker-compose up -- --
docker-compose -f ${COMPOSE_FILE} up -d
docker images|grep none|awk '{print $3 }'|xargs docker rmi
| 40,031
|
https://github.com/tanjinajui/educenter_php_laravel_project/blob/master/public/backend/admin/dev/assets/stylesheets/components/_ui-profile.sass
|
Github Open Source
|
Open Source
|
MIT
| null |
educenter_php_laravel_project
|
tanjinajui
|
Sass
|
Code
| 74
| 246
|
.profile-cover
position: relative
overflow: hidden
height: 160px
@include media-breakpoint-up(md)
height: 260px
.profile-cover-img
width: 100%
max-width: 100%
height: auto
position: absolute
top: 0
left: 0
z-index: 1
.page-header
position: absolute
bottom: 0
left: 0
z-index: 2
background-color: rgba(#000, .8)
background: -webkit-linear-gradient(to top, rgba(#E8EEF5, 1) 40%, rgba(#fff, 0)); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to top, rgba(#E8EEF5, 1) 40%, rgba(#fff, 0)); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
| 43,226
|
https://github.com/cavity-project/data/blob/master/src/Class Libraries/Data.Facts/Data/TestConcatenationTransformer.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
data
|
cavity-project
|
C#
|
Code
| 53
| 149
|
namespace Cavity.Data
{
using System.Collections.Generic;
using Cavity.Collections;
public sealed class TestConcatenationTransformer : ITransformData
{
public IEnumerable<KeyStringDictionary> Transform(IEnumerable<KeyStringDictionary> data)
{
foreach (var entry in data)
{
var value = string.Empty;
foreach (var item in entry)
{
value += item.Value;
}
yield return new KeyStringDictionary
{
{ "CONCAT", value }
};
}
}
}
}
| 33,739
|
https://github.com/wanziw/caffe_DeepID2/blob/master/data/deepid2/get_data.py
|
Github Open Source
|
Open Source
|
Intel, BSD-2-Clause
| null |
caffe_DeepID2
|
wanziw
|
Python
|
Code
| 274
| 801
|
import os
import sys
import random
import numpy as np
from sklearn import cross_validation
trainX = []
trainY = []
testX = []
testY = []
intra = []
extra = []
print sys.argv[1], sys.argv[2]
trainingpath= sys.argv[1] + "CASIA-WebFace/"
testingpath = sys.argv[1] + sys.argv[2] + '/'
#training dataset
folder = [name for name in os.listdir(trainingpath) if os.path.isdir(os.path.join(trainingpath, name))]
for ff in folder:
path = trainingpath + ff + '/croped/'
im = [name for name in os.listdir(path)]
for ii in im:
trainX.append(path + ii)
trainY.append(str(int(ff)))
#testing dataset
folder = [name for name in os.listdir(testingpath)]
for ff in folder:
path = testingpath + ff + '/croped/'
im = [name for name in os.listdir(path)]
for ii in im:
testX.append(path + ii)
testY.append(ff)
#generate testing pairs
testamount = 10
while True:
if len(intra) == testamount and len(extra) == testamount:
break
a = random.randint(0, len(testX) - 1)
b = random.randint(0, len(testX) - 1)
if testY[a] == testY[b]:
if len(intra) == testamount: continue
intra.append([a, b])
else:
if len(extra) == testamount: continue
extra.append([a, b])
#corss validation
X_train, _, Y_train, _ = cross_validation.train_test_split(trainX, trainY, test_size = 0.2)
X_test = testX
Y_test = testY
#write all information into files
f = open('./data/deepid2/train.out', 'w')
for i in range(len(X_train)):
f.write('../../' + X_train[i] + ' ' + Y_train[i] + '\n')
f = open('./data/deepid2/val.out' , 'w')
for i in range(len(X_test)):
f.write('../../' + X_test[i] + ' ' + Y_test[i] + '\n')
f = open('./data/deepid2/intra.out', 'w')
for i in range(len(intra)):
f.write(str(intra[i][0]) + ' ' + str(intra[i][1]) + '\n')
f = open('./data/deepid2/extra.out', 'w')
for i in range(len(extra)):
f.write(str(extra[i][0]) + ' ' + str(extra[i][1]) + '\n')
f = open('./data/deepid2/name' + sys.argv[2] + '.out', 'w')
for i in range(len(testY)):
f.write(str(testY[i]) + '\n')
| 46,886
|
https://github.com/tyhand/ember-symfony-test/blob/master/src/AppBundle/Serializer/EmberSerializer.php
|
Github Open Source
|
Open Source
|
MIT
| null |
ember-symfony-test
|
tyhand
|
PHP
|
Code
| 103
| 284
|
<?php
namespace AppBundle\Serializer;
use League\Fractal\Serializer\DataArraySerializer;
class EmberSerializer extends DataArraySerializer
{
/**
* Data key name
*
* @var string
*/
protected $dataKeyName;
/**
* Constructor
*
* @param string $dataKeyName Data key name
*/
public function __construct($dataKeyName)
{
$this->dataKeyName = $dataKeyName;
}
/**
* Serialize a collection.
*
* @param string $resourceKey
* @param array $data
*
* @return array
*/
public function collection($resourceKey, array $data)
{
return [$this->dataKeyName => $data];
}
/**
* Serialize an item.
*
* @param string $resourceKey
* @param array $data
*
* @return array
*/
public function item($resourceKey, array $data)
{
return [$this->dataKeyName => $data];
}
}
| 18,497
|
https://github.com/nbros/OcaIDE/blob/master/Ocaml/src/ocaml/editor/actions/OpenIntfImplAction.java
|
Github Open Source
|
Open Source
|
CECILL-B
| 2,021
|
OcaIDE
|
nbros
|
Java
|
Code
| 182
| 701
|
package ocaml.editor.actions;
import java.io.File;
import ocaml.OcamlPlugin;
import ocaml.editors.OcamlEditor;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.ide.IDE;
/** This action opens an editor for the corresponding interface/implementation. */
public class OpenIntfImplAction implements IWorkbenchWindowActionDelegate {
private IWorkbenchWindow window;
public void run(IAction action) {
IWorkbenchPage page = window.getActivePage();
if (page != null) {
IEditorPart editorPart = page.getActiveEditor();
if (editorPart != null) {
if (editorPart instanceof OcamlEditor) {
OcamlEditor editor = (OcamlEditor) editorPart;
IPath file = editor.getPathOfFileBeingEdited();
if (file != null) {
String filepath = file.toOSString();
if (filepath.endsWith(".ml"))
filepath = filepath.substring(0, filepath.length() - 3) + ".mli";
else if (filepath.endsWith(".mli"))
filepath = filepath.substring(0, filepath.length() - 4) + ".ml";
else
return;
try {
IFileStore fileStore = EFS.getStore(new File(filepath).toURI());
IDE.openEditorOnFileStore(page, fileStore);
} catch (Exception e) {
OcamlPlugin.logError("OpenIntfImplAction.run()", e);
return;
}
}
} else
OcamlPlugin.logError("OpenIntfImplAction: only works on ml and mli files");
} else
OcamlPlugin.logError("OpenIntfImplAction: editorPart is null");
} else
OcamlPlugin.logError("OpenIntfImplAction: page is null");
}
public void dispose() {
}
public void init(IWorkbenchWindow window) {
this.window = window;
}
public void selectionChanged(IAction action, ISelection selection) {
}
}
| 19,852
|
https://github.com/huunghiapn/giaitriviet/blob/master/app/src/main/java/com/nghianh/giaitriviet/providers/wordpress/ui/WordpressDetailActivity.java
|
Github Open Source
|
Open Source
|
ECL-2.0, Apache-2.0
| 2,019
|
giaitriviet
|
huunghiapn
|
Java
|
Code
| 978
| 4,303
|
package com.nghianh.giaitriviet.providers.wordpress.ui;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.format.DateUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewStub;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.nghianh.giaitriviet.Config;
import com.nghianh.giaitriviet.R;
import com.nghianh.giaitriviet.comments.CommentsActivity;
import com.nghianh.giaitriviet.fav.FavDbAdapter;
import com.nghianh.giaitriviet.providers.web.WebviewActivity;
import com.nghianh.giaitriviet.providers.wordpress.PostItem;
import com.nghianh.giaitriviet.providers.wordpress.api.JsonApiPostLoader;
import com.nghianh.giaitriviet.providers.wordpress.api.WordpressGetTask;
import com.nghianh.giaitriviet.providers.wordpress.api.WordpressGetTaskInfo;
import com.nghianh.giaitriviet.providers.wordpress.api.providers.JetPackProvider;
import com.nghianh.giaitriviet.util.DetailActivity;
import com.nghianh.giaitriviet.util.ExpandedListView;
import com.nghianh.giaitriviet.util.Helper;
import com.nghianh.giaitriviet.util.MediaActivity;
import com.nghianh.giaitriviet.util.WebHelper;
import com.squareup.picasso.Picasso;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.util.List;
/**
* This activity is used to display a wordpress post
*/
public class WordpressDetailActivity extends DetailActivity implements JsonApiPostLoader.BackgroundPostCompleterListener {
//By default, we remove the first image, however, you can disable this
private static final boolean REMOVE_FIRST_IMG = true;
//Preload all posts for faster loading, increases API requests
public static final boolean PRELOAD_POSTS = true;
//Utilties
private FavDbAdapter mDbHelper;
private WebView htmlTextView;
private TextView mTitle;
//Extra's
public static final String EXTRA_POSTITEM = "postitem";
public static final String EXTRA_API_BASE = "apiurl";
public static final String EXTRA_DISQUS = "disqus";
//Post information
private PostItem post;
private String disqusParseable;
private String apiBase;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Use the general detaillayout and set the viewstub for wordpress
setContentView(R.layout.activity_details);
ViewStub stub = (ViewStub) findViewById(R.id.layout_stub);
stub.setLayoutResource(R.layout.activity_wordpress_details);
View inflated = stub.inflate();
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
thumb = (ImageView) findViewById(R.id.image);
coolblue = (RelativeLayout) findViewById(R.id.coolblue);
//String url = getIntent().getStringExtra(EXTRA_API_BASE)
// + "get_post/?post_id=";
Bundle bundle = this.getIntent().getExtras();
post = (PostItem) getIntent().getSerializableExtra(EXTRA_POSTITEM);
disqusParseable = getIntent().getStringExtra(EXTRA_DISQUS);
apiBase = getIntent().getStringExtra(EXTRA_API_BASE);
//If we have a post and a bundle
if (null != post && null != bundle) {
String dateauthortext = getResources().getString(R.string.wordpress_subtitle_start) +
DateUtils.getRelativeDateTimeString(this, post.getDate().getTime(), DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL)
+ getResources().getString(R.string.wordpress_subtitle_end)
+ post.getAuthor();
// getting a valid url, displaying it and setting a parralax
// listener. Also a fallback for no image.
String imageurl = post.getAttachmentUrl();
if (null == imageurl || imageurl.equals("") || imageurl.equals("null"))
imageurl = post.getThumbnailUrl();
if ((null != imageurl && !imageurl.equals("") && !imageurl.equals("null"))) {
Picasso.with(this).load(imageurl).into(thumb);
final String fImageUrl = imageurl;
thumb.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent commentIntent = new Intent(WordpressDetailActivity.this, MediaActivity.class);
commentIntent.putExtra(MediaActivity.TYPE, MediaActivity.TYPE_IMG);
commentIntent.putExtra(MediaActivity.URL, fImageUrl);
startActivity(commentIntent);
}
});
findViewById(R.id.scroller).setOnTouchListener(new View.OnTouchListener() {
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View v, MotionEvent event) {
return (findViewById(R.id.progressBar).getVisibility() == View.VISIBLE) && android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.JELLY_BEAN;
}
});
}
setUpHeader(imageurl);
Helper.admobLoader(this, getResources(), findViewById(R.id.adView));
mTitle = (TextView) findViewById(R.id.title);
mTitle.setText(post.getTitle());
TextView mDateAuthorView = (TextView) findViewById(R.id.dateauthorview);
mDateAuthorView.setText(dateauthortext);
htmlTextView = (WebView) findViewById(R.id.htmlTextView);
htmlTextView.getSettings().setJavaScriptEnabled(true);
htmlTextView.setBackgroundColor(Color.TRANSPARENT);
htmlTextView.getSettings().setDefaultFontSize(
WebHelper.getWebViewFontSize(this));
//htmlTextView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
htmlTextView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
htmlTextView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null
&& (url.endsWith(".png") || url
.endsWith(".jpg") || url
.endsWith(".jpeg"))) {
Intent commentIntent = new Intent(WordpressDetailActivity.this, MediaActivity.class);
commentIntent.putExtra(MediaActivity.TYPE, MediaActivity.TYPE_IMG);
commentIntent.putExtra(MediaActivity.URL, url);
startActivity(commentIntent);
return true;
} else if (url != null
&& (url.startsWith("http://") || url
.startsWith("https://"))) {
Intent mIntent = new Intent(WordpressDetailActivity.this, WebviewActivity.class);
mIntent.putExtra(WebviewActivity.OPEN_EXTERNAL, Config.OPEN_INLINE_EXTERNAL);
mIntent.putExtra(WebviewActivity.URL, url);
startActivity(mIntent);
return true;
} else {
Uri uri = Uri.parse(url);
Intent ViewIntent = new Intent(Intent.ACTION_VIEW, uri);
// Verify it resolves
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager
.queryIntentActivities(ViewIntent, 0);
boolean isIntentSafe = activities.size() > 0;
// Start an activity if it's safe
if (isIntentSafe) {
startActivity(ViewIntent);
}
return true;
}
}
});
//If the post is completed, load the body. Else, retrieve the full body first
if (post.isCompleted()) {
loadCompletedPost(post);
} else {
new JsonApiPostLoader(post, getIntent().getStringExtra(EXTRA_API_BASE), this).start();
}
Button btnFav = (Button) findViewById(R.id.favorite);
// Listening to button event
btnFav.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
mDbHelper = new FavDbAdapter(WordpressDetailActivity.this);
mDbHelper.open();
if (mDbHelper.checkEvent(post.getTitle(), post, FavDbAdapter.KEY_WORDPRESS)) {
// Item is new
mDbHelper.addFavorite(post.getTitle(), post, FavDbAdapter.KEY_WORDPRESS);
Toast toast = Toast
.makeText(
WordpressDetailActivity.this,
getResources().getString(
R.string.favorite_success),
Toast.LENGTH_LONG);
toast.show();
} else {
Toast toast = Toast.makeText(
WordpressDetailActivity.this,
getResources().getString(
R.string.favorite_duplicate),
Toast.LENGTH_LONG);
toast.show();
}
}
});
//If we have tags and a baseurl, load the related posts
if (post.getTag() != null && getIntent().getStringExtra(EXTRA_API_BASE) != null) {
final ExpandedListView relatedList = (ExpandedListView) findViewById(R.id.related_list);
WordpressGetTaskInfo mInfo = new WordpressGetTaskInfo(null, relatedList, this, null, this.findViewById(R.id.contentholder), getIntent().getStringExtra(EXTRA_API_BASE), true);
mInfo.ignoreId = post.getId();
WordpressGetTask.getTagPosts(mInfo, post.getTag());
relatedList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Object o = relatedList.getItemAtPosition(position);
PostItem newsData = (PostItem) o;
Intent intent = new Intent(WordpressDetailActivity.this, WordpressDetailActivity.class);
intent.putExtra(EXTRA_POSTITEM, newsData);
intent.putExtra(EXTRA_API_BASE, getIntent().getStringExtra(EXTRA_API_BASE));
if (disqusParseable != null)
intent.putExtra(WordpressDetailActivity.EXTRA_DISQUS, disqusParseable);
startActivity(intent);
finish();
}
});
}
}
}
@Override
public void onPause() {
super.onPause();
htmlTextView.onPause();
}
@Override
public void onResume() {
super.onResume();
htmlTextView.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.wordpress_detail_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.menu_share:
shareContent();
return true;
case R.id.menu_view:
Intent mIntent = new Intent(WordpressDetailActivity.this, WebviewActivity.class);
mIntent.putExtra(WebviewActivity.OPEN_EXTERNAL, Config.OPEN_EXPLICIT_EXTERNAL);
mIntent.putExtra(WebviewActivity.URL, post.getUrl());
startActivity(mIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void shareContent() {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, post.getTitle() + "\n" + post.getUrl());
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "Share using"));
}
private void loadCompletedPost(final PostItem result) {
if (null != result) {
setHTML(result.getContent());
//If we have a commentsArray or a disqus url, enable comments
if ((result.getCommentCount() != 0 && result.getCommentsArray() != null) ||
disqusParseable != null ||
(post.getPostType() == PostItem.PostType.JETPACK && result.getCommentCount() != 0)) {
Button btnComment = (Button) findViewById(R.id.comments);
//Set the comments count if we have it available
if (result.getCommentCount() != 0)
btnComment.setText(Helper.formatValue(result.getCommentCount()) + " " + getResources().getString(R.string.comments));
else
btnComment.setText(getResources().getString(R.string.comments));
btnComment.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent commentIntent = new Intent(WordpressDetailActivity.this, CommentsActivity.class);
if (disqusParseable != null) {
commentIntent.putExtra(CommentsActivity.DATA_PARSEABLE, disqusParseable);
commentIntent.putExtra(CommentsActivity.DATA_TYPE, CommentsActivity.DISQUS);
commentIntent.putExtra(CommentsActivity.DATA_ID, post.getId().toString());
} else {
if (post.getPostType() == PostItem.PostType.JETPACK) {
commentIntent.putExtra(CommentsActivity.DATA_PARSEABLE, JetPackProvider.getPostCommentsUrl(apiBase, post.getId().toString()));
commentIntent.putExtra(CommentsActivity.DATA_TYPE, CommentsActivity.WORDPRESS_JETPACK);
} else {
commentIntent.putExtra(CommentsActivity.DATA_PARSEABLE, result.getCommentsArray().toString());
commentIntent.putExtra(CommentsActivity.DATA_TYPE, CommentsActivity.WORDPRESS_JSON);
}
}
startActivity(commentIntent);
}
});
}
} else {
findViewById(R.id.progressBar).setVisibility(View.GONE);
Helper.noConnection(WordpressDetailActivity.this);
}
}
public void setHTML(String source) {
Document doc = Jsoup.parse(source);
//Remove the first image to prevent a repetition of the header image (if enabled and present)
if (REMOVE_FIRST_IMG) {
if (doc.select("img") != null && doc.select("img").first() != null)
doc.select("img").first().remove();
}
String html = WebHelper.docToBetterHTML(doc, this);
htmlTextView.loadDataWithBaseURL(post.getUrl(), html, "text/html", "UTF-8", "");
htmlTextView.setVisibility(View.VISIBLE);
findViewById(R.id.progressBar).setVisibility(View.GONE);
}
@Override
public void completed(final PostItem item) {
runOnUiThread(new Runnable() {
@Override
public void run() {
loadCompletedPost(item);
}
});
}
}
| 50,063
|
https://github.com/SpaceIm/conan-vxl/blob/master/conanfile.py
|
Github Open Source
|
Open Source
|
MIT
| null |
conan-vxl
|
SpaceIm
|
Python
|
Code
| 322
| 1,749
|
from conans import ConanFile, CMake, tools
from conans.errors import ConanInvalidConfiguration
required_conan_version = ">=1.33.0"
class VxlConan(ConanFile):
name = "vxl"
description = "VXL (the Vision-something-Libraries) is a collection of C++ " \
"libraries designed for computer vision research and implementation."
license = "BSD-3-Clause"
topics = ("vxl", "computer-vision", "image", "video", "classification", "topology")
homepage = "https://vxl.github.io"
url = "https://github.com/conan-io/conan-center-index"
settings = "os", "arch", "compiler", "build_type"
options = {
"shared": [True, False],
"fPIC": [True, False],
"core_numerics": [True, False],
"core_geometry": [True, False],
"core_serialisation": [True, False],
"core_utilities": [True, False],
"core_imaging": [True, False],
"core_probability": [True, False],
"core_video": [True, False],
"gui": [True, False],
}
default_options = {
"shared": False,
"fPIC": True,
"core_numerics": True,
"core_geometry": True,
"core_serialisation": True,
"core_utilities": True,
"core_imaging": True,
"core_probability": True,
"core_video": False,
"gui": False,
}
exports_sources = "CMakeLists.txt"
generators = "cmake", "cmake_find_package"
_cmake = None
@property
def _source_subfolder(self):
return "source_subfolder"
def config_options(self):
if self.settings.os == "Windows":
del self.options.fPIC
def configure(self):
if self.options.shared:
del self.options.fPIC
def requirements(self):
if self.options.core_geometry:
self.requires("clipper/6.4.2")
if self.options.core_imaging:
self.requires("bzip2/1.0.8")
self.requires("dcmtk/3.6.6")
self.requires("libgeotiff/1.6.0")
self.requires("libjpeg/9d")
self.requires("libpng/1.6.37")
self.requires("libtiff/4.2.0")
self.requires("openjpeg/2.4.0")
self.requires("zlib/1.2.11")
def validate(self):
if self.settings.compiler.get_safe("cppstd"):
tools.check_min_cppstd(self, 11)
if self.options.core_probability and not self.options.core_numerics:
raise ConanInvalidConfiguration("core_probability requires core_numerics")
if self.options.gui and not (self.options.core_numerics and self.options.core_geometry and \
self.options.core_serialisation and self.options.core_utilities and self.options.core_imaging):
raise ConanInvalidConfiguration("gui requires core_numerics, core_geometry, core_serialisation, core_utilities and core_imaging")
if self.options.core_video and not (self.options.core_utilities and self.options.core_imaging):
raise ConanInvalidConfiguration("core_video requires core_utilities and core_imaging")
def source(self):
tools.get(**self.conan_data["sources"][self.version],
destination=self._source_subfolder, strip_root=True)
def _configure_cmake(self):
if self._cmake:
return self._cmake
self._cmake = CMake(self)
# root CMakeLists.txt
self._cmake.definitions["VXL_LEGACY_FUTURE_REMOVE"] = True
self._cmake.definitions["VXL_USE_HISTORICAL_IMPLICIT_CONVERSIONS"] = True
self._cmake.definitions["VXL_USE_HISTORICAL_PROTECTED_IVARS"] = True
if self.settings.os == "Windows":
self._cmake.definitions["VXL_USE_WIN_WCHAR_T"] = True
else:
self._cmake.definitions["VXL_BUILD_POSITION_DEPENDENT_CODE"] = self.options.get_safe("fPIC", True)
self._cmake.definitions["VXL_USE_LFS"] = False
self._cmake.definitions["VXL_BUILD_CORE_NUMERICS_ONLY"] = False
self._cmake.definitions["VXL_BUILD_CORE_NUMERICS"] = self.options.core_numerics
self._cmake.definitions["VXL_BUILD_CORE_GEOMETRY"] = self.options.core_geometry
self._cmake.definitions["VXL_BUILD_CORE_SERIALISATION"] = self.options.core_serialisation
self._cmake.definitions["VXL_BUILD_CORE_UTILITIES"] = self.options.core_utilities
self._cmake.definitions["VXL_BUILD_CORE_IMAGING"] = self.options.core_imaging
self._cmake.definitions["VXL_BUILD_EXAMPLES"] = False
self._cmake.definitions["VXL_BUILD_NONDEPRECATED_ONLY"] = True
self._cmake.definitions["VXL_BUILD_CORE_PROBABILITY"] = self.options.core_probability
self._cmake.definitions["VXL_USE_GEOTIFF"] = True
self._cmake.definitions["VXL_BUILD_CONTRIB"] = False
self._cmake.definitions["VXL_BUILD_OBJECT_LIBRARIES"] = False
# core/CMakeLists.txt
self._cmake.definitions["VXL_BUILD_VGUI"] = False
self._cmake.definitions["VXL_BUILD_CORE_VIDEO"] = self.options.core_video
self._cmake.configure()
return self._cmake
def build(self):
cmake = self._configure_cmake()
cmake.build()
def package(self):
self.copy("LICENSE", dst="licenses", src=self._source_subfolder)
cmake = self._configure_cmake()
cmake.install()
def package_info(self):
self.cpp_info.libs = tools.collect_libs(self)
| 20,357
|
https://github.com/hoempf/DoH/blob/master/go/dnsrecurser_test.go
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,019
|
DoH
|
hoempf
|
Go
|
Code
| 812
| 1,759
|
/*
* go DoH Daemon - DNS recurser test suite
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Provided to you under the terms of the BSD 3-Clause License
*
* Copyright (c) 2019. Gianpaolo Del Matto, https://github.com/gpdm, <delmatto _ at _ phunsites _ dot _ net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* 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.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*/
package dohservice
import (
"io/ioutil"
"testing"
)
// TestSendDNSRequestWithoutActiveResolvers tests if we get a proper error
// in case no DNS resolvers are available.
func TestSendDNSRequestWithoutActiveResolvers(t *testing.T) {
// clear all active resolvers
ActiveDNSResolvers = nil
// load data file
request, err := ioutil.ReadFile("../testdata/A_www.example.com.bin")
if err != nil {
t.Errorf("Reading data file failed with error: %v", err)
return
}
// send request
response, err := sendDNSRequest(request)
// test succeeds if we get "no resolvers available" error
if err.Error() == "No active DNS resolvers available (all targets are offline)" {
t.Logf("sendDNSRequest() returned *expected* error: %v", err)
return
}
// test fails if we get any other kind of error
if err != nil {
t.Errorf("sendDNSRequest() returned unexpected error: %v", err)
return
}
// test fails if we didn't get an error, but an actual response
t.Errorf("sendDNSRequest() returned no error at all, but an unexpected response: %v", response)
}
// TestSendDNSRequestWithRandomResolverSelection checks random resolver selection
// by iterating over a list of valid backends several times
func TestSendDNSRequestWithRandomResolverSelection(t *testing.T) {
// assign list of valid resolvers
ActiveDNSResolvers = collectionOfValidResolvers
// load data file
request, err := ioutil.ReadFile("../testdata/A_www.example.com.bin")
if err != nil {
t.Errorf("Reading data file failed with error: %v", err)
return
}
// loop 10 times to send request to random resolvers
for i := 1; i <= 10; i++ {
response, err := sendDNSRequest(request)
if err != nil {
t.Errorf("sendDNSRequest() failed with error: %v", err)
return
}
t.Logf("sendDNSRequest() succeeded with response: %v", response)
}
}
// TestSendDNSRequestUDP checks UDP Resolver
func TestSendDNSRequestUDP(t *testing.T) {
// assign list of valid resolvers
ActiveDNSResolvers = []DNSResolver{validUDPResolverGoogle}
// load data file
request, err := ioutil.ReadFile("../testdata/A_www.example.com.bin")
if err != nil {
t.Errorf("Reading data file failed with error: %v", err)
return
}
response, err := sendDNSRequest(request)
if err != nil {
t.Errorf("sendDNSRequest() failed with error: %v", err)
return
}
t.Logf("sendDNSRequest() succeeded with response: %v", response)
}
// TestSendDNSRequestDoHPost checks DoH Resolver through HTTP-POST
func TestSendDNSRequestDoHPost(t *testing.T) {
// assign list of valid resolvers
ActiveDNSResolvers = []DNSResolver{validDoHResolverCloudFlarePost}
// load data file
request, err := ioutil.ReadFile("../testdata/A_www.example.com.bin")
if err != nil {
t.Errorf("Reading data file failed with error: %v", err)
return
}
response, err := sendDNSRequest(request)
if err != nil {
t.Errorf("sendDNSRequest() failed with error: %v", err)
return
}
t.Logf("sendDNSRequest() succeeded with response: %v", response)
}
// TestSendDNSRequestDoHGet checks DoH Resolver through HTTP-GET
func TestSendDNSRequestDoHGet(t *testing.T) {
// assign list of valid resolvers
ActiveDNSResolvers = []DNSResolver{validDoHResolverCloudFlareGet}
// load data file
request, err := ioutil.ReadFile("../testdata/A_www.example.com.bin")
if err != nil {
t.Errorf("Reading data file failed with error: %v", err)
return
}
response, err := sendDNSRequest(request)
if err != nil {
t.Errorf("sendDNSRequest() failed with error: %v", err)
return
}
t.Logf("sendDNSRequest() succeeded with response: %v", response)
}
| 26,457
|
https://github.com/fmap-archive/typeclasses.js/blob/master/lib/typeclasses/functor/object.js
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| null |
typeclasses.js
|
fmap-archive
|
JavaScript
|
Code
| 19
| 60
|
var _ = require('underscore');
module.exports.map = function(obj, fn) {
_.each(obj, function(vs,k) {
obj[k] = fn(vs);
});
return obj;
};
| 14,955
|
https://github.com/gfpeltier/AdventOfCode-Scala/blob/master/src/main/scala/aoc2020/Day10.scala
|
Github Open Source
|
Open Source
|
MIT
| null |
AdventOfCode-Scala
|
gfpeltier
|
Scala
|
Code
| 125
| 435
|
package aoc2020
import scala.collection.mutable.ListBuffer
object Day10 {
def buildChain(adapters: Set[Int]): (List[Int], Int, Int, Int) = {
var chain = ListBuffer.empty[Int]
val diffCnts = Array.fill[Int](4)(0)
var currJ, nextJ = 0
var remAdapters = adapters
while (remAdapters.nonEmpty) {
nextJ = ((currJ - 3) to (currJ + 3)).toSet.intersect(remAdapters).toList.min
val diff = Math.abs(nextJ - currJ)
diffCnts(diff) = diffCnts(diff) + 1
currJ = nextJ
remAdapters -= nextJ
chain += nextJ
}
(chain.toList, diffCnts(1), diffCnts(2), diffCnts(3))
}
def part1(instrs: List[String]): Int = {
val nums = instrs.map(_.toInt).toSet
val (chain, oneJ, twoJ, threeJ) = buildChain(nums)
println(chain)
oneJ * (threeJ + 1)
}
def part2(instrs: List[String]): Long = {
instrs.map(_.toInt).sorted
.foldLeft(Map[Int, Long](0 -> 1))((m, n) => {
m + (n -> (m.getOrElse(n-1, 0L) + m.getOrElse(n-2, 0L) + m.getOrElse(n-3, 0L)))
})
.max._2
}
}
| 5,038
|
https://github.com/Greg-Turner/Trasalum/blob/master/Trasalum/Models/Company.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
Trasalum
|
Greg-Turner
|
C#
|
Code
| 121
| 316
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Trasalum.Models
{
public class Company
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
[Display(Name = "Street Address")]
public string Address { get; set; }
[Required]
[Display(Name = "City")]
public string City { get; set; }
[Required]
[Display(Name = "State")]
public string State { get; set; }
[Required]
[Display(Name = "Zip Code")]
public string ZipCode { get; set; }
[Required]
[Display(Name = "Main Phone #")]
public string Phone { get; set; }
[Required]
[DataType(DataType.Url)]
[Display(Name = "Website URL")]
public string Website { get; set; }
[Required]
[DataType(DataType.Url)]
[Display(Name = "LinkedIn Profile URL")]
public string LinkedIn { get; set; }
}
}
| 941
|
https://github.com/connorjsmith/fast-dna/blob/master/packages/fast-components-react-base/src/toggle/index.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
fast-dna
|
connorjsmith
|
TypeScript
|
Code
| 19
| 39
|
import Toggle from "./toggle";
import toggleSchema from "./toggle.schema";
export { toggleSchema };
export default Toggle;
export * from "./toggle";
| 19,589
|
https://github.com/cwmiller/broadworks-connector/blob/master/src/Ocip/Models/CallCenterReportInterval.php
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
broadworks-connector
|
cwmiller
|
PHP
|
Code
| 269
| 1,087
|
<?php
namespace CWM\BroadWorksConnector\Ocip\Models;
/**
* CallCenterReportInterval
*
* Report interval for call center enhanced reporting scheduled reports.
*
* @Groups [{"id":"e2c537e3e39483b96620673a7012ffdd:7466","type":"choice"}]
*/
class CallCenterReportInterval
{
/**
* @ElementName dates
* @Type \CWM\BroadWorksConnector\Ocip\Models\CallCenterReportIntervalDates
* @Group e2c537e3e39483b96620673a7012ffdd:7466
* @var \CWM\BroadWorksConnector\Ocip\Models\CallCenterReportIntervalDates|null
*/
private $dates = null;
/**
* @ElementName current
* @Type \CWM\BroadWorksConnector\Ocip\Models\CallCenterReportCurrentInterval
* @Group e2c537e3e39483b96620673a7012ffdd:7466
* @var \CWM\BroadWorksConnector\Ocip\Models\CallCenterReportCurrentInterval|null
*/
private $current = null;
/**
* @ElementName past
* @Type \CWM\BroadWorksConnector\Ocip\Models\CallCenterReportPastInterval
* @Group e2c537e3e39483b96620673a7012ffdd:7466
* @var \CWM\BroadWorksConnector\Ocip\Models\CallCenterReportPastInterval|null
*/
private $past = null;
/**
* Getter for dates
*
* @return \CWM\BroadWorksConnector\Ocip\Models\CallCenterReportIntervalDates
*/
public function getDates()
{
return $this->dates instanceof \CWM\BroadWorksConnector\Ocip\Nil ? null : $this->dates;
}
/**
* Setter for dates
*
* @param \CWM\BroadWorksConnector\Ocip\Models\CallCenterReportIntervalDates $dates
* @return $this
*/
public function setDates(\CWM\BroadWorksConnector\Ocip\Models\CallCenterReportIntervalDates $dates)
{
$this->dates = $dates;
return $this;
}
/**
* @return $this
*/
public function unsetDates()
{
$this->dates = null;
return $this;
}
/**
* Getter for current
*
* @return \CWM\BroadWorksConnector\Ocip\Models\CallCenterReportCurrentInterval
*/
public function getCurrent()
{
return $this->current instanceof \CWM\BroadWorksConnector\Ocip\Nil ? null : $this->current;
}
/**
* Setter for current
*
* @param \CWM\BroadWorksConnector\Ocip\Models\CallCenterReportCurrentInterval $current
* @return $this
*/
public function setCurrent(\CWM\BroadWorksConnector\Ocip\Models\CallCenterReportCurrentInterval $current)
{
$this->current = $current;
return $this;
}
/**
* @return $this
*/
public function unsetCurrent()
{
$this->current = null;
return $this;
}
/**
* Getter for past
*
* @return \CWM\BroadWorksConnector\Ocip\Models\CallCenterReportPastInterval
*/
public function getPast()
{
return $this->past instanceof \CWM\BroadWorksConnector\Ocip\Nil ? null : $this->past;
}
/**
* Setter for past
*
* @param \CWM\BroadWorksConnector\Ocip\Models\CallCenterReportPastInterval $past
* @return $this
*/
public function setPast(\CWM\BroadWorksConnector\Ocip\Models\CallCenterReportPastInterval $past)
{
$this->past = $past;
return $this;
}
/**
* @return $this
*/
public function unsetPast()
{
$this->past = null;
return $this;
}
}
| 28,090
|
https://github.com/flyfire-cn/flyfire.CustomSerialPort/blob/master/flyfire.HelloArm/Program.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
flyfire.CustomSerialPort
|
flyfire-cn
|
C#
|
Code
| 719
| 2,799
|
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Reflection;
using System.Text;
using flyfire.IO.Ports;
namespace flyfire.HelloArm
{
public class Program
{
private static CustomSerialPort csp = null;
private static string[] serailports;
private static int curSerialPortOrder = 0;
private static string selectedComPort = "";
private static Dictionary<string, CustomSerialPort> servicePorts = new Dictionary<string, CustomSerialPort>();
private static System.Timers.Timer sendTimer = new System.Timers.Timer();
private static readonly int baudRate = 115200;
static void Main(string[] args)
{
SetLibPath();
ShowWelcome();
GetPortNames();
ShowPortNames();
if (serailports.Length == 0)
{
Console.WriteLine($"Press any key to exit");
Console.ReadKey();
return;
}
#if RunIsService
RunService();
#endif
bool quit = false;
while (!quit)
{
Console.WriteLine("\r\nPlease Input command Key\r\n");
Console.WriteLine("p:Show SerialPort List");
Console.WriteLine($"t:Test Uart:\"{selectedComPort}\"");
Console.WriteLine($"o:Open Uart:\"{selectedComPort}\"");
Console.WriteLine($"c:Close Uart:\"{selectedComPort}\"");
Console.WriteLine("n:select next serial port");
Console.WriteLine("q:exit app");
Console.WriteLine();
var key = Console.ReadKey().KeyChar;
Console.WriteLine();
switch (key)
{
case (Char)27:
case 'q':
case 'Q':
quit = true;
break;
case 's':
ShowWelcome();
break;
case 'p':
ShowPortNames();
break;
case 'n':
SelectSerialPort();
break;
case 't':
TestUart(selectedComPort);
break;
case 'w':
TestWinUart(selectedComPort);
break;
case 'o':
OpenUart(selectedComPort);
break;
case 'c':
CloseUart();
break;
}
}
}
private static void RunService()
{
Console.WriteLine("\r\nRun Mode:Service");
if (serailports.Length > 0)
{
foreach (var name in serailports)
{
if (name.Contains("0"))
continue;
CustomSerialPort csp = new CustomSerialPort(name, baudRate);
csp.ReceivedEvent += Csp_ReceivedEvent;// Csp_DataReceived;
try
{
csp.Open();
servicePorts.Add(name, csp);
Console.WriteLine($"Service Open Uart [{name}] Succful!");
}
catch (Exception ex)
{
Console.WriteLine($"RunService Open Uart [{name}] Exception:{ex}");
}
}
OpenUartTestTimer();
}
}
private static void Csp_ReceivedEvent(object sender, byte[] bytes)
{
try
{
CustomSerialPort sps = (CustomSerialPort)sender;
string msg = Encoding.ASCII.GetString(bytes).Replace("\r", "").Replace("\n", "");
string echo = $"{sps.PortName} Receive Data:[{msg}].Item already filtered crlf.";
Console.WriteLine(echo);
if(!echo.Contains($"{sps.PortName}"))
sps.WriteLine(msg);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// 配置依赖库环境变量
/// 程序中设置对当前程序无效,需重启程序方能生效,仅用于测试
/// </summary>
private static void SetLibPath(string libPathVariable = "LD_LIBRARY_PATH", string lib_path = "lib\\serialportstream", string os = "unix")
{
try
{
if (!Environment.OSVersion.Platform.ToString().Contains(os, StringComparison.OrdinalIgnoreCase))
return;
var path = Environment.GetEnvironmentVariable(libPathVariable);
if (path == null || path == string.Empty)
{
path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, lib_path);
if (Directory.Exists(path))
{
Console.WriteLine($"Set Environment Variable LD_LIBRARY_PATH={path}");
Environment.SetEnvironmentVariable(libPathVariable, path, EnvironmentVariableTarget.User);
}
else
Console.WriteLine("The support library that the program depends on does not exist");
}
path = Environment.GetEnvironmentVariable(libPathVariable);
Console.WriteLine($"LD_LIBRARY_PATH={path}");
}
catch (Exception ex)
{
Console.WriteLine($"Set Environment Variable Exception:{ex}");
}
}
/// <summary>
/// 循环切换选择串口
/// </summary>
private static void SelectSerialPort()
{
if (curSerialPortOrder < serailports.Length)
{
CloseUart();
curSerialPortOrder++;
curSerialPortOrder %= serailports.Length;
selectedComPort = serailports[curSerialPortOrder];
Console.WriteLine($"current selected serial port:{selectedComPort}");
}
}
private static void ShowPortNames()
{
Console.WriteLine($"This computer has {serailports.Length} serial ports.");
foreach (string serial in serailports)
Console.WriteLine($"serial port:{serial}");
}
private static void CloseUart()
{
if (csp != null)
{
if (csp.IsOpen)
csp.Close();
csp.ReceivedEvent -= Csp_ReceivedEvent;//Csp_DataReceived;
csp = null;
Console.WriteLine($"close serial port:{selectedComPort} succful!");
}
#if RunIsService
foreach (var csp in servicePorts.Values)
{
if (csp.IsOpen)
{
csp.Close();
}
}
#endif
if (sendTimer != null && sendTimer.Enabled)
{
sendTimer.Stop();
sendTimer.Elapsed -= SendTimer_Elapsed;
}
msgIndex = 0;
}
private static void OpenUart(string portName)
{
CloseUart();
try
{
csp = new CustomSerialPort(portName);
csp.BaudRate = baudRate;
csp.ReceivedEvent += Csp_ReceivedEvent;
csp.Open();
OpenUartTestTimer();
Console.WriteLine($"open serial port:{portName} succful!baudRate:{baudRate}");
}
catch (Exception ex)
{
Console.WriteLine($"Open Uart Exception:{ex}");
}
}
private static void OpenUartTestTimer()
{
sendTimer.Interval = 5000;
sendTimer.Elapsed += SendTimer_Elapsed;
sendTimer.Start();
}
static int msgIndex = 0;
private static void SendTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (csp != null && csp.IsOpen)
{
msgIndex++;
string sendMsg = $"{selectedComPort} send msg:{msgIndex:d4}\t{DateTime.Now:yyyy/MM/dd HH:mm:ss.fff}\r\n";
csp.Write(sendMsg);
}
#if RunIsService
if (servicePorts.Count > 0)
msgIndex++;
foreach (var sps in servicePorts.Values)
{
if (sps.IsOpen)
{
string sendMsg = $"{sps.PortName} send msg:{msgIndex:d4}\t{DateTime.Now:yyyy/MM/dd HH:mm:ss.fff}\r\n";
sps.Write(sendMsg);
}
}
#endif
}
private static void TestWinUart(string portName)
{
SerialPort sp;
try
{
sp = new SerialPort()
{
PortName = portName,
BaudRate = baudRate
};
sp.Open();
string msg;
msg = "Hello Uart";
sp.WriteLine(msg);
Console.WriteLine(msg);
msg = "Byebye Uart";
sp.WriteLine(msg);
sp.Close();
sp.Dispose();
sp = null;
Console.WriteLine(msg);
}
catch (Exception ex)
{
Console.WriteLine($"Open Uart Exception:{ex}");
}
}
private static void TestUart(string portName)
{
CustomSerialPort sp;
try
{
sp = new CustomSerialPort(portName, baudRate);
sp.Open();
string msg;
msg = "Hello Uart";
sp.WriteLine(msg);
Console.WriteLine(msg);
msg = "Byebye Uart";
sp.WriteLine(msg);
sp.Close();
sp.Dispose();
sp = null;
Console.WriteLine(msg);
}
catch (Exception ex)
{
Console.WriteLine($"Open Uart Exception:{ex}");
}
}
private static void ShowWelcome()
{
var version = Assembly.GetExecutingAssembly().GetName().Version;
var Version = version.ToString();
var buildDateTime = System.IO.File.GetLastWriteTime(new Program().GetType().Assembly.Location).ToString();
Console.WriteLine($"Hello {Environment.OSVersion.Platform}!");
Console.WriteLine($"This is .netcore application.Version:{Version}\r\n");
Console.WriteLine($"System info:{Environment.OSVersion}");
Console.WriteLine($"Environment.Version:{Environment.Version}");
Console.WriteLine($"Environment Directory:{Environment.CurrentDirectory}");
Console.WriteLine($"Application Directory:{AppDomain.CurrentDomain.BaseDirectory}");
Console.WriteLine();
Console.WriteLine("Now time:{0:yyyy/MM/dd HH:mm:ss.fff}\r\n", DateTime.Now);
}
/// <summary>
/// Get PortNames
/// </summary>
private static void GetPortNames()
{
serailports = CustomSerialPort.GetPortNames();
if (serailports.Length > curSerialPortOrder)
selectedComPort = serailports[curSerialPortOrder];
}
}
}
| 50,522
|
https://github.com/guanxiong/birm/blob/master/themes/mobile/style129/js/alert.js
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
birm
|
guanxiong
|
JavaScript
|
Code
| 146
| 763
|
/**
* Created by 铁手 on 13-11-15.
*/
function alert(str, title ,callback , closedocallback) {
if(closedocallback == undefined) closedocallback = false;
$("#alert_box").remove();
$("body").css('position', 'relative');
//样式
$alert_css = '<style>#alert_warp{height:100%; width:100%; position:fixed; _position:absolute; top:0; z-index:1000;background-color: rgba(0, 0, 0, 0.4);}#alert_box{display:none;padding: 10px;width: 240px;left:50%;margin-left:-130px;background-color: rgba(0,0,0,0.8);border-radius: 6px;color: #fff;position: fixed;z-index:1001;}#alert_close{display: block;width: 100%;-webkit-tap-highlight-color:rgba(0,0,0,0);height: 30px;margin:0;text-align: right;}#alert_title{float: left;line-height: 30px;color: #999;}#alert_close img{width: 26px;}#alert_msg{text-align: center;margin-top: 4px;}#confirm{-webkit-tap-highlight-color:rgba(0,0,0,0);font-size:1.2em;display: inherit;text-decoration: none;color:#fff;text-align: center;margin: 0;padding: 8px;}</style>';
//结构
$html = '<div id="alert_warp"><div id="alert_box"><p id="alert_close">';
// 提示框标题
if (title) {
$html += '<span id="alert_title">' + title + '</span>';
}
$html += '<img src="./images/icon/icon_close1.png?1119" /></p><p id="alert_msg">' + str + '</p><p id="confirm">确 定</p></div></div>';
//表现
$("body").append($alert_css + $html);
$("#alert_box").fadeIn('fast');
$half_height = $(window).height() / 2;
$msgboxheight = $("#alert_box").height() / 2;
$("#alert_box").css('bottom', $half_height + 'px');
$("#alert_box").css('margin-bottom', '-' + $msgboxheight + 'px');
$("#confirm").click(function () {
$("#alert_box").fadeOut('slow', function () {
$("#alert_warp").remove();
if(callback){
callback();
}
});
});
$("#alert_close").click(function () {
$("#alert_warp").fadeOut('slow', function () {
$("#alert_warp").remove();
if(closedocallback && callback) callback();
});
});
/*callback*/
}
| 35,086
|
https://github.com/JanainaSantos/ouvidoria/blob/master/util/util-core/src/main/java/com/googlecode/ouvidoria/util/ByteArrayUtils.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,015
|
ouvidoria
|
JanainaSantos
|
Java
|
Code
| 194
| 491
|
package com.googlecode.ouvidoria.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ByteArrayUtils {
/**
* Transforma o objeto passado como paramtero em um array de bytes
*
* @param obj
* objeto a ser transformado
* @return o array de bytes representando o objeto
* @throws IOException
*/
public static byte[] toByteArray(Object obj) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream outputToString = new ObjectOutputStream(baos);
outputToString.writeObject(obj);
outputToString.close();
return baos.toByteArray();
}
/**
* Transforma o array de bytes em um objeto
*
* @param array
* array a ser transformado em objeto
* @return O Objeto gerado
* @throws IOException
* @throws ClassNotFoundException
*/
public static Object toObject(byte[] array) throws IOException, ClassNotFoundException {
ByteArrayInputStream bais = new ByteArrayInputStream(array);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
}
/**
* Concatena dois arrays de bytes
*
* @param l
* o array da esquerda
* @param r
* o array da direita
* @return o array contendo os dois arrays de entrada concatenados
*/
public static byte[] concatenate(byte[] l, byte[] r) {
byte[] b = new byte[l.length + r.length];
System.arraycopy(l, 0, b, 0, l.length);
System.arraycopy(r, 0, b, l.length, r.length);
return b;
}
}
| 23,942
|
https://github.com/IPDSnelting/velcom/blob/master/frontend/src/components/graphs/comparison/RepoBranchSelector.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
velcom
|
IPDSnelting
|
Vue
|
Code
| 323
| 1,417
|
<template>
<v-expansion-panels multiple accordion>
<v-expansion-panel
v-for="repo in sortedRepos"
:key="repo.id"
:disabled="repo.trackedBranches.length === 0"
>
<v-expansion-panel-header>
<v-checkbox
:input-value="allBranchesSelected(repo)"
:indeterminate="onlySomeBranchesSelected(repo)"
:style="{ color: colorForRepo(repo.id) }"
:color="colorForRepo(repo.id)"
dense
hide-details
class="ma-0 pa-0 flex-grow-0 colored-checkbox"
@change="toggleRepo(repo)"
@click.native.stop="() => {}"
></v-checkbox>
<span v-if="!hasConflictingNames">{{ repo.name }}</span>
<v-container fluid class="ma-0 pa-0" v-if="hasConflictingNames">
<v-row no-gutters class="mt-0">
<v-col>
<span>{{ repo.name }}</span>
</v-col>
</v-row>
<v-row no-gutters class="mt-0">
<v-col>
<span class="caption text--disabled">{{ repo.id }}</span>
</v-col>
</v-row>
</v-container>
<span v-if="repo.trackedBranches.length === 0" class="text-end ml-3">
No tracked branches
</span>
</v-expansion-panel-header>
<v-expansion-panel-content>
<v-list dense class="pt-0">
<v-list-item v-for="branch in repo.trackedBranches" :key="branch">
<v-list-item-content class="ma-0 pa-0">
<v-checkbox
:input-value="selectedBranchesForRepo(repo.id)"
:value="branch"
:label="branch"
:color="colorForRepo(repo.id)"
:style="{ color: colorForRepo(repo.id) }"
class="ma-0 pa-0 colored-checkbox"
hide-details
dense
@change="toggleBranch(repo, branch)"
></v-checkbox>
</v-list-item-content>
</v-list-item>
</v-list>
</v-expansion-panel-content>
</v-expansion-panel>
</v-expansion-panels>
</template>
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import { Repo, RepoId } from '@/store/types'
import { vxm } from '@/store'
import { Prop } from 'vue-property-decorator'
@Component
export default class RepoBranchSelector extends Vue {
@Prop()
private readonly selectedBranches!: Map<RepoId, string[]>
private selectedBranchesForRepo(repoId: RepoId) {
return this.selectedBranches.get(repoId) || []
}
private get sortedRepos() {
return vxm.repoModule.allRepos.slice().sort((a, b) => {
if (a.trackedBranches.length === 0 && b.trackedBranches.length === 0) {
return a.name.localeCompare(b.name)
}
if (a.trackedBranches.length === 0) {
return 1
}
if (b.trackedBranches.length === 0) {
return -1
}
return a.name.localeCompare(b.name)
})
}
private get hasConflictingNames() {
const distinct = new Set(this.sortedRepos.map(it => it.name.trim()))
return distinct.size !== this.sortedRepos.length
}
private colorForRepo(repoId: RepoId) {
return vxm.colorModule.colorByIndex(
vxm.repoModule.allRepos.findIndex(repo => repo.id === repoId) || 0
)
}
private onlySomeBranchesSelected(repo: Repo) {
const selectedLength = this.selectedBranchesForRepo(repo.id).length
return selectedLength < repo.trackedBranches.length && selectedLength > 0
}
private allBranchesSelected(repo: Repo) {
if (repo.trackedBranches.length === 0) {
return false
}
const selectedLength = this.selectedBranchesForRepo(repo.id).length
return selectedLength === repo.trackedBranches.length
}
private toggleRepo(repo: Repo) {
if (this.allBranchesSelected(repo)) {
this.$emit('update:set-all', {
repoId: repo.id,
branches: []
})
} else {
this.$emit('update:set-all', {
repoId: repo.id,
branches: repo.trackedBranches
})
}
}
private toggleBranch(repo: Repo, branch: string) {
this.$emit('update:toggle-branch', {
repoId: repo.id,
branch: branch
})
}
}
</script>
<style>
.colored-checkbox .v-icon {
color: inherit !important;
}
</style>
| 34,555
|
https://github.com/920232796/NLP_flask/blob/master/nlp_api/webs/controllers/index.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
NLP_flask
|
920232796
|
Python
|
Code
| 887
| 3,288
|
from re import U
from flask import Blueprint, request
from flask.json import jsonify
from flask import make_response
# from application import db
import jieba
from test.classification import text_classification
from test.auto_title_test import title
from test.poem_test import poem
from test.math_test import math_ques
from test.ner_test import ner_print
from test.gpt_article_continued import get_article
from test.relation_extract_test import relation_extract, predicate2id
from bert_seq2seq import load_chinese_base_vocab, Tokenizer
from webs.utils.utils import load_model, RedisCache
from datetime import datetime
import torch
## 引入缓存
from application import cache
import redis
router_index = Blueprint("index_page", __name__)
r = RedisCache(host="localhost", port=6379, decode_responses=True)
# device = torch.device("cuda:3" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")
classify_target = ["财经", "彩票", "房产", "股票", "家居", "教育", "科技", "社会", "时尚", "时政", "体育", "星座", "游戏", "娱乐"]
ner_target = ["other", "address", "book", "company", "game", "government", "movie", "name", "organization", "position", "scene"]
model_dir = "../state_dict/"
vocab_path = model_dir + "roberta_wwm_vocab.txt" # roberta模型字典的位置
model_name = "roberta"
nezha_name = "nezha"
# 模型位置
cls_model_path = model_dir + "bert_multi_classify_model.bin"
couplet_model_path = model_dir + "bert_model_poem_ci_duilian.bin"
math_model_path = model_dir + "bert_math_ques_model.bin"
ner_model_path = model_dir + "bert_ner_model_crf.bin"
auto_title_model_path = model_dir + "nezha_auto_title.bin"
gpt_article_model_path = model_dir + "gpt2_article_continued/pytorch_model.bin"
auto_relation_extract_model_path = model_dir + "nezha_relation_extract.bin"
## 文本分类
word2idx = load_chinese_base_vocab(vocab_path, simplfied=False)
tokenizer = Tokenizer(word2idx)
bert_classify = load_model(word2idx, model_path=cls_model_path,
model_name=model_name, model_class="cls",
target_size=len(classify_target), is_all_params=True, device=device)
## 对联
bert_couplet = load_model(word2idx, model_path=couplet_model_path,
model_name=model_name, model_class="seq2seq",
is_all_params=True, device=device)
## 小学数学题
bert_math = load_model(word2idx, model_path=math_model_path,
model_name=model_name, model_class="seq2seq",
is_all_params=True, device=device)
## ner
bert_ner = load_model(word2idx, model_path=ner_model_path,
model_name=model_name, model_class="sequence_labeling_crf",
target_size=len(ner_target), is_all_params=True, device=device)
## auto title
bert_auto_title = load_model(word2idx, model_path=auto_title_model_path,
model_name=nezha_name, model_class="seq2seq",
is_all_params=True, device=device)
## gpt2 article continued
gpt_article = load_model(word2idx, model_path=gpt_article_model_path ,is_gpt=True, device=device, is_all_params=False)
## auto_relation_extract
auto_relation_extract_model = load_model(word2idx, model_path=auto_relation_extract_model_path,
model_name=nezha_name, model_class="relation_extrac",
target_size=len(predicate2id), is_all_params=True, device=device)
print("all models have beed loaded .")
@router_index.route("/")
def index():
return "hello world test install"
# 请求拦截器 可以配置一个全局的拦截,当1s内请求次数超过5次时候,那么则暂停一段时间
@router_index.before_request
def before_user():
global flag
resp = {"code": 200, "msg": "success", "data": [], "ret": 1}
## 在这里做一下缓存功能
num = cache.get("number")
if num is not None and num > 4:
return "网站流量过大,请稍后访问。"
if num is None :
num = 0
num = num + 1
cache.set("number", num, timeout=3)
return None
@router_index.route("/auto_fenci", methods=["GET", "POST"])
def auto_fenci():
resp = {"code": 200, "msg": "success", "data": [], "ret": 1}
req = request.values
word = req["text"] if "text" in req else ""
if word == "":
resp["ret"] = 0
resp["msg"] = "请重新输入句子"
return jsonify(resp)
word_split = jieba.cut(word)
word_split = "\t".join(word_split)
print(f"输出结果: {word_split}")
resp["data"] = word_split
return jsonify(resp)
@router_index.route("/text_classify", methods=["GET", "POST"])
def text_classify():
resp = {"code": 200, "msg": "success", "data": [], "ret": 1}
req = request.values
text = req["text"] if "text" in req else ""
if text == "":
resp["ret"] = 0
resp["msg"] = "请重新输入句子"
return jsonify(resp)
cache_res = r.get_cache(text, prefix="classify")
if cache_res == "":
# 没有缓存
res = text_classification(bert_classify, text, tokenizer, device=device)
r.set_cache(text, prefix="classify", res=res)
# print(r.keys())
else :
res = cache_res
print(f"输出结果: {res}")
resp["data"] = res
return jsonify(resp)
@router_index.route("/auto_title", methods=["GET", "POST"])
def auto_title():
resp = {"code": 200, "msg": "success", "data": [], "ret": 1}
req = request.values
text = req["text"] if "text" in req else ""
if text == "":
resp["ret"] = 0
resp["msg"] = "请重新输入句子"
return jsonify(resp)
cache_res = r.get_cache(text, prefix="auto_title")
if cache_res == "":
# 没有缓存
res = title(bert_auto_title, text)
r.set_cache(text, prefix="auto_title", res=res)
# print(r.keys())
else :
res = cache_res
print(f"输出结果: {res}")
resp["data"] = res
return jsonify(resp)
@router_index.route("/auto_couplet", methods=["GET", "POST"])
def auto_couplet():
resp = {"code": 200, "msg": "success", "data": [], "ret": 1}
req = request.values
text = req["text"] if "text" in req else ""
if text == "":
resp["ret"] = 0
resp["msg"] = "请重新输入句子"
return jsonify(resp)
cache_res = r.get_cache(text, prefix="auto_couplet")
if cache_res == "":
# 没有缓存
res = poem(bert_couplet, text)
r.set_cache(text, prefix="auto_couplet", res=res)
# print(r.keys())
else :
res = cache_res
print(f"输出结果: {res}")
resp["data"] = res
return jsonify(resp)
@router_index.route("/auto_math", methods=["GET", "POST"])
def auto_math():
resp = {"code": 200, "msg": "success", "data": [], "ret": 1}
req = request.values
text = req["text"] if "text" in req else ""
if text == "":
resp["ret"] = 0
resp["msg"] = "请重新输入句子"
return jsonify(resp)
cache_res = r.get_cache(text, prefix="auto_math")
if cache_res == "":
# 没有缓存
res = math_ques(bert_math, text)
r.set_cache(text, prefix="auto_math", res=res)
# print(r.keys())
else :
res = cache_res
try:
res_res = eval(res)
resp["data"] = res + " = " + str(res_res)
except Exception as e :
# print(e)
resp["data"] = "no result"
return jsonify(resp)
print(f"输出结果: { resp['data']}")
return jsonify(resp)
@router_index.route("/auto_ner", methods=["GET", "POST"])
def auto_ner():
resp = {"code": 200, "msg": "success", "data": [], "ret": 1}
req = request.values
text = req["text"] if "text" in req else ""
if text == "":
resp["ret"] = 0
resp["msg"] = "请重新输入句子"
return jsonify(resp)
cache_res = r.get_cache(text, prefix="auto_ner")
if cache_res == "":
# 没有缓存
res = ner_print(bert_ner, text, word2idx, tokenizer, ner_target, device=device)
r.set_cache(text, prefix="auto_ner", res=res)
# print(r.keys())
else :
res = cache_res
resp["data"] = res
print(f"输出结果: { resp['data']}")
return jsonify(resp)
@router_index.route("/auto_article", methods=["GET", "POST"])
def auto_article():
resp = {"code": 200, "msg": "success", "data": [], "ret": 1}
req = request.values
text = req["text"] if "text" in req else ""
if text == "":
resp["ret"] = 0
resp["msg"] = "请重新输入句子开头"
return jsonify(resp)
res = get_article(gpt_article, text, out_max_length=100, top_k=10)
resp["data"] = res
print(f"输出结果: { resp['data']}")
return jsonify(resp)
@router_index.route("/auto_relation_extract", methods=["GET", "POST"])
def auto_relation_extract():
resp = {"code": 200, "msg": "success", "data": [], "ret": 1}
req = request.values
text = req["text"] if "text" in req else ""
if text == "":
resp["ret"] = 0
resp["msg"] = "请重新输入"
return jsonify(resp)
cache_res = r.get_cache(text, prefix="auto_relation_extract")
if cache_res == "":
# 没有缓存
res = relation_extract(auto_relation_extract_model, text, word2idx, tokenizer, device=device)
r.set_cache(text, prefix="auto_relation_extract", res=res)
# print(r.keys())
else :
res = cache_res
resp["data"] = res
print(f"输出结果: { resp['data']}")
return jsonify(resp)
| 46,436
|
https://github.com/styler/fleet/blob/master/pkg/args_test.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
fleet
|
styler
|
Go
|
Code
| 205
| 526
|
// Copyright 2014 The fleet Authors
//
// 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 pkg
import "testing"
func TestTrimToDashes(t *testing.T) {
var argtests = []struct {
input []string
output []string
}{
{[]string{"foo", "bar", "baz"}, []string{"foo", "bar", "baz"}},
{[]string{"abc", "def", "--", "ghi"}, []string{"ghi"}},
{[]string{"abc", "def", "--"}, []string{}},
{[]string{"--"}, []string{}},
{[]string{"--", "abc", "def", "ghi"}, []string{"abc", "def", "ghi"}},
{[]string{"--", "bar", "--", "baz"}, []string{"bar", "--", "baz"}},
{[]string{"--flagname", "--", "ghi"}, []string{"ghi"}},
{[]string{"--", "--flagname", "ghi"}, []string{"--flagname", "ghi"}},
}
for _, test := range argtests {
args := TrimToDashes(test.input)
if len(test.output) != len(args) {
t.Fatalf("error trimming dashes: expected %s, got %s", test.output, args)
}
for i, v := range args {
if v != test.output[i] {
t.Fatalf("error trimming dashes: expected %s, got %s", test.output, args)
}
}
}
}
| 7,673
|
https://github.com/svetlimladenov/ASP.NET-MVC-5/blob/master/Template/src/MVC5Template/Web/MvcTemplate.Web/Services/Contracts/IPhonesServices.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
ASP.NET-MVC-5
|
svetlimladenov
|
C#
|
Code
| 33
| 123
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using MvcTemplate.Web.Controllers;
using MvcTemplate.Web.Models;
namespace MvcTemplate.Web.Services.Contacts
{
public interface IPhonesServices
{
Phone CreatePhone(CreatePhoneInputModel inputModel, string id);
PhoneDetailsViewModel GetPhoneDetails(string model);
}
}
| 631
|
https://github.com/ivanoff/api-i/blob/master/test/_init.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
api-i
|
ivanoff
|
JavaScript
|
Code
| 40
| 118
|
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const Api = require('../src');
const config = require('./mocks/config');
describe('Init', () => {
global.Api = Api;
global.config = config;
global.configNoToken = {...config, token: undefined};
global.configNoDb = {...config, token: undefined, db: undefined};
})
| 25,069
|
https://github.com/shervs336/paluwagan/blob/master/resources/views/auth/register.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
paluwagan
|
shervs336
|
PHP
|
Code
| 73
| 366
|
@extends('layout.app')
@section('content')
<!-- resources/views/auth/register.blade.php -->
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1 class="text-center">Paluwagan 2018</h1>
<br />
<div class="well">
<form method="POST" action="/auth/register">
{!! csrf_field() !!}
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="{{ old('name') }}">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" value="{{ old('username') }}">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control">
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" name="password_confirmation" class="form-control">
</div>
<div>
<button type="submit" class="btn btn-default">Register</button>
</div>
</form>
</div>
</div>
</div>
@endsection
| 8,479
|
https://github.com/DNCBA/test/blob/master/mhcdemo/src/main/java/com/mhc/mybatis/demo/config/QueryInterceptor.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
test
|
DNCBA
|
Java
|
Code
| 128
| 509
|
package com.mhc.mybatis.demo.config;
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.Properties;
@Intercepts(value = {
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})}
)
public class QueryInterceptor implements Interceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(QueryInterceptor.class);
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
LOGGER.info("QueryInterceptor args {}", args);
Method method = invocation.getMethod();
LOGGER.info("QueryInterceptor method {}",method.getName());
Object target = invocation.getTarget();
LOGGER.info("QueryInterceptor target {}",target.getClass().getName());
Object resutl = invocation.proceed();
LOGGER.info("QueryInterceptor result {}", resutl);
return resutl;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
| 31,156
|
https://github.com/xuedong/time-series/blob/master/TGA_python_wrapper/setup_global_align.py
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
time-series
|
xuedong
|
Python
|
Code
| 58
| 152
|
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
# Note: numy.get_include is important to use the correct numpy version (in a non-std location)
# else we get "RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility"
ext_modules = [Extension("global_align", ["global_align.pyx"], include_dirs=[numpy.get_include()])]
setup(
name = 'global_align',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
| 2,752
|
https://github.com/theatrejs-labs/from-user-to-maker/blob/master/src/slides/Inklings/components/Photoshop/index.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
from-user-to-maker
|
theatrejs-labs
|
TSX
|
Code
| 328
| 967
|
import React, { RefObject } from 'react'
import sidebar from './assets/sidebar.png'
import top from './assets/top.png'
import cursorImage from './assets/cursor.svg'
import './style.scss'
import PhotoshopScene from './PhotoshopScene';
import { project } from '../../../../shared/Theatre';
interface IProps {
appear: boolean
}
interface IState {
cursor: {
x: number,
y: number
}
selection: {
left: number,
top: number,
width: number,
height: number,
opacity: number
}
}
export default class Photoshop extends React.Component<IProps, IState> {
playground: RefObject<HTMLDivElement> = React.createRef()
photoshop: PhotoshopScene
timeline: Theatre.Timeline
constructor (props: IProps) {
super(props)
this.state = {
cursor: {
x: 50,
y: 50
},
selection: {
top: 0,
left: 0,
width: 0,
height: 0,
opacity: 0
}
}
this.photoshop = new PhotoshopScene();
this.timeline = project.getTimeline('Photoshop')
this.initTheatre()
}
initTheatre () {
const cursor = this.timeline.getObject('Cursor', {}, {
props: {
x: { type: 'number' },
y: { type: 'number' }
}
})
const selection = this.timeline.getObject('Selection', {}, {
props: {
top: { type: 'number' },
left: { type: 'number' },
width: { type: 'number' },
height: { type: 'number' },
opacity: { type: 'number' }
}
})
const canvas = this.timeline.getObject('Photoshop Canvas', {}, {
props: {
draw: { type: 'number' },
shader: { type: 'number' },
}
})
cursor.onValuesChange((values) => {
this.setState({ cursor: values as any })
})
selection.onValuesChange((values) => {
this.setState({ selection: values as any })
})
canvas.onValuesChange((values) => {
this.photoshop.setState(values)
})
}
stepOne () {
this.timeline.play({ range: { from: 0, to: 2350 } })
}
stepTwo () {
this.timeline.play({ range: { from: 2200, to: 4000 } })
}
componentDidMount () {
if (this.playground.current) {
this.photoshop.init(this.playground.current);
}
}
render () {
const { appear } = this.props
const { cursor, selection } = this.state
return (<div className={"Comparison__panel photoshop" + (appear ? ' appear' : '')}>
<h1>Photoshop</h1>
<div className="photoshop__app">
<img className="sidebar" src={sidebar} alt="Photoshop Sidebar"/>
<img className="topbar" src={top} alt="Photoshop Topbar"/>
<div ref={this.playground} className="playground">
<img src={cursorImage} style={{ marginTop: cursor.y, marginLeft: cursor.x }} className="cursor" alt="Cursor" />
<div className="selection" style={{
marginTop: selection.top,
marginLeft: selection.left,
width: selection.width,
height: selection.height,
opacity: selection.opacity
}}></div>
</div>
</div>
</div>)
}
}
| 2,862
|
https://github.com/BandwidthOnDemand/nsi-requester/blob/master/app/support/CustomSSLEngineProvider.scala
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,019
|
nsi-requester
|
BandwidthOnDemand
|
Scala
|
Code
| 320
| 560
|
/*
* Copyright (c) 2012, 2013, 2014, 2015, 2016 SURFnet BV
* All rights reserved.
*
* 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.
* * Neither the name of the SURFnet BV nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* 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.
*/
package support
import javax.net.ssl._
import play.core.ApplicationProvider
import play.server.api._
/*
* This custom SSL engine creates an instance of the default SSL Engine and
* enables client authentication. For this class to be instantiated the
* following command line argument must be used when starting the application:
*
* -Dplay.http.sslengineprovider=support.CustomSSLEngineProvider
*/
class CustomSSLEngineProvider(appProvider: ApplicationProvider) extends SSLEngineProvider {
override def createSSLEngine(): SSLEngine = {
val sslEngine = SSLContext.getDefault.createSSLEngine
sslEngine.setNeedClientAuth(true)
sslEngine
}
}
| 3,116
|
https://github.com/apache/sis/blob/master/endorsed/src/org.apache.sis.feature/main/org/apache/sis/feature/builder/AssociationRoleBuilder.java
|
Github Open Source
|
Open Source
|
Apache-2.0, LicenseRef-scancode-unknown-license-reference, BSD-3-Clause, MIT, EPL-1.0, Classpath-exception-2.0, GPL-2.0-only, LicenseRef-scancode-public-domain
| 2,023
|
sis
|
apache
|
Java
|
Code
| 1,263
| 2,748
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sis.feature.builder;
import org.opengis.util.GenericName;
import org.apache.sis.feature.Features;
import org.apache.sis.feature.DefaultAssociationRole;
// Specific to the main branch:
import org.apache.sis.feature.DefaultFeatureType;
/**
* Describes one association from the {@code FeatureType} to be built by an {@code FeatureTypeBuilder} to another
* {@code FeatureType}. A different instance of {@code AssociationRoleBuilder} exists for each feature association
* to describe. Those instances are created preferably by {@code FeatureTypeBuilder.addAssociation(FeatureType)},
* or in case of cyclic reference by {@code FeatureTypeBuilder.addAssociation(GenericName)}.
*
* @author Johann Sorel (Geomatys)
* @author Martin Desruisseaux (Geomatys)
* @version 0.8
*
* @see org.apache.sis.feature.DefaultAssociationRole
* @see FeatureTypeBuilder#addAssociation(DefaultFeatureType)
* @see FeatureTypeBuilder#addAssociation(GenericName)
*
* @since 0.8
*/
public final class AssociationRoleBuilder extends PropertyTypeBuilder {
/**
* The target feature type, or {@code null} if unknown.
*/
private final DefaultFeatureType type;
/**
* Name of the target feature type (never null).
*/
private final GenericName typeName;
/**
* The association created by this builder, or {@code null} if not yet created.
* This field must be cleared every time that a setter method is invoked on this builder.
*/
private transient DefaultAssociationRole property;
/**
* Creates a new {@code AssociationRole} builder for values of the given type.
* The {@code type} argument can be null if unknown, but {@code typeName} is mandatory.
*
* @param owner the builder of the {@code FeatureType} for which to add this property.
*/
AssociationRoleBuilder(final FeatureTypeBuilder owner, final DefaultFeatureType type, final GenericName typeName) {
super(owner);
this.type = type;
this.typeName = typeName;
}
/**
* Creates a new {@code FeatureAssociationRole} builder initialized to the values of an existing association.
*
* @param owner the builder of the {@code FeatureType} for which to add this property.
*/
AssociationRoleBuilder(final FeatureTypeBuilder owner, final DefaultAssociationRole template) {
super(owner);
property = template;
minimumOccurs = template.getMinimumOccurs();
maximumOccurs = template.getMaximumOccurs();
if (!template.isResolved()) {
type = null;
typeName = Features.getValueTypeName(template);
} else {
type = template.getValueType();
typeName = type.getName();
}
initialize(template);
}
/**
* If the {@code FeatureAssociationRole} created by the last call to {@link #build()} has been cached,
* clears that cache. This method must be invoked every time that a setter method is invoked.
*/
@Override
final void clearCache() {
property = null;
super.clearCache();
}
/**
* Appends a text inside the value returned by {@link #toString()}, before the closing bracket.
*/
@Override
final void toStringInternal(final StringBuilder buffer) {
buffer.append(" → ").append(typeName);
}
/**
* Returns a default name to use if the user did not specified a name. The first letter will be changed to
* lower case (unless the name looks like an acronym) for compliance with Java convention on property names.
*/
@Override
final String getDefaultName() {
return typeName.tip().toString();
}
/**
* Sets the {@code FeatureAssociationRole} name as a generic name.
* If another name was defined before this method call, that previous value will be discarded.
*
* @return {@code this} for allowing method calls chaining.
*/
@Override
public AssociationRoleBuilder setName(final GenericName name) {
super.setName(name);
return this;
}
/**
* Sets the {@code FeatureAssociationRole} name as a simple string (local name).
* The namespace will be the value specified by the last call to {@link FeatureTypeBuilder#setNameSpace(CharSequence)},
* but that namespace will not be visible in the {@linkplain org.apache.sis.util.iso.DefaultLocalName#toString()
* string representation} unless the {@linkplain org.apache.sis.util.iso.DefaultLocalName#toFullyQualifiedName()
* fully qualified name} is requested.
*
* <p>This convenience method creates a {@link org.opengis.util.LocalName} instance from
* the given {@code CharSequence}, then delegates to {@link #setName(GenericName)}.</p>
*
* @return {@code this} for allowing method calls chaining.
*/
@Override
public AssociationRoleBuilder setName(final CharSequence localPart) {
super.setName(localPart);
return this;
}
/**
* Sets the {@code FeatureAssociationRole} name as a string in the given scope.
* The {@code components} array must contain at least one element.
* The last component (the {@linkplain org.apache.sis.util.iso.DefaultScopedName#tip() tip}) will be sufficient
* in many cases for calls to the {@link org.apache.sis.feature.AbstractFeature#getProperty(String)} method.
* The other elements before the last one are optional and can be used for resolving ambiguity.
* They will be visible as the name {@linkplain org.apache.sis.util.iso.DefaultScopedName#path() path}.
*
* <div class="note"><b>Example:</b>
* a call to {@code setName("A", "B", "C")} will create a "A:B:C" name.
* An association built with this name can be obtained from a feature by a call to {@code feature.getProperty("C")}
* if there is no ambiguity, or otherwise by a call to {@code feature.getProperty("B:C")} (if non-ambiguous) or
* {@code feature.getProperty("A:B:C")}.</div>
*
* In addition to the path specified by the {@code components} array, the name may also contain
* a namespace specified by the last call to {@link FeatureTypeBuilder#setNameSpace(CharSequence)}.
* But contrarily to the specified components, the namespace will not be visible in the name
* {@linkplain org.apache.sis.util.iso.DefaultScopedName#toString() string representation} unless the
* {@linkplain org.apache.sis.util.iso.DefaultScopedName#toFullyQualifiedName() fully qualified name} is requested.
*
* <p>This convenience method creates a {@link org.opengis.util.LocalName} or {@link org.opengis.util.ScopedName}
* instance depending on whether the {@code names} array contains exactly 1 element or more than 1 element, then
* delegates to {@link #setName(GenericName)}.</p>
*
* @return {@code this} for allowing method calls chaining.
*/
@Override
public AssociationRoleBuilder setName(final CharSequence... components) {
super.setName(components);
return this;
}
/**
* Sets the minimum number of associations. If the given number is greater than the
* {@linkplain #getMaximumOccurs() maximal number} of associations, than the maximum
* is also set to that value.
*
* @param occurs the new minimum number of associations.
* @return {@code this} for allowing method calls chaining.
*/
@Override
public AssociationRoleBuilder setMinimumOccurs(final int occurs) {
super.setMinimumOccurs(occurs);
return this;
}
/**
* Sets the maximum number of associations. If the given number is less than the
* {@linkplain #getMinimumOccurs() minimal number} of associations, than the minimum
* is also set to that value. {@link Integer#MAX_VALUE} means that there is no maximum.
*
* @param occurs the new maximum number of associations.
* @return {@code this} for allowing method calls chaining.
*/
@Override
public AssociationRoleBuilder setMaximumOccurs(final int occurs) {
super.setMaximumOccurs(occurs);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public AssociationRoleBuilder setDefinition(final CharSequence definition) {
super.setDefinition(definition);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public AssociationRoleBuilder setDesignation(final CharSequence designation) {
super.setDesignation(designation);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public AssociationRoleBuilder setDescription(final CharSequence description) {
super.setDescription(description);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public AssociationRoleBuilder setDeprecated(final boolean deprecated) {
super.setDeprecated(deprecated);
return this;
}
/**
* Builds the association role from the information specified to this builder.
* If a role has already been built and this builder state has not changed since the role creation,
* then the previously created {@code FeatureAssociationRole} instance is returned.
*
* <div class="warning"><b>Warning:</b> In a future SIS version, the return type may be changed to the
* {@code org.opengis.feature.FeatureAssociationRole} interface. This change is pending GeoAPI revision.</div>
*
* @return the association role.
*/
@Override
public DefaultAssociationRole build() {
if (property == null) {
if (type != null) {
property = new DefaultAssociationRole(identification(), type, minimumOccurs, maximumOccurs);
} else {
property = new DefaultAssociationRole(identification(), typeName, minimumOccurs, maximumOccurs);
}
}
return property;
}
}
| 37,078
|
https://github.com/johnantoni/plugin.social/blob/master/lib/social_helpers.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,009
|
plugin.social
|
johnantoni
|
Ruby
|
Code
| 48
| 155
|
module SocialHelpers
def get_twitter(u, p)
s = ""
if (u.length > 0 && p.length > 0)
client = Twitter::Client.new(:login => u, :pass => p)
timeline = client.timeline_for(:user, :id => u.to_s, :count => 1) do |status|
s = "<a href='http://twitter.com/#{status.user.screen_name}' alt='Twitter', title='Twitter'>#{status.user.screen_name}:</a> #{status.text}"
end
end
return s
end
end
| 48,360
|
https://github.com/georgeconstantinou/project-template-cakephp/blob/master/config/log_actions.php
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
project-template-cakephp
|
georgeconstantinou
|
PHP
|
Code
| 44
| 105
|
<?php
return [
'LogActions' => [
// Enable actions logs
'enableLogActions' => true,
// List of controllers to Log
'controllers' => [
// example :
// \App\Controller\ThingsController::class,
],
// Actions to log
'actions' => [
// example :
// 'view', 'edit'
],
],
];
| 36,635
|
https://github.com/ellawg/ellawirstad.se/blob/master/src/components/molecules/ArrowBack.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
ellawirstad.se
|
ellawg
|
TypeScript
|
Code
| 29
| 82
|
import Link from "next/link";
import Arrow from "../atoms/Arrow";
const ArrowBack = () => (
<Link href="/">
<div className="m-8 h-8 cursor-pointer">
<Arrow left />
</div>
</Link>
);
export default ArrowBack;
| 7,735
|
https://github.com/Chanc3/beta-revai-java-sdk/blob/master/src/test/java/ai/rev/speechtotext/integration/GetCaptionsTest.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
beta-revai-java-sdk
|
Chanc3
|
Java
|
Code
| 245
| 914
|
package ai.rev.speechtotext.integration;
import ai.rev.speechtotext.ApiClient;
import ai.rev.speechtotext.models.asynchronous.RevAiCaptionType;
import ai.rev.speechtotext.models.asynchronous.RevAiJob;
import ai.rev.speechtotext.models.asynchronous.RevAiJobStatus;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import static ai.rev.speechtotext.testutils.ConversionUtil.convertInputStreamToString;
import static org.assertj.core.api.Assertions.assertThat;
public class GetCaptionsTest {
private static ApiClient apiClient;
private static String jobId;
private final String VTT_CONTAINS = "WEBVTT";
@Before
public void setup() throws IOException {
apiClient = new ApiClient(EnvHelper.getToken());
String mediaUrl = "https://www.rev.ai/FTC_Sample_1.mp3";
RevAiJob revAiJob = apiClient.submitJobUrl(mediaUrl);
jobId = revAiJob.getJobId();
pollForJobCompletionOrTimeout(jobId);
}
@Test
public void GetCaptions_JobIdIsValid_ReturnsCaptionStream() throws IOException {
InputStream inputStream = apiClient.getCaptions(jobId);
String captions = convertInputStreamToString(inputStream);
assertThat(captions).as("Caption output").isNotEmpty();
assertThat(captions).as("Caption content").doesNotContain(VTT_CONTAINS);
}
@Test
public void GetCaptions_TypeIsSpecifiedAndJobIdIsValid_ReturnsCaptionStreamInVttFormat()
throws IOException {
InputStream inputStream = apiClient.getCaptions(jobId, RevAiCaptionType.VTT);
String captions = convertInputStreamToString(inputStream);
assertThat(captions).as("Captions output").isNotEmpty();
assertThat(captions).as("Caption content").contains(VTT_CONTAINS);
}
private void pollForJobCompletionOrTimeout(String jobId) {
boolean isComplete = false;
int pollingAttempts = 0;
int maximumPollingAttempts = 60;
while (!isComplete && pollingAttempts < maximumPollingAttempts) {
RevAiJob revAiJob;
try {
revAiJob = apiClient.getJobDetails(jobId);
} catch (IOException e) {
throw new RuntimeException(
"Failed to get job details for [" + jobId + "] " + e.getMessage());
}
RevAiJobStatus jobStatus = revAiJob.getJobStatus();
if (jobStatus.equals(RevAiJobStatus.TRANSCRIBED)) {
isComplete = true;
} else if (jobStatus.equals(RevAiJobStatus.FAILED)) {
throw new RuntimeException("Job [" + jobId + "] failed");
} else {
pollingAttempts++;
if (pollingAttempts == maximumPollingAttempts) {
throw new RuntimeException(
"Maximum polling attempts ["
+ maximumPollingAttempts
+ "] reached and Job ["
+ jobId
+ "] has a status of ["
+ jobStatus.getStatus()
+ "]");
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new RuntimeException("Thread.sleep failed " + e.getMessage());
}
}
}
}
}
| 19,070
|
https://github.com/hybridappnest/AppNestiOS/blob/master/Pods/Headers/Private/TXIMSDK_TUIKit_iOS/TUIMemberPanelCell.h
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
AppNestiOS
|
hybridappnest
|
C
|
Code
| 1
| 35
|
../../../TXIMSDK_TUIKit_iOS/TUIKit/Classes/Section/Commom/Cell/TUIMemberPanelCell.h
| 2,541
|
https://github.com/maazirfan/gearVRProject/blob/master/Assets/Plugins/Android/Shader/MeshVertShader.vsh
|
Github Open Source
|
Open Source
|
MIT
| null |
gearVRProject
|
maazirfan
|
GLSL
|
Code
| 86
| 301
|
attribute highp vec3 inVertex;
attribute mediump vec3 inNormal;
attribute mediump vec2 inTexCoord;
uniform highp mat4 MVPMatrix;
uniform mediump vec2 TexCoordMove;
varying mediump vec2 TexCoord;
void main()
{
highp vec4 vPos = vec4(0,0,0,1);
vPos.x = ( inTexCoord.x * 2.0 - 1.0 );
vPos.y = ( inTexCoord.y * 2.0 - 1.0 );
gl_Position = vPos;
// Pass through texcoords
//inTexCoord.x += TexCoordMove.x;
mediump vec4 vec4Temp = vec4(inTexCoord.x - TexCoordMove.x,inTexCoord.y - TexCoordMove.y,0,1.0);
vec4Temp = MVPMatrix * vec4Temp;
vec4Temp.xyz = vec4Temp.xyz / vec4Temp.w;
TexCoord = vec4Temp.xy;
//TexCoord = inTexCoord;
}
| 46,470
|
https://github.com/zone117x/CsQuery/blob/master/source/CsQuery.Tests/Utility/FastActivator.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
CsQuery
|
zone117x
|
C#
|
Code
| 86
| 324
|
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using Assert = NUnit.Framework.Assert;
using CollectionAssert = NUnit.Framework.CollectionAssert;
using StringAssert = NUnit.Framework.StringAssert;
using TestContext = Microsoft.VisualStudio.TestTools.UnitTesting.TestContext;
using CsQuery;
using CsQuery.Utility;
using CsQuery.ExtensionMethods;
using CsQuery.ExtensionMethods.Internal;
using CsQuery.StringScanner;
namespace CsQuery.Tests.Utility
{
[TestClass,TestFixture]
public class FastActivator_
{
[Test,TestMethod]
public void CreateInstance_Object()
{
var test = Activator.CreateInstance<TestClass>();
Assert.AreEqual(1, test.integer);
}
[TestMethod,Test]
public void CreateInstance_Type() {
var integer = Activator.CreateInstance(typeof(int));
Assert.AreEqual(integer, 0);
}
class TestClass
{
public TestClass()
{
integer = 1;
}
public int integer;
}
}
}
| 32,980
|
https://github.com/mikegwyn17/LudemDareSpring2020/blob/master/LudemDareSpring2020/Assets/Scripts/Enemy/EnemyReaction.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
LudemDareSpring2020
|
mikegwyn17
|
C#
|
Code
| 89
| 197
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement; // This is very important if we want to restart the level
public class EnemyReaction : MonoBehaviour
{
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
// This function is called every time another collider overlaps the trigger collider
void OnTriggerEnter2D(Collider2D other)
{
// Checking if the overlapped collider is an enemy
if (other.CompareTag("Enemy"))
{
// This scene HAS TO BE IN THE BUILD SETTINGS!!!
SceneManager.LoadScene("SceneOne");
}
}
}
| 23,459
|
https://github.com/solitardj9/timeline-service/blob/master/timelineService/src/main/java/com/solitardj9/timelineService/utils/fileUtil/MapFileUtil.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
timeline-service
|
solitardj9
|
Java
|
Code
| 351
| 1,169
|
package com.solitardj9.timelineService.utils.fileUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentNavigableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MapFileUtil {
//
private static final Logger logger = LoggerFactory.getLogger(MapFileUtil.class);
public static void writeTimelinespAsFile(Map<String, ConcurrentNavigableMap<Long, String>> timelines, String fileName) {
//
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(fileName));
oos.writeObject(timelines);
oos.close();
} catch (IOException e) {
logger.error("[MapFileUtil].writeMapAsFile : error = " + e.getStackTrace());
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
logger.error("[MapFileUtil].writeMapAsFile : error = " + e.getStackTrace());
}
}
}
}
@SuppressWarnings({ "unchecked" })
public static Map<String, ConcurrentNavigableMap<Long, String>> readTimelinesFromFile(String fileName) {
//
Map<String, ConcurrentNavigableMap<Long, String>> timelines = new HashMap<>();
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(fileName));
timelines = (Map<String, ConcurrentNavigableMap<Long, String>>) ois.readObject();
ois.close();
} catch (IOException e) {
logger.error("[MapFileUtil].readTimelinesFromFile : error = " + e.getStackTrace());
return timelines;
} catch (ClassNotFoundException e) {
logger.error("[MapFileUtil].readTimelinesFromFile : error = " + e.getStackTrace());
return timelines;
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
logger.error("[MapFileUtil].readTimelinesFromFile : error = " + e.getStackTrace());
}
}
}
return timelines;
}
@SuppressWarnings({ "unchecked" })
public static Map<String, ConcurrentNavigableMap<Long, String>> readTimelinesFromFile(File file) {
//
Map<String, ConcurrentNavigableMap<Long, String>> timelines = new HashMap<>();
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(file));
timelines = (Map<String, ConcurrentNavigableMap<Long, String>>) ois.readObject();
ois.close();
} catch (IOException e) {
logger.error("[MapFileUtil].readTimelinesFromFile : error = " + e.getStackTrace());
return timelines;
} catch (ClassNotFoundException e) {
logger.error("[MapFileUtil].readTimelinesFromFile : error = " + e.getStackTrace());
return timelines;
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
logger.error("[MapFileUtil].readTimelinesFromFile : error = " + e.getStackTrace());
}
}
}
return timelines;
}
public static Boolean deleteFile(String fileName) {
//
File file = new File(fileName);
if (file.exists()) {
if (file.delete()) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
public static Boolean deleteFile(File file) {
//
if (file.exists()) {
if (file.delete()) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
}
| 3,156
|
https://github.com/gradle/gradle/blob/master/subprojects/core/src/main/java/org/gradle/internal/buildtree/DefaultBuildTreeContext.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause, LGPL-2.1-or-later, LicenseRef-scancode-mit-old-style, EPL-2.0, CDDL-1.0, MIT, LGPL-2.1-only, Apache-2.0, MPL-2.0, EPL-1.0
| 2,023
|
gradle
|
gradle
|
Java
|
Code
| 176
| 413
|
/*
* Copyright 2021 the original author or authors.
*
* 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 org.gradle.internal.buildtree;
import org.gradle.internal.event.ListenerManager;
import org.gradle.internal.invocation.BuildAction;
import org.gradle.internal.service.ServiceRegistry;
class DefaultBuildTreeContext implements BuildTreeContext {
private final ServiceRegistry services;
private boolean completed;
public DefaultBuildTreeContext(ServiceRegistry services) {
this.services = services;
}
@Override
public BuildActionRunner.Result execute(BuildAction action) {
if (completed) {
throw new IllegalStateException("Cannot run more than one action for a build tree.");
}
try {
BuildTreeLifecycleListener broadcaster = services.get(ListenerManager.class).getBroadcaster(BuildTreeLifecycleListener.class);
broadcaster.afterStart();
try {
return services.get(BuildTreeActionExecutor.class).execute(action, this);
} finally {
broadcaster.beforeStop();
}
} finally {
completed = true;
}
}
}
| 17,258
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.