file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
has_loc.rs | ned::Spanned;
use syn::Attribute;
use syn::Data;
use syn::DataEnum;
use syn::DataStruct;
use syn::DeriveInput;
use syn::Error;
use syn::Lit;
use syn::Meta;
use syn::NestedMeta;
use syn::Result;
use syn::Variant;
use crate::simple_type::SimpleType;
use crate::util::InterestingFields;
/// Builds a HasLoc impl.
///
/// ... |
quote!(#field.loc_id())
}
FieldKind::None => todo!(),
FieldKind::Numbered(_) => todo!(),
}
} else {
let field = data
.fields
.iter()
.enumerate()
.map(|(i, field)| (i, field, SimpleType::from_type(&f... | {
// struct Foo {
// ...
// loc: LocId,
// }
let struct_name = &input.ident;
let default_select_field = handle_has_loc_attr(&input.attrs)?;
let loc_field = if let Some(f) = default_select_field {
match f.kind {
FieldKind::Named(name) => {
let name = n... | identifier_body |
reader_test.go | w.WriteHeader(500)
return
}
to = len(data)
if hasPositiveStartOffset && j+1 < len(rh) { // The case of "bytes=N-M"
to, err = strconv.Atoi(rh[j+1:])
if err != nil {
w.WriteHeader(500)
return
}
to++ // Range header is inclusive, Go slice is exclusive
}
if from >= len(data) && to != from ... |
if err != nil {
t.Errorf("#%d: %v", i, err)
continue
}
if got := string(gotb); got != test.want {
t.Errorf("#%d: got %q, want %q", i, got, test.want)
}
if r.Attrs.Size != int64(len(readData)) {
t.Errorf("#%d: got Attrs.Size=%q, want %q", i, r.Attrs.Size, len(readData))
}
wantOffset... | {
n, err := r.Read(buf)
gotb = append(gotb, buf[:n]...)
if err == io.EOF {
break
}
if err != nil {
t.Fatalf("#%d: %v", i, err)
}
} | conditional_block |
reader_test.go |
"google.golang.org/api/option"
)
const readData = "0123456789"
func TestRangeReader(t *testing.T) {
ctx := context.Background()
hc, close := newTestServer(handleRangeRead)
defer close()
multiReaderTest(ctx, t, func(t *testing.T, c *Client) {
obj := c.Bucket("b").Object("o")
for _, test := range []struct {
... | random_line_split | ||
reader_test.go | w.WriteHeader(500)
return
}
to = len(data)
if hasPositiveStartOffset && j+1 < len(rh) { // The case of "bytes=N-M"
to, err = strconv.Atoi(rh[j+1:])
if err != nil {
w.WriteHeader(500)
return
}
to++ // Range header is inclusive, Go slice is exclusive
}
if from >= len(data) && to != from ... |
func (f *fakeReadCloser) Read(buf []byte) (int, error) {
i := f.c
n := 0
if i < len(f.counts) {
n = f.counts[i]
}
var err error
if i >= len(f.counts)-1 {
err = f.err
}
copy(buf, f.data[f.d:f.d+n])
if len(buf) < n {
n = len(buf)
f.counts[i] -= n
err = nil
} else {
f.c++
}
f.d += n
return n, er... | {
return nil
} | identifier_body |
reader_test.go | w.WriteHeader(500)
return
}
to = len(data)
if hasPositiveStartOffset && j+1 < len(rh) { // The case of "bytes=N-M"
to, err = strconv.Atoi(rh[j+1:])
if err != nil {
w.WriteHeader(500)
return
}
to++ // Range header is inclusive, Go slice is exclusive
}
if from >= len(data) && to != fro... | (t *testing.T) {
e := errors.New("")
f := &fakeReadCloser{
data: []byte(readData),
counts: []int{1, 2, 3},
err: e,
}
wants := []string{"0", "12", "345"}
buf := make([]byte, 10)
for i := 0; i < 3 | TestFakeReadCloser | identifier_name |
moment-ext.ts | let ambigDateOfMonthRegex = /^\s*\d{4}-\d\d$/
let ambigTimeOrZoneRegex =
/^\s*\d{4}-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?)?$/
let newMomentProto: any = moment.fn // where we will attach our new methods
let oldMomentProto = $.extend({}, newMomentProto) // copy of original mo... | seconds: 0,
ms: 0
})
// Mark the time as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(),
// which clears all ambig flags.
this._ambigTime = true
this._ambigZone = true // if ambiguous time, also ambiguous timezone offset
}
return this // for ch... | minutes: 0, | random_line_split |
moment-ext.ts | let ambigDateOfMonthRegex = /^\s*\d{4}-\d\d$/
let ambigTimeOrZoneRegex =
/^\s*\d{4}-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?)?$/
let newMomentProto: any = moment.fn // where we will attach our new methods
let oldMomentProto = $.extend({}, newMomentProto) // copy of original mo... | (mom, formatStr?) {
return oldMomentProto.format.call(mom, formatStr) // oldMomentProto defined in moment-ext.js
}
export { newMomentProto, oldMomentProto, oldMomentFormat }
// Creating
// -------------------------------------------------------------------------------------------------
// Creates a new moment, si... | oldMomentFormat | identifier_name |
moment-ext.ts | let ambigDateOfMonthRegex = /^\s*\d{4}-\d\d$/
let ambigTimeOrZoneRegex =
/^\s*\d{4}-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?)?$/
let newMomentProto: any = moment.fn // where we will attach our new methods
let oldMomentProto = $.extend({}, newMomentProto) // copy of original mo... | isAmbigZone = true
} else if ((ambigMatch = ambigTimeOrZoneRegex.exec(input))) {
isAmbigTime = !ambigMatch[5] // no time part?
isAmbigZone = true
}
} else if ($.isArray(input)) {
// arrays have no timezone information, so assume ambiguous zone
isAmbigZone = true
}... | {
let input = args[0]
let isSingleString = args.length === 1 && typeof input === 'string'
let isAmbigTime
let isAmbigZone
let ambigMatch
let mom
if (moment.isMoment(input) || isNativeDate(input) || input === undefined) {
mom = moment.apply(null, args)
} else { // "parsing" is required
isAmbigTi... | identifier_body |
qwe58.py | range(len(x_result)):
xm_result.append(np.mean(pad_result[i:i+plen+1]))
xm_result.reverse()
head = [xm_result[0] for z in range(plen)]
tail = [xm_result[-1] for z in range(plen)]
pad_result= head+xm_result+tail
hx_result=[]
for i in range(len(x_result)):
hx_result.append(np.mean(pad_result[i:i+pl... | for cls_ind, cls in enumerate(CLASSES[1:]):
cls_ind += 1
cls_boxes = boxes[:, 4:8] #boxes[:, 4*cls_ind:4*(cls_ind + 1)]
cls_scores = scores[:, cls_ind]
cls_dets = np.hstack((cls_boxes,cls_scores[:, np.newaxis])).astype(np.float32)
keep = nms(cls_dets, NMS_THRESH)
# add vote
... | random_line_split | |
qwe58.py | #vis_detections_video(im, cls, dets, thresh=CONF_THRESH)
################################
inds = np.where(dets[:, -1] >= CONF_THRESH)[0]
if len(inds) == 0:
continue
#print(inds)
for i in inds:
#area = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])
bb... | inue
| conditional_block | |
qwe58.py | _crop
#print '----debug-----box', boxes[:4, :]
#exit(0)
timer.toc()
print (str(nb)+'Detection took {:.3f}s for ''{:d} object proposals').format(timer.total_time, boxes.shape[0])
CONF_THRESH = 0.80
NMS_THRESH = 0.3
min_y = 0
min_x = 51.0
#Max = 0
#arealist=[]
maxb = [0,0,10,1... | dets_voted = np.zeros_like(dets_NMS) # Empty matrix with the same shape and type
_overlaps = bbox_overlaps(
np.ascontiguousarray(dets_NMS[:, 0:4], dtype=np.float),
np.ascontiguousarray(dets_all[:, 0:4], dtype=np.float))
# for each survived box
for i, det in enumerate(dets_NMS):
dets_... | identifier_body | |
qwe58.py | (x_result,N):
plen=N
head = [x_result[0] for z in range(plen)]
tail = [x_result[-1] for z in range(plen)]
pad_result= head+x_result+tail
xm_result=[]
for i in range(len(x_result)):
xm_result.append(np.mean(pad_result[i:i+plen+1]))
xm_result.reverse()
head = [xm_result[0] for z in range(plen)]
t... | smooth_curve | identifier_name | |
address.go | if alen > 0 {
b[6] = byte(alen)
copy(data[:alen], a.Addr)
data = data[alen:]
}
return ll, nil
}
func parseLinkAddr(b []byte) (Addr, error) {
if len(b) < 8 {
return nil, errInvalidAddr
}
_, a, err := parseKernelLinkAddr(syscall.AF_LINK, b[4:])
if err != nil {
return nil, err
}
a.(*LinkAddr).Index = i... |
func (a *Inet4Addr) marshal(b []byte) (int, error) {
l, ll := a.lenAndSpace()
if len(b) < ll {
return 0, errShortBuffer
}
b[0] = byte(l)
b[1] = syscall.AF_INET
copy(b[4:8], a.IP[:])
return ll, nil
}
// An Inet6Addr represents an internet address for IPv6.
type Inet6Addr struct {
IP [16]byte // IP addre... | {
return sizeofSockaddrInet, roundup(sizeofSockaddrInet)
} | identifier_body |
address.go | }
if alen > 0 {
b[6] = byte(alen)
copy(data[:alen], a.Addr)
data = data[alen:]
}
return ll, nil
}
func parseLinkAddr(b []byte) (Addr, error) {
if len(b) < 8 {
return nil, errInvalidAddr
}
_, a, err := parseKernelLinkAddr(syscall.AF_LINK, b[4:])
if err != nil {
return nil, err
}
a.(*LinkAddr).Index =... | (af int, b []byte) (Addr, error) {
switch af {
case syscall.AF_INET:
if len(b) < sizeofSockaddrInet {
return nil, errInvalidAddr
}
a := &Inet4Addr{}
copy(a.IP[:], b[4:8])
return a, nil
case syscall.AF_INET6:
if len(b) < sizeofSockaddrInet6 {
return nil, errInvalidAddr
}
a := &Inet6Addr{ZoneID: ... | parseInetAddr | identifier_name |
address.go | oneID))
}
return ll, nil
}
// parseInetAddr parses b as an internet address for IPv4 or IPv6.
func parseInetAddr(af int, b []byte) (Addr, error) {
switch af {
case syscall.AF_INET:
if len(b) < sizeofSockaddrInet {
return nil, errInvalidAddr
}
a := &Inet4Addr{}
copy(a.IP[:], b[4:8])
return a, nil
case... | {
return nil, errMessageTooShort
} | conditional_block | |
address.go | .ZoneID))
}
return ll, nil
}
// parseInetAddr parses b as an internet address for IPv4 or IPv6.
func parseInetAddr(af int, b []byte) (Addr, error) {
switch af {
case syscall.AF_INET:
if len(b) < sizeofSockaddrInet {
return nil, errInvalidAddr
}
a := &Inet4Addr{}
copy(a.IP[:], b[4:8])
return a, nil
ca... | if len(b) < l {
return nil, errMessageTooShort
} | random_line_split | |
main.rs | );
match font.render(text).solid(color) {
Ok(surface) => {
match texture_creator.create_texture_from_surface(surface) {
Ok(t) => {
t
}
Err(e) => |
}
}
Err(e) => {
panic!("{}", e);
}
}
}
fn obtain_result<T, E: std::fmt::Display>(res: Result<T, E>) -> T {
match res {
Ok(r) => {
r
}
Err(e) => {
panic!("{}", e);
}
}
}
fn draw_centered_text(canvas: &mut Canvas<Window>, texture: &Texture, y_offset: i32) {
//Draw the title
let dst = {
... | {
panic!("{}", e);
} | conditional_block |
main.rs |
fn obtain_result<T, E: std::fmt::Display>(res: Result<T, E>) -> T {
match res {
Ok(r) => {
r
}
Err(e) => {
panic!("{}", e);
}
}
}
fn draw_centered_text(canvas: &mut Canvas<Window>, texture: &Texture, y_offset: i32) {
//Draw the title
let dst = {
let query = texture.query();
let xpos = (SCREEN_W... | {
let color = Color::RGB(0, 255, 0);
match font.render(text).solid(color) {
Ok(surface) => {
match texture_creator.create_texture_from_surface(surface) {
Ok(t) => {
t
}
Err(e) => {
panic!("{}", e);
}
}
}
Err(e) => {
panic!("{}", e);
}
}
} | identifier_body | |
main.rs | );
match font.render(text).solid(color) {
Ok(surface) => {
match texture_creator.create_texture_from_surface(surface) {
Ok(t) => {
t
}
Err(e) => {
panic!("{}", e);
}
}
}
Err(e) => {
panic!("{}", e);
}
}
}
fn obtain_result<T, E: std::fmt::Display>(res: Result<T, E>) -> T {
... | if !going_to_next_round {
//Start the timer
round_transition_timer = ticks;
//Increment round number
game_state.round_number += 1;
//Create round # texture
round_number_texture = text_texture(&format!("Round {}", game_state.round_number), &texture_creator, &font);
going... | random_line_split | |
main.rs | );
match font.render(text).solid(color) {
Ok(surface) => {
match texture_creator.create_texture_from_surface(surface) {
Ok(t) => {
t
}
Err(e) => {
panic!("{}", e);
}
}
}
Err(e) => {
panic!("{}", e);
}
}
}
fn obtain_result<T, E: std::fmt::Display>(res: Result<T, E>) -> T {
... | <T: std::cmp::PartialOrd>(value: T, lower_bound: T, upper_bound: T) -> T{
let mut clamped_value = value;
if clamped_value < lower_bound {
clamped_value = lower_bound;
}
if clamped_value > upper_bound {
clamped_value = upper_bound;
}
clamped_value
}
fn main() {
let sdl_context = sdl2::init().unwrap();
let v... | clamp | identifier_name |
bind.go |
import (
"reflect"
"github.com/apache/beam/sdks/v2/go/pkg/beam/core/funcx"
"github.com/apache/beam/sdks/v2/go/pkg/beam/core/typex"
"github.com/apache/beam/sdks/v2/go/pkg/beam/internal/errors"
)
// TODO(herohde) 4/21/2017: Bind is where most user mistakes will likely show
// up. We should verify that common mista... | // See the License for the specific language governing permissions and
// limitations under the License.
package graph | random_line_split | |
bind.go | 0]), typex.New(ret[1])))
default:
return nil, errors.Errorf("too many return values: %v", ret)
}
for _, param := range params {
values, _ := funcx.UnfoldEmit(param.T)
trimmed := trimIllegal(values)
if len(trimmed) == 2 {
outbound = append(outbound, typex.NewKV(typex.New(trimmed[0]), typex.New(trimmed[1])... | {
switch t.Type() {
case typex.KVType:
if isMain {
return 2, nil
}
// A KV side input must be a single iterator/map.
return 1, nil
case typex.CoGBKType:
return len(t.Components()), nil
default:
return 0, errors.Errorf("unexpected composite inbound type: %v", t.Type())
}
} | conditional_block | |
bind.go | ex.X, v int, emit func(string, typex.X))
//
// or
//
// func (context.Context, k typex.X, v int) (string, typex.X, error)
//
// are UserFns that may take one or two incoming fulltypes: either KV<X,int>
// or X with a singleton side input of type int. For the purpose of the
// shape of data processing, the two forms are... | (fn *funcx.Fn, typedefs map[string]reflect.Type, in ...typex.FullType) ([]typex.FullType, []InputKind, []typex.FullType, []typex.FullType, error) {
addContext := func(err error, fn *funcx.Fn) error {
return errors.WithContextf(err, "binding fn %v", fn.Fn.Name())
}
inbound, kinds, err := findInbound(fn, in...)
if... | Bind | identifier_name |
bind.go | ex.X, v int, emit func(string, typex.X))
//
// or
//
// func (context.Context, k typex.X, v int) (string, typex.X, error)
//
// are UserFns that may take one or two incoming fulltypes: either KV<X,int>
// or X with a singleton side input of type int. For the purpose of the
// shape of data processing, the two forms are... | elm, kind, err := tryBindInbound(input, paramsToBind, index == 0)
if err != nil {
return nil, nil, addContext(err, paramsToBind, input)
}
inbound = append(inbound, elm)
kinds = append(kinds, kind)
index += arity
}
if index < len(params) {
return nil, nil, addContext(errors.New("too few inputs: forgot... | {
// log.Printf("Bind inbound: %v %v", fn, in)
addContext := func(err error, p []funcx.FnParam, in any) error {
return errors.WithContextf(err, "binding params %v to input %v", p, in)
}
var inbound []typex.FullType
var kinds []InputKind
params := funcx.SubParams(fn.Param, fn.Params(funcx.FnValue|funcx.FnIter|f... | identifier_body |
helper.go | "
// }
// }
// //既不是IPv4,也不是IPv6,则是错误的
// }else{
// actionResultItem["ipAddr"] = "IP_IS_NOT_V4_OR_V6"
// }
//
// //存储操作结果
// actionResult = append(actionResult,actionResultItem)
//
// //存储查找过的结果
// ipsMap[ipStr] = actionResultItem
// }
//
// return actionResult
//}
// IsNumeric is_numeric()
// Numeric st... | identifier_name | ||
helper.go | dic = strings.Split(dicStr, ",")
}
length := len(dic)
for i := 0; i < randStrLength; i++ {
rand.Seed(time.Now().UnixNano())
randNum := rand.Intn(length - 1)
key += dic[randNum]
}
return key
}
//http响应json-成功数据
//@params string message 响应消息
//@params interface{} data 响应数据,一般也是map数据类型
func (thisObj *helper)... | } else {
dicStr := "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z" | random_line_split | |
helper.go | NewHelper() *helper {
return &helper{
}
}
//获取当前时间戳-int类型数据
func (thisObj *helper) CurrTimeInt() int {
return int(time.Now().Unix())
}
//json解析
//@params interface{} t 基本上传参都是map数据类型,如map[string]interface{}或是map[string]string
func (thisObj *helper) JSONMarshal(t interface{}) ([]byte, error) {
buffer := &bytes.B... | per = NewHelper()
}
func | identifier_body | |
helper.go | //解析成json输出
res := []byte(result.JsonSeqUnicode())
if len(res) > 4*1024 {
//xxx.Http.WriteGzip(res)
} else {
//xxx.Http.Write(res)
}
}
//http响应json
//@params map[string]interface{} data 响应数据
func (thisObj *helper) HttpResponseJSON(data map[string]interface{}) {
//xxx.Http.SetHeader("Content-Type", "applicatio... | p的代码:
// // 有可能传递过来的是ip2long转换的整型ip值 转换成ip字符串
// // $ipStr = is_numeric($ip) ? long2ip($ip) : $ip;
// ipStr := ""
// //若是整型值
// if thisObj.IsNumeric(ip) {
// //转成字符串
// ipInt,ipIntErr := strconv.Atoi(ip)
// //若转换出错
// if ipIntErr!=nil {
// actionResultItem["ipAddr"] = "IP_TO_INT_ERROR"
// actionResul... | -------
// //模拟ph | conditional_block |
q19.rs | };
use differential_dataflow::operators::arrange::ArrangeBySelf;
use timely::dataflow::operators::{Probe, Map, Delay};
use std::time::Instant;
use std::cmp::{min, max};
pub fn | (path: String, change_path: String, params: &Vec<String>) {
// unpack parameters
let param_city1 = params[0].parse::<u64>().unwrap();
let param_city2 = params[1].parse::<u64>().unwrap();
timely::execute_from_args(std::env::args(), move |worker| {
let mut timer = worker.timer();
let inde... | run | identifier_name |
q19.rs | };
use differential_dataflow::operators::arrange::ArrangeBySelf;
use timely::dataflow::operators::{Probe, Map, Delay};
use std::time::Instant;
use std::cmp::{min, max};
pub fn run(path: String, change_path: String, params: &Vec<String>) | worker.dataflow::<usize,_,_>(|scope| {
let (located_in_input, locatedin) = scope.new_collection::<DynamicConnection, _>();
let (knows_input, knows) = scope.new_collection::<DynamicConnection, _>();
// creators for comments AND posts
let (has_creator_input, has_cr... | {
// unpack parameters
let param_city1 = params[0].parse::<u64>().unwrap();
let param_city2 = params[1].parse::<u64>().unwrap();
timely::execute_from_args(std::env::args(), move |worker| {
let mut timer = worker.timer();
let index = worker.index();
let peers = worker.peers();
... | identifier_body |
q19.rs | _trace};
use differential_dataflow::operators::arrange::ArrangeBySelf;
use timely::dataflow::operators::{Probe, Map, Delay};
use std::time::Instant;
use std::cmp::{min, max};
pub fn run(path: String, change_path: String, params: &Vec<String>) {
// unpack parameters
let param_city1 = params[0].parse::<u64>().un... | &knows.map(|conn| (conn.a().clone(), conn.b().clone()))
)
;
// calculate weights starting from personB
let weights = bi_knows
.join_map( // join messages of personB
&has_creator.map(|conn| (conn.b().clone(),... | random_line_split | |
train_full_random.py | run
#num_examples = int(raw_input('Number of images to train: ')) #len(training)
#plot some diagnostics at the end
plot = True
# A way to use a synapse to store LFP, useful when you don't want to
# trace the voltages of all AL neurons.
lfp_syn = True
#-----------------------------------------------------------
#Tuna... | #probability inter-AL connections
#0.5
PAL = 0.5
#AL->KCs
#0.01
PALKC = 0.02
#KCs->BLs
#0.3
PKCBL = 0.3
taupre = 15*ms #width of STDP
taupost = taupre
input_intensity = 0.3 #scale input
reset_time = 30 #ms
# needed for gradual current
tr = 20*ms # rise time
tf = 20*ms # fall time
width = 150*ms # duration of const... | random_line_split | |
train_full_random.py |
# Parallelize using OpenMP. Might not work....
# also only works with C++ standalone/comp = True
# prefs.devices.cpp_standalone.openmp_threads = 4
start_scope()
#path to the data folder
MNIST_data_path = 'data_set/'
# MNIST_data_path = '/home/jplatt/Mothnet/MNIST_data/'
#path to folder to save data
prefix = 'total... | set_device('cpp_standalone', debug=True, build_on_run=False) | conditional_block | |
conf_utils.py | utilities."""
from __future__ import print_function
import json
import logging
import fileinput
import os
import subprocess
import pkg_resources
from six.moves import configparser
import yaml
from functest.utils import config
from functest.utils import env
from functest.utils import functest_utils
RALLY_CONF_PAT... |
with open(conf_file, 'wb') as config_file:
rconfig.write(config_file)
def configure_tempest_update_params(
tempest_conf_file, image_id=None, flavor_id=None,
compute_cnt=1, image_alt_id=None, flavor_alt_id=None,
admin_role_name='admin', cidr='192.168.120.0/24',
domain_id='... | sections = rconfig.sections()
for section in conf_yaml:
if section not in sections:
rconfig.add_section(section)
sub_conf = conf_yaml.get(section)
for key, value in sub_conf.items():
rconfig.set(section, key, value) | conditional_block |
conf_utils.py | utilities."""
from __future__ import print_function
import json
import logging
import fileinput
import os
import subprocess
import pkg_resources
from six.moves import configparser
import yaml
from functest.utils import config
from functest.utils import env
from functest.utils import functest_utils
RALLY_CONF_PAT... | Returns deployment id for active Rally deployment
"""
cmd = ("rally deployment list | awk '/" +
getattr(config.CONF, 'rally_deployment_name') +
"/ {print $2}'")
proc = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
... | def get_verifier_deployment_id():
""" | random_line_split |
conf_utils.py | utilities."""
from __future__ import print_function
import json
import logging
import fileinput
import os
import subprocess
import pkg_resources
from six.moves import configparser
import yaml
from functest.utils import config
from functest.utils import env
from functest.utils import functest_utils
RALLY_CONF_PAT... | str(getattr(config.CONF, 'rally_deployment_name'))]
output = subprocess.check_output(cmd)
LOGGER.info("%s\n%s", " ".join(cmd), output)
except subprocess.CalledProcessError:
pass
cmd = ['rally', 'deployment', 'create', '--fromenv',
'--name', str(getattr(config.C... | """Create new rally deployment"""
# set the architecture to default
pod_arch = env.get("POD_ARCH")
arch_filter = ['aarch64']
if pod_arch and pod_arch in arch_filter:
LOGGER.info("Apply aarch64 specific to rally config...")
with open(RALLY_AARCH64_PATCH_PATH, "r") as pfile:
r... | identifier_body |
conf_utils.py | utilities."""
from __future__ import print_function
import json
import logging
import fileinput
import os
import subprocess
import pkg_resources
from six.moves import configparser
import yaml
from functest.utils import config
from functest.utils import env
from functest.utils import functest_utils
RALLY_CONF_PAT... | (
tempest_conf_file, image_id=None, flavor_id=None,
compute_cnt=1, image_alt_id=None, flavor_alt_id=None,
admin_role_name='admin', cidr='192.168.120.0/24',
domain_id='default'):
# pylint: disable=too-many-branches,too-many-arguments,too-many-statements
"""
Add/update needed p... | configure_tempest_update_params | identifier_name |
navfunc.py | 467e-5;
wie_e = np.asarray([0,0,wie]).reshape((3,1));
earth_f = (earth_a-earth_b)/earth_a;
earth_e = sqrt(earth_f*(2.0-earth_f));
earth_e2 = (earth_e**2.0);
def __init__(self):
pass
def Rlambda(self, lat_rad):
"""
: parameter : lat_rad [rad] latitude
: outp... |
output: nparray() with Q
"""
return self.euler2Q(self.C2euler(C))
def C2euler(self, C):
"""
Navigation -- from C to (phi,theta,psi)[rad]
output: tuple with angles in [rad]
"""
assert(C[2,2] != 0)
assert(C[0,0] != 0)
assert(C[0,2]>=... | """
Navigation -- from C to Q | random_line_split |
navfunc.py | np.asarray([0,0,wie]).reshape((3,1));
earth_f = (earth_a-earth_b)/earth_a;
earth_e = sqrt(earth_f*(2.0-earth_f));
earth_e2 = (earth_e**2.0);
def __init__(self):
pass
def Rlambda(self, lat_rad):
"""
: parameter : lat_rad [rad] latitude
: output : R_lbd
... | """
Converter coordenadas ECEF geodeticas para retangulares.
pgeo [in] Coordenadas geodeticas.
prect [out] Coordenadas retangulares.
"""
s = sin(geo.lat);
RN = self.earth_a / sqrt(1.0 - (self.earth_e2 * s * s));
return CRECT((
(RN + geo.h) * cos(geo... | identifier_body | |
navfunc.py | (self):
K = 180./mt.pi;
return "<CGEO: lat=%1.2f[deg] lon=%1.2f[deg] h=%1.1f[m]>" % (self.lat*K, self.lon*K, self.h)
class CRECT:
def __init__(self, r_e):
if type(r_e) is np.ndarray:
self.x = r_e.squeeze()[0];
self.y = r_e.squeeze()[1];
self.z = r_e.squ... | __repr__ | identifier_name | |
navfunc.py |
else:
print "ainda nao suportado!"
def __repr__(self):
K = 180./mt.pi;
return "<CRECT: x=%1.2f[m] y=%1.2f[m] z=%1.2f[m]>" % (self.x, self.y, self.z)
def aslist(self):
return [
self.x,
self.y,
self.z
];
#>>--<<..>>--<<.... | self.x = r_e[0]
self.y = r_e[1]
self.z = r_e[2] | conditional_block | |
cluster_save_all_model_flam.py |
# Save a txt file
data = np.array(zip(zrange, dl_mpc, dl_cm), dtype=[('zrange', float), ('dl_mpc', float), ('dl_cm', float)])
np.savetxt('dl_lookup_table.txt', data, fmt=['%.3f', '%.6e', '%.6e'], delimiter=' ', header='z dl_mpc dl_cm')
print "Luminosity distance lookup table saved in txt file.",
... | random_line_split | ||
cluster_save_all_model_flam.py | _lookup_table.txt', data, fmt=['%.3f', '%.6e', '%.6e'], delimiter=' ', header='z dl_mpc dl_cm')
print "Luminosity distance lookup table saved in txt file.",
print "In same folder as this code."
return None
def compute_filter_flam(filt, filtername, start, model_comp_spec, model_lam_grid, \
total_mo... |
# transverse array to make shape consistent with others
# I did it this way so that in the above for loop each filter is looped over only once
# i.e. minimizing the number of times each filter is gridded on to the model grid
#filt_flam_model_t = filt_flam_model.T
# save the mo... | num = simps(y=model_comp_spec[i] * filt_interp / (4 * np.pi * dl * dl * (1+z)), x=model_lam_grid_z)
filt_flam_model[j, i] = num / den | conditional_block |
cluster_save_all_model_flam.py | _lookup_table.txt', data, fmt=['%.3f', '%.6e', '%.6e'], delimiter=' ', header='z dl_mpc dl_cm')
print "Luminosity distance lookup table saved in txt file.",
print "In same folder as this code."
return None
def compute_filter_flam(filt, filtername, start, model_comp_spec, model_lam_grid, \
total_mo... | #print "At z:", z
# ------------------------------ Now compute model filter magnitudes ------------------------------ #
# Redshift the base models
dl = dl_tbl['dl_cm'][j] # has to be in cm
#print "Lum dist [cm]:", dl
#model_comp_spec_z = model_comp_spec / (4 * np.p... | print "\n", "Working on filter:", filtername
if filtername == 'u':
filt['trans'] /= 100.0 # They've given throughput percentages for the u-band
filt_flam_model = np.zeros(shape=(len(zrange), total_models), dtype=np.float64)
"""
print model_comp_spec.nbytes / (1024 * 1024)
print model... | identifier_body |
cluster_save_all_model_flam.py | _table.txt', data, fmt=['%.3f', '%.6e', '%.6e'], delimiter=' ', header='z dl_mpc dl_cm')
print "Luminosity distance lookup table saved in txt file.",
print "In same folder as this code."
return None
def | (filt, filtername, start, model_comp_spec, model_lam_grid, \
total_models, zrange, dl_tbl):
print "\n", "Working on filter:", filtername
if filtername == 'u':
filt['trans'] /= 100.0 # They've given throughput percentages for the u-band
filt_flam_model = np.zeros(shape=(len(zrange), total_mod... | compute_filter_flam | identifier_name |
lib.rs | aining edge device provisioning data...");
match settings.auto_reprovisioning_mode() {
AutoReprovisioningMode::AlwaysOnStartup => {
tokio_runtime.block_on(reprovision_device(&client))?
}
AutoReprovisioningMode::Dynamic | AutoReprovisioning... | {
let iot_hub_name = workload_config.iot_hub_name().to_string();
let device_id = workload_config.device_id().to_string();
let (mgmt_tx, mgmt_rx) = oneshot::channel();
let (mgmt_stop_and_reprovision_tx, mgmt_stop_and_reprovision_rx) = mpsc::unbounded();
let mgmt = start_management::<M>(settings, ru... | identifier_body | |
lib.rs | is used for getting notifications from the mgmt service
// indicating that the daemon should shut down and attempt to reprovision the device.
let mgmt_stop_and_reprovision_signaled =
mgmt_stop_and_reprovision_rx
.into_future()
.then(|res| match res {
Ok((Some(())... | Error | identifier_name | |
lib.rs | _SERVER_CERT_MAX_DURATION_SECS: i64 = 90 * 24 * 3600;
const STOP_TIME: Duration = Duration::from_secs(30);
/// This is the interval at which to poll Identity Service for device information.
const IS_GET_DEVICE_INFO_RETRY_INTERVAL_SECS: Duration = Duration::from_secs(5);
#[derive(Clone, serde::Serialize, serde::Deser... | // Normally aziot-edged will stop all modules when it shuts down. But if it crashed,
// modules will continue to run. On Linux systems where aziot-edged is responsible for
// creating/binding the socket (e.g., CentOS 7.5, which uses systemd but does not
// support systemd socket activati... | };
};
info!("Finished provisioning edge device.");
| random_line_split |
util.go | lowFalse <<= 1
}
if highTrue == 0 {
return 0, fmt.Errorf("cannot find high enough value to make pred(value)==true")
}
for highTrue-lowFalse > 1 {
mid := (lowFalse + highTrue) / 2
mm, err := pred(mid)
if err != nil {
return 0, err
}
if mm {
highTrue = mid
} else {
lowFalse = mid
}
}
ret... | {
lf, err := pred(lowFalseStart)
if err != nil {
return 0, err
}
if lf {
return 0, fmt.Errorf("lowestTrue expected pred(lowFalseStart)==false; got pred(%d)==true", lowFalseStart)
}
lowFalse := lowFalseStart
highTrue := 0
for lowFalse < MaxInt/2 {
attempt := lowFalse * 2
st, err := pred(attempt)
if err... | identifier_body | |
util.go | func(int) (bool, error)) (int, error) {
if lowTrue >= highFalse {
return 0, fmt.Errorf("highestTrue(%d,%d, pred): want arg1 < arg2", lowTrue, highFalse)
}
lt, err := pred(lowTrue)
if err != nil {
return 0, err
}
if !lt {
return 0, fmt.Errorf("highestTrue(%d,%d, pred): pred(%d)==false", lowTrue, highFalse, ... |
if chunk != nil {
result = append(result, chunk)
}
return result
}
// KeyValuePairs splits a space-separated sequence of colon-separated key:value
// pairs into a map.
func KeyValuePairs(input string) map[string]string {
result := make(map[string]string)
parts := strings.Split(input, " ")
for _, part := range... | {
if line == "" {
if chunk != nil {
result = append(result, chunk)
chunk = nil
}
} else {
chunk = append(chunk, line)
}
} | conditional_block |
util.go | }
lowFalse := lowFalseStart
highTrue := 0
for lowFalse < MaxInt/2 {
attempt := lowFalse * 2
st, err := pred(attempt)
if err != nil {
return 0, err
}
if st {
highTrue = attempt
break
}
lowFalse <<= 1
}
if highTrue == 0 {
return 0, fmt.Errorf("cannot find high enough value to make pred(valu... | if lf {
return 0, fmt.Errorf("lowestTrue expected pred(lowFalseStart)==false; got pred(%d)==true", lowFalseStart) | random_line_split | |
util.go | pred func(int) (bool, error)) (int, error) {
if lowTrue >= highFalse {
return 0, fmt.Errorf("highestTrue(%d,%d, pred): want arg1 < arg2", lowTrue, highFalse)
}
lt, err := pred(lowTrue)
if err != nil {
return 0, err
}
if !lt {
return 0, fmt.Errorf("highestTrue(%d,%d, pred): pred(%d)==false", lowTrue, highFa... | (lines []string) [][]string {
var result [][]string
var chunk []string
for _, line := range lines {
if line == "" {
if chunk != nil {
result = append(result, chunk)
chunk = nil
}
} else {
chunk = append(chunk, line)
}
}
if chunk != nil {
result = append(result, chunk)
}
return result
}
... | LinesByParagraph | identifier_name |
FilterListViewModel.ts | false;
@property()
extentSelectorConfig: ExtentSelector;
@property()
output: FilterOutput;
// ----------------------------------
//
// Private Variables
//
// ----------------------------------
private _layers: FilterLayers = {};
private _timeout: NodeJS.Timeout;
// ----------------------... | const query = layer.createQuery();
query.where = layer.definitionExpression ? layer.definitionExpression : "1=1";
if (layer?.capabilities?.query?.supportsCacheHint) {
query.cacheHint = true;
}
if (field) {
query.outFields = [field];
query.returnDistinctValues = true... | }
async calculateStatistics(layerId: string, field: string): Promise<__esri.Graphic[]> {
const layer = this.map.layers.find(({ id }) => id === layerId) as __esri.FeatureLayer;
if (layer && layer.type === "feature") { | random_line_split |
FilterListViewModel.ts | false;
@property()
extentSelectorConfig: ExtentSelector;
@property()
output: FilterOutput;
// ----------------------------------
//
// Private Variables
//
// ----------------------------------
private _layers: FilterLayers = {};
private _timeout: NodeJS.Timeout;
// ----------------------... | handleResetDatePicker(expression: Expression, layerId: string, event: Event): void {
const datePicker = document.getElementById(expression.id.toString()) as HTMLCalciteInputDatePickerElement;
datePicker.start = null;
datePicker.startAsDate = null;
datePicker.end = null;
datePicker.endAsDate = null... | setTimeout(() => {
const datePicker = event.target as HTMLCalciteInputDatePickerElement;
this.setExpressionDates(datePicker.startAsDate, datePicker.endAsDate, expression, layerId);
}, 1000);
}
| identifier_body |
FilterListViewModel.ts | false;
@property()
extentSelectorConfig: ExtentSelector;
@property()
output: FilterOutput;
// ----------------------------------
//
// Private Variables
//
// ----------------------------------
private _layers: FilterLayers = {};
private _timeout: NodeJS.Timeout;
// ----------------------... | this._generateOutput(layerId);
}
handleNumberInputCreate(
expression: Expression,
layerId: string,
type: "min" | "max",
input: HTMLCalciteInputElement
): void {
input.addEventListener("calciteInputInput", this.handleNumberInput.bind(this, expression, layerId, type));
}
handleNumberInp... | delete this._layers[layerId].expressions[expression.id];
}
| conditional_block |
FilterListViewModel.ts | ;
@property()
extentSelectorConfig: ExtentSelector;
@property()
output: FilterOutput;
// ----------------------------------
//
// Private Variables
//
// ----------------------------------
private _layers: FilterLayers = {};
private _timeout: NodeJS.Timeout;
// ----------------------------... | : void {
this.layerExpressions?.map((layerExpression) => {
let tmpExp = {};
const { id } = layerExpression;
layerExpression.expressions.map((expression) => {
if (!expression.checked) {
expression.checked = false;
} else {
tmpExp = {
[expression.id]: ... | itExpressions() | identifier_name |
a3c_v10_cnn_lstm.py | R = GAMMA * R + agent.rewards[i]
advantage = R - agent.values[i]
value_loss = value_loss + 0.5 * advantage.pow(2)
deltaT = agent.rewards[i] + GAMMA * agent.values[i + 1].data - agent.values[i].data
gae = gae * GAMMA * LAMBDA + deltaT # generalized advantage estimator
actor_loss... | torch.nn.init.xavier_uniform_(self.encoder2.weight)
torch.nn.init.xavier_uniform_(self.encoder3.weight)
torch.nn.init.xavier_uniform_(self.critic_linear.weight)
# torch.nn.init.xavier_uniform_(self.actor_linear.weight)
def forward(self, x, raw, hx, cx):
timesteps, batch_size... | torch.nn.init.xavier_uniform_(self.encoder1.weight) | random_line_split |
a3c_v10_cnn_lstm.py |
def ensure_shared_grads(lnet, gnet):
for param, shared_param in zip(lnet.parameters(), gnet.parameters()):
if shared_param.grad is not None:
return
shared_param._grad = param.grad
def update_glob_net(opt, lnet, gnet, agent, GAMMA):
R = 0
actor_loss = 0
value_loss = 0
... | """Stops all agents"""
return [agent.shutdown() for agent in agents] | identifier_body | |
a3c_v10_cnn_lstm.py |
shared_param._grad = param.grad
def update_glob_net(opt, lnet, gnet, agent, GAMMA):
R = 0
actor_loss = 0
value_loss = 0
gae = 0
agent.values.append(torch.zeros(1)) # we need to add this for the deltaT equation(below)
# print(agent.rewards)
for i in reversed(range(len(agent.rewar... | return | conditional_block | |
a3c_v10_cnn_lstm.py | += 0.05
# reward stage2: teach agent to not stand on or beside bombs
# reward /= 4
# bomb_life = state[agent_nr]['bomb_life']
# if we stand on a bomb or next to bomb
# just_placed_bomb = np.logical_xor(last_action==5,action==5)
# if bomb_life[position]>0 and not(just_placed_bomb):
# rew... | reset_lstm | identifier_name | |
LCOGT_submit_requests.py | _duration_error: in minutes, is the maximum allowable difference between
the start & end times of the request, and the _billed duration_ of the
request. By design in the API, the billed duration is always shorter than
the (end-start) time. I allotted 1 hour on either side for scheduling, so a
bit of sla... | while is_modified:
if n_iter >= 10:
raise AssertionError('too many iterations')
requestgroup, is_modified = (
validate_single_request(
requestgroup,
max... | conditional_block | |
LCOGT_submit_requests.py | raise_error=True):
"""
Submit the RequestGroup through the "validate" API, cf.
https://developers.lco.global/#validate-a-requestgroup
max_duration_error: in minutes, is the maximum allowable difference between
the start & end times of the request, and the _billed duratio... |
def submit_single_request(requestgroup):
# Submit the fully formed RequestGroup
response = requests.post(
'https://observe.lco.global/api/requestgroups/',
headers={'Authorization': 'Token {}'.format(token)},
json=requestgroup
)
# Make sure the API call was successful
try:
... | format(window_durn/60, billed_durn/60, expcount))
print(42*'-')
return requestgroup, is_modified
| random_line_split |
LCOGT_submit_requests.py | (requestgroup, max_duration_error=15,
raise_error=True):
"""
Submit the RequestGroup through the "validate" API, cf.
https://developers.lco.global/#validate-a-requestgroup
max_duration_error: in minutes, is the maximum allowable difference between
the start & end times o... | validate_single_request | identifier_name | |
LCOGT_submit_requests.py | raise_error=True):
"""
Submit the RequestGroup through the "validate" API, cf.
https://developers.lco.global/#validate-a-requestgroup
max_duration_error: in minutes, is the maximum allowable difference between
the start & end times of the request, and the _billed duratio... | )
else:
resultsdir = (
os.path.join(RESULTSDIR,'LCOGT_{}_updated_requests/'.format(semesterstr))
)
pkl_savpath = (
os.path.join(resultsdir, '{}.pkl'.format(savstr))
)
mult_savpath = (
os.path.join(resultsdir, '{}_summary.csv'.format(savstr))
)
... | """
savstr: used for directory management
validate_all: if true, first validates observation requests to ensure that
they can be submitted
submit_all: actually submits them
max_N_transit_per_object:
max_duration_error: in minutes, maximum acceptable difference between
_desired_ observati... | identifier_body |
base_plugin.go | TypeTransformation = "HTTP-Functions"
pluginStage = plugins.PostInAuth
)
type GetTransformationFunction func(destination *v1.Destination_Function) (*TransformationTemplate, error)
type Plugin interface {
ActivateFilterForCluster(out *envoyapi.Cluster)
AddRequestTransformationsToRoute(getTemplate GetT... | (getTemplate GetTransformationFunction, in *v1.Route, extractors map[string]*Extraction, out *envoyroute.Route) error {
switch {
case in.MultipleDestinations != nil:
for _, dest := range in.MultipleDestinations {
err := p.setTransformationForRoute(getTemplate, dest.Destination, extractors, out)
if err != nil ... | setTransformationsForRoute | identifier_name |
base_plugin.go | ServiceTypeTransformation = "HTTP-Functions"
pluginStage = plugins.PostInAuth
)
type GetTransformationFunction func(destination *v1.Destination_Function) (*TransformationTemplate, error)
type Plugin interface {
ActivateFilterForCluster(out *envoyapi.Cluster)
AddRequestTransformationsToRoute(getTempl... | if err != nil {
return err
}
hash := fmt.Sprintf("%v", intHash)
// cache the transformation, the filter config needs to contain all of them
p.cachedTransformations[hash] = &t
// set the filter metadata on the route
if out.Metadata == nil {
out.Metadata = &envoycore.Metadata{}
}
filterMetadata := common.... | random_line_split | |
base_plugin.go | TypeTransformation = "HTTP-Functions"
pluginStage = plugins.PostInAuth
)
type GetTransformationFunction func(destination *v1.Destination_Function) (*TransformationTemplate, error)
type Plugin interface {
ActivateFilterForCluster(out *envoyapi.Cluster)
AddRequestTransformationsToRoute(getTemplate GetT... |
}
return extractors, nil
}
// TODO: clean up the response transformation
// params should live on the source (upstream/function)
func (p *transformationPlugin) AddResponseTransformationsToRoute(in *v1.Route, out *envoyroute.Route) error {
if in.Extensions == nil {
return nil
}
extension, err := DecodeRouteExt... | {
return nil, errors.Wrap(err, "error processing parameter")
} | conditional_block |
base_plugin.go | TypeTransformation = "HTTP-Functions"
pluginStage = plugins.PostInAuth
)
type GetTransformationFunction func(destination *v1.Destination_Function) (*TransformationTemplate, error)
type Plugin interface {
ActivateFilterForCluster(out *envoyapi.Cluster)
AddRequestTransformationsToRoute(getTemplate GetT... |
// sets all transformations a route may need
// if single destination, just one transformation
// if multi destination, one transformation for each functional
// that specifies a transformation spec
func (p *transformationPlugin) setTransformationsForRoute(getTemplate GetTransformationFunction, in *v1.Route, extracto... | {
var regexString string
var prevEnd int
for _, startStop := range rxp.FindAllStringIndex(paramString, -1) {
start := startStop[0]
end := startStop[1]
subStr := regexp.QuoteMeta(paramString[prevEnd:start]) + `([\-._[:alnum:]]+)`
regexString += subStr
prevEnd = end
}
return regexString + regexp.QuoteMeta... | identifier_body |
tasks.py | DBCopyrightInfoService, ANNArtistInfoService, \
GoogleKGSArtistInfoService, MALCopyrightInfoService, BangumiCopyrightInfoService, GoogleKGSCopyrightInfoService
from bot.services.media_service import MediaService
from bot.services.sakugabooru_service import SakugabooruService
from bot.services.weiboV2_service import... |
ja_names.extend(self.get_values_from_info('name_ja'))
if not ja_names:
ja_names = [self.tag.name.replace("_", " ")]
self._get_and_save_info(AtwikiInfoService, *ja_names)
if self.tag.type == Tag.COPYRIGHT:
self._get_and_save_info(ASDBCopyrightInfoService, *ja_name... | ja_names.append(self.tag.ja_name) | conditional_block |
tasks.py | DBCopyrightInfoService, ANNArtistInfoService, \
GoogleKGSArtistInfoService, MALCopyrightInfoService, BangumiCopyrightInfoService, GoogleKGSCopyrightInfoService
from bot.services.media_service import MediaService
from bot.services.sakugabooru_service import SakugabooruService
from bot.services.weiboV2_service import... |
def _save_info_to_tag(self):
for k, v in self.info.items():
if v:
try:
logger.info("Info [{}: {}] is being added "
"to Tag[{}]. Overwrite: {}".format(k,
v,
... | assert isinstance(tag, Tag)
self.tag = tag
self.overwrite = overwrite
self.info = dict() | identifier_body |
tasks.py | ASDBCopyrightInfoService, ANNArtistInfoService, \
GoogleKGSArtistInfoService, MALCopyrightInfoService, BangumiCopyrightInfoService, GoogleKGSCopyrightInfoService
from bot.services.media_service import MediaService
from bot.services.sakugabooru_service import SakugabooruService
from bot.services.weiboV2_service imp... | self.info.setdefault(k, v)
def get_values_from_info(self, *keys):
return [self.info.get(key, None) for key in keys if self.info.get(key, None)]
def translate_artist(self):
if self.tag.type != Tag.ARTIST:
return
name = self.tag.name.replace("_", " ")
self... | for k, v in info.items():
if k in overwrite_keys:
self.info[k] = v
continue | random_line_split |
tasks.py | DBCopyrightInfoService, ANNArtistInfoService, \
GoogleKGSArtistInfoService, MALCopyrightInfoService, BangumiCopyrightInfoService, GoogleKGSCopyrightInfoService
from bot.services.media_service import MediaService
from bot.services.sakugabooru_service import SakugabooruService
from bot.services.weiboV2_service import... | (self):
if self.tag.type != Tag.COPYRIGHT:
return
name = self.tag.name.replace("_", " ")
self._get_and_save_info(MALCopyrightInfoService, name)
names = [name] + self.get_values_from_info('name_ja')
self._get_and_save_info(BangumiCopyrightInfoService,
... | translate_copyright | identifier_name |
day04.rs | the number must be at least `59` and at most `76`.
let hgt_str = kvs.get("hgt").unwrap();
let hgt = if hgt_str.ends_with("cm") {
let high = hgt_str.strip_suffix("cm").unwrap().parse::<usize>();
match high {
Ok(i @ 150..=193) => Height {
hight:... | random_line_split | ||
day04.rs | hzl
//! eyr:2022
//!
//! iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719
//! ```
//!
//! Count the number of **valid** passports - those that have all required
//! fields **and valid values**. Continue to treat cid as optional.
//! **In your batch file, how many passports are valid?**
#[macro_use... | test_kvlist_parser | identifier_name | |
AtivContex 5.py | 138735,102665,74509,37425)
casosnovosT=(57,185,351,42,365,867,406,204,1085,555,583,190,225,237,178,316,372,3172,1279,1331,130,786,
1275,2268,1073,1240,589)
obitosAcumuladosT=(582,617,3505,568,1017,516,5945,1763,4475,3277,8163,2183,7210,1619,2081,1717,14566,26899,2908,4223,
2744,1839,2733,2042,2336,2368,640)
NovosObitos... | Regioes[1].append(AC[1])
Regioes[2].append(AC[2])
Regioes[3].append(AC[3])
Regioes[4].append(AC[4]) | random_line_split | |
AtivContex 5.py | aba","Cruzeiro do Sul","Feijó","Jordão","Mancio Lima",
"Manoel Urbano","Porto Acre","Rio Branco","Tarauaca","Xapuri","Sena Madureira"]
populacaoAC=[15256,7417,26278,10266,11733,88876, 34780, 8317,18977,9459,18504, 407319,42567,19323,45848 ]
CasosAcumuladoAC=[432,506,1119,367, 247, 3163, 1139, 160, 743,274, 495,10071, 4... | mulado aperte em 2:"))
if(e1==1):
print("***Wiki:estados do Brasil**\n")
print("\nNORTE:\n0-Acre\n1-Amapá\n2-Amazonas\n3-Rondônia\n4-Roraima\n5-Tocantins\n6-Pará")
print("\nNORDESTE:\n7-Alagoas\n8-Bahia\n9-Ceará\n10-Maranhão\n11-Paraíba\nPernanbuco\n13-Piauí\n14-Rio Grande do Nort... | conditional_block | |
sync.go | if reqPerSecond > 0 {
rateLimiter = time.NewTicker(time.Second / time.Duration(reqPerSecond))
}
return &clientConn{
client: &http.Client{},
maxPoolSize: maxPoolSize,
cSemaphore: cSemaphore,
reqPerSecond: reqPerSecond,
rateLimiter: rateLimiter,
}
}
func newRoutineStat(max int) *routineStat {
... |
}
case fetcher := <-s.routineDone:
s.routineReturned++
fmt.Printf("Processor|End[ %d| %d] : %s\n", fetcher.id, s.routineLauched-s.routineReturned, fetcher.urlEntry.url.String())
default:
if s.routineMax == 0 || s.routineLauched-s.routineReturned < s.routineMax {
select {
case record, ok := <-c.... | {
break loop
} | conditional_block |
sync.go | if reqPerSecond > 0 {
rateLimiter = time.NewTicker(time.Second / time.Duration(reqPerSecond))
}
return &clientConn{
client: &http.Client{},
maxPoolSize: maxPoolSize,
cSemaphore: cSemaphore,
reqPerSecond: reqPerSecond,
rateLimiter: rateLimiter,
}
}
func newRoutineStat(max int) *routineStat {
... | (urlEntry *URLEntry) *RecordFetcher {
r := &RecordFetcher{
Fetcher: Fetcher{
id: c.recordStat.routineLauched,
client: c.recordClient,
ctx: c.ctx,
done: c.recordStat.routineDone,
urlEntry: urlEntry,
timeout: time.Second * 30,
},
subUrls: newURLQueue(100),
files: ma... | newRecordFetcher | identifier_name |
sync.go | routineDone chan *Fetcher
routineMax int
}
//Controller is the global data
type Controller struct {
ctx context.Context
wg sync.WaitGroup
explorerClient *clientConn
recordClient *clientConn
subTree chan *URLEntry
record chan *URLEntry
urlCache map[string]... | random_line_split | ||
sync.go | if reqPerSecond > 0 {
rateLimiter = time.NewTicker(time.Second / time.Duration(reqPerSecond))
}
return &clientConn{
client: &http.Client{},
maxPoolSize: maxPoolSize,
cSemaphore: cSemaphore,
reqPerSecond: reqPerSecond,
rateLimiter: rateLimiter,
}
}
func newRoutineStat(max int) *routineStat {
... |
//CreateTime builds url time
func CreateTime(ts string) time.Time {
regex, _ := regexp.Compile("([0-9]+)-([A-Za-z]+)-[0-9]{2}([0-9]{2})[\t ]*([0-9]{2}:[0-9]{2})")
tss := regex.FindStringSubmatch(ts)
if len(tss) == 5 {
ts = fmt.Sprintf("%s %s %s %s PDT", tss[1], tss[2], tss[3], tss[4])
tm, _ := time.Parse(time.... | {
for _, attr := range t.Attr {
if attr.Key == "href" {
return attr.Val, nil
}
}
return "", errors.New("No Href attribute in the link")
} | identifier_body |
auth.go | ([]byte(data))
return fmt.Sprintf("%x", digest.Sum(nil))
}
func getAuthParams(req *http.Request) []AuthMethod {
var methods []AuthMethod
for _, h := range req.Header["Authorization"] {
parser := HeaderParser{Buffer: h}
parser.Init()
if err := parser.Parse(); err != nil {
log.Println(err)
} else {
par... | (entry Entry, res http.ResponseWriter, req *http.Request) bool {
Auth.mutex.Lock()
defer Auth.mutex.Unlock()
now := time.Now()
Auth.purge(now)
authorized, found_auth, stale, errors := Auth.checkRequest(entry, req, now)
if len(errors) > 0 {
for err := range errors {
fmt.Println(err)
}
}
auths, auth_err... | Authenticate | identifier_name |
auth.go | byte(data))
return fmt.Sprintf("%x", digest.Sum(nil))
}
func getAuthParams(req *http.Request) []AuthMethod {
var methods []AuthMethod
for _, h := range req.Header["Authorization"] {
parser := HeaderParser{Buffer: h}
parser.Init()
if err := parser.Parse(); err != nil {
log.Println(err)
} else {
parser... |
func (Auth *Authenticator) checkRequest(entry Entry, req *http.Request, now time.Time) (bool, bool, bool, []error) {
var errors []error
var stale = false
var found_auth_all = false
if req.TLS != nil {
certs := req.TLS.PeerCertificates;
for _, cert := range certs {
authList, ers := authList(entry);
if... | {
// FIXME do something with nonce_count
nonce, ok := auth.nonces[noncekey]
if !ok {
return false, "", "", ""
}
opaque := nonce.Opaque
auth_domain := nonce.Domain
auth_realm := nonce.Realm
valid := nonce.Time.Add(nonce.Validity).After(now)
if !valid {
delete(auth.nonces, noncekey)
//log.Printf("Purge sta... | identifier_body |
auth.go | ([]byte(data))
return fmt.Sprintf("%x", digest.Sum(nil))
}
func getAuthParams(req *http.Request) []AuthMethod {
var methods []AuthMethod
for _, h := range req.Header["Authorization"] {
parser := HeaderParser{Buffer: h}
parser.Init()
if err := parser.Parse(); err != nil {
log.Println(err)
} else {
par... | for ent := entry; ent != nil; ent = ent.Parent(true) {
auths := entry.Parameters().Child("auth")
auth_list, err := auths.Children()
if err != nil && os.IsExist(err) {
errors = append(errors, err)
continue
}
for _, auth := range auth_list {
found := false
if auth.Name() == AnonymousAuthDomain {
... | random_line_split | |
auth.go | byte(data))
return fmt.Sprintf("%x", digest.Sum(nil))
}
func getAuthParams(req *http.Request) []AuthMethod {
var methods []AuthMethod
for _, h := range req.Header["Authorization"] {
parser := HeaderParser{Buffer: h}
parser.Init()
if err := parser.Parse(); err != nil {
log.Println(err)
} else {
parser... |
for _, auth := range auth_list {
found := false
if auth.Name() == AnonymousAuthDomain {
continue
}
for _, v := range res_auths {
if v == auth.Name() {
found = true
break
}
}
if !found {
res_auths = append(res_auths, auth.Name())
}
}
if !auths.Child("inherit").Exists... | {
errors = append(errors, err)
continue
} | conditional_block |
tools.py |
Returns corrected thetas that are with respect to alpha
'''
thetas = thetas_.copy()
nth = thetas.shape[0]
# thresh = pi/2.
th0 = alpha
dalpha = 0
for ith, th in enumerate(thetas):
dth = th - th0
# print th, dth
if dth > pi/2 + pol*pi/4:
if dth > ... | th0 = th
# Detect false rotations
if (0):
gap = 5
# Thetas are wrt alpha
for ith, th in enumerate(thetas):
if ith > gap:
iref = max(0,ith-gap)
dth = th - thetas[iref]
if dth > pi:
# angles should be ... | pol = np.sign(dalpha)
thetas[ith] = th - alpha | random_line_split |
tools.py | (ref,rs):
# ref is 1x2 ndarray
# rs is list of vectors to compare, nx2
return np.linalg.norm((ref-rs),axis=1)
def nematicdirector(Q):
# Given Q matrix return order parameter and angle
w,v = np.linalg.eig(Q)
idx = np.argmax(w)
Lam = w[idx] # Equiv to sqrt(S*S+T*T)
nu = v[:,idx]
alpha... | dist_from | identifier_name | |
tools.py |
Returns corrected thetas that are with respect to alpha
'''
thetas = thetas_.copy()
nth = thetas.shape[0]
# thresh = pi/2.
th0 = alpha
dalpha = 0
for ith, th in enumerate(thetas):
dth = th - th0
# print th, dth
if dth > pi/2 + pol*pi/4:
if dth > ... | phi_jalpha = np.where(phi_jalpha < 0., phi_jalpha+twopi, phi_jalpha)
rods[:,-1] = phi_jalpha
rods = rods[rods[:,-1].argsort()]
nrod = len(rods)
idxs = np.arange(nrod).reshape(nrod,1)
rods = np.append(idxs,rods,axis=1)
rods2 = rods.copy()
rods3 = rods.copy()
# rods is sorted by p... | '''
rod x,y coordinates must be relative to their probe center
angular coordinates are in range [0,2pi]
Given your application, they will have their 4th column as a
variable vector
Instead of strict polar sort, the next rod is actually a nearest
neighbour in the winding direction
We can ach... | identifier_body |
tools.py | +isubth] = subth - pi
thetas[ith] = th - pi
elif dth < -pi:
for isubth, subth in enumerate(thetas[iref+1:ith]):
sub_dth = subth - thetas[iref]
if sub_dth < pi/2:
thetas[iref+1+isubth] = su... | features[i,:] = nbrs[:,-1] / pi | conditional_block | |
resnext_cifar.py | D = cardinality * out_channels // widen_factor
self.conv_reduce = nn.Conv2d(in_channels, D, kernel_size=1, stride=1, padding=0, bias=False)
self.bn_reduce = nn.BatchNorm2d(D)
self.conv_conv = nn.Conv2d(D, D, kernel_size=3, stride=stride, padding=1, groups=cardinality, bias=False)
... | (**kwargs):
"""Constructs a ResNeXt.
"""
model = CifarResNeXt(**kwargs)
return model
# """
# resneXt for cifar with pytorch
# Reference:
# [1] S. Xie, G. Ross, P. Dollar, Z. Tu and K. He Aggregated residual transformations for deep neural networks. In CVPR, 2017
# """
#
# import t... | resnext | identifier_name |
resnext_cifar.py | stride: conv stride. Replaces pooling layer.
cardinality: num of convolution groups.
widen_factor: factor to reduce the input dimensionality before convolution.
"""
super(ResNeXtBottleneck, self).__init__()
D = cardinality * out_channels // widen_factor
... | out_channels: output channel dimensionality | random_line_split | |
resnext_cifar.py | D = cardinality * out_channels // widen_factor
self.conv_reduce = nn.Conv2d(in_channels, D, kernel_size=1, stride=1, padding=0, bias=False)
self.bn_reduce = nn.BatchNorm2d(D)
self.conv_conv = nn.Conv2d(D, D, kernel_size=3, stride=stride, padding=1, groups=cardinality, bias=False)
... |
elif key.split('.')[-1] == 'bias':
self.state_dict()[key][...] = 0
def block(self, name, in_channels, out_channels, pool_stride=2):
""" Stack n bottleneck modules where n is inferred from the depth of the network.
Args:
name: string name of the current block... | if 'conv' in key:
init.kaiming_normal(self.state_dict()[key], mode='fan_out')
if 'bn' in key:
self.state_dict()[key][...] = 1 | conditional_block |
resnext_cifar.py | D = cardinality * out_channels // widen_factor
self.conv_reduce = nn.Conv2d(in_channels, D, kernel_size=1, stride=1, padding=0, bias=False)
self.bn_reduce = nn.BatchNorm2d(D)
self.conv_conv = nn.Conv2d(D, D, kernel_size=3, stride=stride, padding=1, groups=cardinality, bias=False)
... |
# """
# resneXt for cifar with pytorch
# Reference:
# [1] S. Xie, G. Ross, P. Dollar, Z. Tu and K. He Aggregated residual transformations for deep neural networks. In CVPR, 2017
# """
#
# import torch
# import torch.nn as nn
# import math
#
#
# class Bottleneck(nn.Module):
# expansion = 4
#
... | """Constructs a ResNeXt.
"""
model = CifarResNeXt(**kwargs)
return model | identifier_body |
store.ts | utils/ajax';
import { ParserContext, parseRenpyScript } from './renpy/renpy-parser';
import { ButtonConfig, Config, HudStatConfig, SkillData } from './types/config';
import { GameSave } from './types/game-save';
import { SAVE_FILE } from './constants';
import { AppOptions } from '.';
import { getConfig } from './config... | ,
setButtons(state, buttons: { [key: string]: ButtonConfig }) {
for (const i in buttons) {
state.buttons[i] = {
enabled: buttons[i].enabled,
};
}
},
clearDialog(state) {
state.dialog.splice(0);
},
changeButton(state, payload: { button... | {
state.currentScreen = screen;
} | identifier_body |
store.ts | utils/ajax';
import { ParserContext, parseRenpyScript } from './renpy/renpy-parser';
import { ButtonConfig, Config, HudStatConfig, SkillData } from './types/config';
import { GameSave } from './types/game-save';
import { SAVE_FILE } from './constants';
import { AppOptions } from '.';
import { getConfig } from './config... |
// define injection key
key = Symbol('Store Injection Key');
console.log('setup store');
store = createStore<State>({
state: {
machine: {
stack: [],
script: {},
data: {
playerName: 'Player',
},
},
dialog: [],
ready: false,
count: 0,
... | {
plugins.push(createLogger());
} | conditional_block |
store.ts | typings for the store state
export interface SetupStoreResult {
store: Store<State>;
key: InjectionKey<Store<State>>;
}
export type AddStackOptions = Partial<MachineStack>;
let key: InjectionKey<Store<State>> = Symbol('Store Injection Key');
let store: Store<State>;
export function setupStore(options: AppOptio... | clearErrors | identifier_name | |
store.ts | setupStore(options: AppOptions): SetupStoreResult {
const plugins = [];
// checking process.env actually exists just for safety
if (options.logging) {
plugins.push(createLogger());
}
// define injection key
key = Symbol('Store Injection Key');
console.log('setup store');
store = createStore<State>... | }, | random_line_split | |
tls_pstm_montgomery_reduce.rs | //#if SOME_COND #define PSTM_ARM, #define PSTM_32BIT
/* Failure due to bad function param */
/* Failure as a result of system call error */
/* Failure to allocate requested memory */
/* Failure on sanity/limit tests */
pub type uint64 = u64;
pub type uint32 = u32;
pub type int32 = i32;
pub type pstm_digit = uint32;
pu... | (
mut a: *mut pstm_int,
mut m: *mut pstm_int,
mut mp: pstm_digit,
mut paD: *mut pstm_digit,
mut paDlen: uint32,
) -> int32 {
let mut c: *mut pstm_digit = 0 as *mut pstm_digit; //bbox: was int16
let mut _c: *mut pstm_digit = 0 as *mut pstm_digit;
let mut tmpm: *mut pstm_digit = 0 as *mut pstm_digit;
le... | pstm_montgomery_reduce | identifier_name |
tls_pstm_montgomery_reduce.rs | ) 2017 Denys Vlasenko
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
/* The file is taken almost verbatim from matrixssl-3-7-2b-open/crypto/math/.
* Changes are flagged with //bbox
*/
/* *
* @file pstm.h
* @version 33ef80f (HEAD, tag: MATRIXSSL-3-7-2-OPEN, tag: MATRIXSSL-3-7-2-COMM, origin... | {
c = xzalloc((2i32 * pa + 1i32) as size_t) as *mut pstm_digit
//bbox
} | conditional_block | |
tls_pstm_montgomery_reduce.rs | //#if SOME_COND #define PSTM_ARM, #define PSTM_32BIT
/* Failure due to bad function param */
/* Failure as a result of system call error */
/* Failure to allocate requested memory */
/* Failure on sanity/limit tests */
pub type uint64 = u64;
pub type uint32 = u32;
pub type int32 = i32;
pub type pstm_digit = uint32;
pu... | * the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This General Public License does NOT permit incorporating this software
* into proprietary programs. If you are unable to comply with the GPL, a
* commercial license for this software may be purchased fr... | *
* The latest version of this code is available at http://www.matrixssl.org
*
* This software is open source; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by | random_line_split |
helper.go | /gophercloud/gophercloud/pagination"
"go.uber.org/zap"
)
var (
errNotFound = errors.New("not found")
securityGroupCreationLock = sync.Mutex{}
)
const (
errorStatus = "ERROR"
floatingReassignIPCheckPeriod = 3 * time.Second
)
func getRegion(client *gophercloud.ProviderClient, name string) (*osregio... | return true, nil
})
if err != nil {
return nil, err
}
for _, f := range allFlavors {
if f.Name == c.Flavor {
return &f, nil
}
}
return nil, errNotFound
}
func getSecurityGroup(client *gophercloud.ProviderClient, region, name string) (*ossecuritygroups.SecGroup, error) {
netClient, err := goopenstac... | }
allFlavors = append(allFlavors, flavors...) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.