file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
core.py | # /usr/bin/env python2.7
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2017-2018, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modifica... | :
"""
Class for query a graph's operations and related data.
"""
def __init__(self, graph, op_map=None, ops_to_ignore=None, strict=True):
"""
Constructor
:param graph: The graph to search
:param op_map: The map of operations used to identify op sequences as "one op".
... | OpQuery | identifier_name |
core.py | # /usr/bin/env python2.7
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2017-2018, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modifica... | def get_weight_ops(self, ops=None, skip_bias_op=False):
"""
Get all ops that contain weights. If a list of ops is passed search only ops
from this list. Return the sequenced list of weight ops always with Conv/FC
first, followed by the bias op, if present.
:param ops: List of... | random_line_split | |
config.go | package option
import (
"bytes"
"fmt"
"github.com/cilium/cilium/pkg/logging/logfields"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"io/ioutil"
"os"
"path/filepath"
"strings"
"k8s-lx1036/k8s/network/cilium/cilium/pkg/config/defaults"
)
const (
// ciliumEnvPrefix is the prefix used for environ... | // EnableNodePort enables k8s NodePort service implementation in BPF
EnableNodePort bool
// EnableHostPort enables k8s Pod's hostPort mapping through BPF
EnableHostPort bool
// NodePortMode indicates in which mode NodePort implementation should run
// ("snat", "dsr" or "hybrid")
NodePortMode string
// NodePortA... | ////////////////////////////// Service ////////////////////////// | random_line_split |
config.go | package option
import (
"bytes"
"fmt"
"github.com/cilium/cilium/pkg/logging/logfields"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"io/ioutil"
"os"
"path/filepath"
"strings"
"k8s-lx1036/k8s/network/cilium/cilium/pkg/config/defaults"
)
const (
// ciliumEnvPrefix is the prefix used for environ... | ame) // name of config file (without extension)
viper.AddConfigPath("$HOME") // adding home directory as first search path
}
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
log.WithField(logfields.Path, viper.ConfigFileUsed()).
Info("Using config from file")
... | File)
} else {
viper.SetConfigName(configN | conditional_block |
config.go | package option
import (
"bytes"
"fmt"
"github.com/cilium/cilium/pkg/logging/logfields"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"io/ioutil"
"os"
"path/filepath"
"strings"
"k8s-lx1036/k8s/network/cilium/cilium/pkg/config/defaults"
)
const (
// ciliumEnvPrefix is the prefix used for environ... |
var (
// Config represents the daemon configuration
Config = &DaemonConfig{}
)
// InitConfig reads in config file and ENV variables if set.
func InitConfig(configName string) func() {
return func() {
Config.ConfigFile = viper.GetString(ConfigFile) // enable ability to specify config file via flag
Config.Confi... | {
c.LibDir = viper.GetString(LibDir)
c.BpfDir = filepath.Join(c.LibDir, defaults.BpfDir)
c.AgentHealthPort = viper.GetInt(AgentHealthPort)
c.AgentLabels = viper.GetStringSlice(AgentLabels)
c.AllowICMPFragNeeded = viper.GetBool(AllowICMPFragNeeded)
c.AllowLocalhost = viper.GetString(AllowLocalhost)
c.AnnotateK8s... | identifier_body |
config.go | package option
import (
"bytes"
"fmt"
"github.com/cilium/cilium/pkg/logging/logfields"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"io/ioutil"
"os"
"path/filepath"
"strings"
"k8s-lx1036/k8s/network/cilium/cilium/pkg/config/defaults"
)
const (
// ciliumEnvPrefix is the prefix used for environ... | {}, error) {
m := map[string]interface{}{}
fi, err := ioutil.ReadDir(dirName)
if err != nil && !os.IsNotExist(err) {
return nil, fmt.Errorf("unable to read configuration directory: %s", err)
}
for _, f := range fi {
if f.Mode().IsDir() {
continue
}
fName := filepath.Join(dirName, f.Name())
// the fil... | ing]interface | identifier_name |
extract_patch.py | #exec(open('__init__.py').read())
from __future__ import division, print_function
from hscom import __common__
(print, print_, print_on, print_off,
rrr, profile) = __common__.init(__name__, '[extract]')
# Science
import cv2
import numpy as np
from numpy import sqrt
# Hotspotter
import draw_func2 as df2
def rrr():
... | (evals, evecs) = np.linalg.eig(M2x2)
l1, l2 = evals
v1, v2 = evecs
return l1, l2, v1, v2
#-----------------------
# INPUT
#-----------------------
# We will call perdoch's invA = invV
print('--------------------------------')
print('Let V = Perdoch.A')
print(... | arrow.set_facecolor(color)
ax.add_patch(arrow)
df2.update()
def _2x2_eig(M2x2): | random_line_split |
extract_patch.py | #exec(open('__init__.py').read())
from __future__ import division, print_function
from hscom import __common__
(print, print_, print_on, print_off,
rrr, profile) = __common__.init(__name__, '[extract]')
# Science
import cv2
import numpy as np
from numpy import sqrt
# Hotspotter
import draw_func2 as df2
def rrr():
... | (M2x2):
(evals, evecs) = np.linalg.eig(M2x2)
l1, l2 = evals
v1, v2 = evecs
return l1, l2, v1, v2
#-----------------------
# INPUT
#-----------------------
# We are given the keypoint in invA format
(x, y, ia11, ia21, ia22), ia12 = kp, 0
# invA2x2 is a transforma... | _2x2_eig | identifier_name |
extract_patch.py | #exec(open('__init__.py').read())
from __future__ import division, print_function
from hscom import __common__
(print, print_, print_on, print_off,
rrr, profile) = __common__.init(__name__, '[extract]')
# Science
import cv2
import numpy as np
from numpy import sqrt
# Hotspotter
import draw_func2 as df2
def rrr():
... |
else:
patch, subkp = get_patch(rchip, kp)
#print('[extract] kp = '+str(kp))
#print('[extract] subkp = '+str(subkp))
#print('[extract] patch.shape = %r' % (patch.shape,))
color = (0, 0, 1)
fig, ax = df2.imshow(patch, **kwargs)
df2.draw_kpts2([subkp], ell_color=color, pts=True)
... | wpatch, wkp = get_warped_patch(rchip, kp)
patch = wpatch
subkp = wkp | conditional_block |
extract_patch.py | #exec(open('__init__.py').read())
from __future__ import division, print_function
from hscom import __common__
(print, print_, print_on, print_off,
rrr, profile) = __common__.init(__name__, '[extract]')
# Science
import cv2
import numpy as np
from numpy import sqrt
# Hotspotter
import draw_func2 as df2
def rrr():
... |
def get_kp_border(rchip, kp):
np.set_printoptions(precision=8)
df2.reset()
df2.figure(9003, docla=True, doclf=True)
def _plotpts(data, px, color=df2.BLUE, label=''):
#df2.figure(9003, docla=True, pnum=(1, 1, px))
df2.plot2(data.T[0], data.T[1], '-', '', color=color, label=label)
... | from hotspotter import draw_func2 as df2
np.set_printoptions(precision=8)
tau = 2 * np.pi
df2.reset()
df2.figure(9003, docla=True, doclf=True)
ax = df2.gca()
ax.invert_yaxis()
def _plotpts(data, px, color=df2.BLUE, label=''):
#df2.figure(9003, docla=True, pnum=(1, 1, px))
df... | identifier_body |
main.rs | #![feature(unboxed_closures, fn_traits)]
use std::fmt::Debug;
// error[E0635]: unknown feature `fnbox`
// #![feature(unboxed_closures, fn_traits, fnbox)]
// 返回闭包
// 放入 `Box<T>` 中是因为闭包的大小在编译期是未知的.
// fn counter(i: i32) -> Box<Fn(i32) -> i32> {
// Box::new(move |n: i32| n + i)
// }
// Rust 2018 中也可以写成 `impl Fn(i32)... | impl FnOnce<()> for Closure {
type Output = u32;
extern "rust-call" fn call_once(self, args: ()) -> u32 {
println!("call it FnOnce()");
self.env_var + 2
}
}
impl FnMut<()> for Closure {
extern "rust-call" fn call_mut(&mut self, args: ()) -> u32 {
println!("call it FnMut()");
... | env_var: u32,
}
| random_line_split |
main.rs | #![feature(unboxed_closures, fn_traits)]
use std::fmt::Debug;
// error[E0635]: unknown feature `fnbox`
// #![feature(unboxed_closures, fn_traits, fnbox)]
// 返回闭包
// 放入 `Box<T>` 中是因为闭包的大小在编译期是未知的.
// fn counter(i: i32) -> Box<Fn(i32) -> i32> {
// Box::new(move |n: i32| n + i)
// }
// Rust 2018 中也可以写成 `impl Fn(i32)... | 装箱稍后在迭代器中使用
// 所以这里必须使用 `move` 关键字将 `s` 的所有权转移到闭包中,
// 因为变量 `s` 是复制语义类型, 所以该闭包捕获的是原始变量 `s` 的副本
c.push(Box::new(move || println!("{}", s)));
c.push(Box::new(|| println!("third")));
}
// `Fn` 并不受孤儿规则限制, 可有可无
// use std::ops::Fn;
// 以 trait 限定的方式实现 any 方法
// 自定义的 Any 不同于标准库的 Any
// 该函数的泛型 `F` 的 trait 限定为... | 要将闭包 | identifier_name |
main.rs | #![feature(unboxed_closures, fn_traits)]
use std::fmt::Debug;
// error[E0635]: unknown feature `fnbox`
// #![feature(unboxed_closures, fn_traits, fnbox)]
// 返回闭包
// 放入 `Box<T>` 中是因为闭包的大小在编译期是未知的.
// fn counter(i: i32) -> Box<Fn(i32) -> i32> {
// Box::new(move |n: i32| n + i)
// }
// Rust 2018 中也可以写成 `impl Fn(i32)... | Pick<F>
// where
// F: Fn(&(u32, u32)) -> &u32,
// {
// fn call(&self) -> &u32 { (self.func)(&self.data) }
// }
// 实际生命周期
impl<F> Pick<F>
where
F: for<'f> Fn(&'f (u32, u32)) -> &'f u32,
{
fn call(&self) -> &u32 { (self.func)(&self.data) }
}
fn max(data: &(u32, u32)) -> &u32 {
if data.0 > data.1 {... | 器自动补齐了生命周期参数
// impl<F> | identifier_body |
main.rs | #![feature(unboxed_closures, fn_traits)]
use std::fmt::Debug;
// error[E0635]: unknown feature `fnbox`
// #![feature(unboxed_closures, fn_traits, fnbox)]
// 返回闭包
// 放入 `Box<T>` 中是因为闭包的大小在编译期是未知的.
// fn counter(i: i32) -> Box<Fn(i32) -> i32> {
// Box::new(move |n: i32| n + i)
// }
// Rust 2018 中也可以写成 `impl Fn(i32)... | let env_var = 1;
let c = || env_var + 2;
assert_eq!(3, c());
// 显式指定闭包类型
let env_var = 1;
// 该类型为 trait 对象, 此处必须使用 trait 对象
let c: Box<Fn() -> i32> = Box::new(|| env_var + 2);
assert_eq!(3, c());
// 复制语义类型自动实现 `Fn`
// 绑定为字符串字面量, 为复制语义类型
let s = "hello";
// 闭包会按照不可变引用类型来捕获... | }
// 与上者等价的闭包示例
| conditional_block |
onsite_create_calibration_file.py | #!/usr//bin/env python
"""
Onsite script for creating a flat-field calibration file file to be run as a command line:
--> onsite_create_calibration_file
"""
import argparse
import os
import subprocess
import sys
from pathlib import Path
from astropy.time import Time
import pymongo
import lstchain
import lstchai... | if __name__ == '__main__':
main() | random_line_split | |
onsite_create_calibration_file.py | #!/usr//bin/env python
"""
Onsite script for creating a flat-field calibration file file to be run as a command line:
--> onsite_create_calibration_file
"""
import argparse
import os
import subprocess
import sys
from pathlib import Path
from astropy.time import Time
import pymongo
import lstchain
import lstchai... |
if __name__ == '__main__':
main()
| """ return the range of charges to select the FF events """
try:
if filters is None:
raise ValueError("Filters are not defined")
# give standard values if standard filters
if filters == '52':
min_ff = 3000
max_ff = 12000
else:
# ... ... | identifier_body |
onsite_create_calibration_file.py | #!/usr//bin/env python
"""
Onsite script for creating a flat-field calibration file file to be run as a command line:
--> onsite_create_calibration_file
"""
import argparse
import os
import subprocess
import sys
from pathlib import Path
from astropy.time import Time
import pymongo
import lstchain
import lstchai... | ():
args, remaining_args = parser.parse_known_args()
run = args.run_number
prod_id = args.prod_version
stat_events = args.statistics
time_run = args.time_run
sys_date = args.sys_date
no_sys_correction = args.no_sys_correction
output_base_name = args.output_base_name
sub_run = args.su... | main | identifier_name |
onsite_create_calibration_file.py | #!/usr//bin/env python
"""
Onsite script for creating a flat-field calibration file file to be run as a command line:
--> onsite_create_calibration_file
"""
import argparse
import os
import subprocess
import sys
from pathlib import Path
from astropy.time import Time
import pymongo
import lstchain
import lstchai... |
# give standard values if standard filters
if filters == '52':
min_ff = 3000
max_ff = 12000
else:
# ... recuperate transmission value of all the filters
transm_file = os.path.join(os.path.dirname(__file__), "../../data/filters_transmission.dat")... | raise ValueError("Filters are not defined") | conditional_block |
auto-py-torrent.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""auto_py_torrent.
This module provides utilities to download a torrent within specific types.
"""
# Author: Gabriel Scotillo
# URL: https://github.com/ocslegna/auto_py_torrent
# Please do not download illegal torrents or torrents that you do not have
# permission ... | (self):
"""Build appropiate encoded URL.
This implies the same way of searching a torrent as in the page itself.
"""
url = requests.utils.requote_uri(
self.torrent_page + self.string_search)
if self.page == '1337x':
return(url + '/1/')
elif self.p... | build_url | identifier_name |
auto-py-torrent.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""auto_py_torrent.
This module provides utilities to download a torrent within specific types.
"""
# Author: Gabriel Scotillo
# URL: https://github.com/ocslegna/auto_py_torrent
# Please do not download illegal torrents or torrents that you do not have
# permission ... | titles = []
seeders = []
leechers = []
ages = []
sizes = []
if self.page == 'the_pirate_bay':
for elem in self.elements[0]:
title = elem.find('a', {'class': 'detLink'}).get_text()
titles.append(title)
font_text... | def build_table(self):
"""Build table."""
headers = ['Title', 'Seeders', 'Leechers', 'Age', 'Size'] | random_line_split |
auto-py-torrent.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""auto_py_torrent.
This module provides utilities to download a torrent within specific types.
"""
# Author: Gabriel Scotillo
# URL: https://github.com/ocslegna/auto_py_torrent
# Please do not download illegal torrents or torrents that you do not have
# permission ... |
elif self.mode_search == 'list':
if self.selected is not None:
# t_p, pirate and 1337x got magnet inside, else direct.
if self.page in ['the_pirate_bay',
'torrent_project',
... | print('Nothing found.')
return | conditional_block |
auto-py-torrent.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""auto_py_torrent.
This module provides utilities to download a torrent within specific types.
"""
# Author: Gabriel Scotillo
# URL: https://github.com/ocslegna/auto_py_torrent
# Please do not download illegal torrents or torrents that you do not have
# permission ... |
def select_torrent(self):
"""Select torrent.
First check if specific element/info is obtained in content_page.
Specify to user if it wants best rated torrent or select one from list.
If the user wants best rated: Directly obtain magnet/torrent.
Else: build table with all d... | """Handle user's input in list mode."""
#self.selected = input('>> ')
self.selected = '0'
if self.selected in ['Q', 'q']:
sys.exit(1)
elif self.selected in ['B', 'b']:
self.back_to_menu = True
return True
elif is_num(self.selected):
... | identifier_body |
filter.go | // Copyright © 2021 Kaleido, Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unle... | and ...Filter) AndFilter {
return &andFilter{
baseFilter: baseFilter{
fb: fb,
op: FilterOpAnd,
children: and,
},
}
}
type orFilter struct {
baseFilter
}
func (fb *orFilter) Condition(children ...Filter) MultiConditionFilter {
fb.children = append(fb.children, children...)
return fb
}
fu... | nd( | identifier_name |
filter.go | // Copyright © 2021 Kaleido, Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unle... | }
func (f *baseFilter) Skip(skip uint64) Filter {
f.fb.skip = skip
return f
}
func (f *baseFilter) Limit(limit uint64) Filter {
f.fb.limit = limit
return f
}
func (f *baseFilter) Count(c bool) Filter {
f.fb.count = c
return f
}
func (f *baseFilter) Ascending() Filter {
f.fb.forceAscending = true
return f
}
... | }
return f | random_line_split |
filter.go | // Copyright © 2021 Kaleido, Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unle... |
func (fb *filterBuilder) IContains(name string, value driver.Value) Filter {
return fb.fieldFilter(FilterOpICont, name, value)
}
func (fb *filterBuilder) NotIContains(name string, value driver.Value) Filter {
return fb.fieldFilter(FilterOpNotICont, name, value)
}
func (fb *filterBuilder) fieldFilter(op FilterOp, n... |
return fb.fieldFilter(FilterOpNotCont, name, value)
}
| identifier_body |
filter.go | // Copyright © 2021 Kaleido, Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unle... | } else if f.fb.forceAscending {
for _, sf := range f.fb.sort {
sf.Descending = false
}
}
return &FilterInfo{
Children: children,
Op: f.op,
Field: f.field,
Values: values,
Value: value,
Sort: f.fb.sort,
Skip: f.fb.skip,
Limit: f.fb.limit,
Count: f.fb.count,
}, ni... |
sf.Descending = true
}
| conditional_block |
wdpost_dispute_test.go | // stm: #integration
package itests
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/builtin"
minertypes "github.com/filecoin-project/go-state-types/builtin/... |
func TestWindowPostDisputeFails(t *testing.T) {
//stm: @CHAIN_SYNCER_LOAD_GENESIS_001, @CHAIN_SYNCER_FETCH_TIPSET_001,
//stm: @CHAIN_SYNCER_START_001, @CHAIN_SYNCER_SYNC_001, @BLOCKCHAIN_BEACON_VALIDATE_BLOCK_VALUES_01
//stm: @CHAIN_SYNCER_COLLECT_CHAIN_001, @CHAIN_SYNCER_COLLECT_HEADERS_001, @CHAIN_SYNCER_VALIDAT... | {
//stm: @CHAIN_SYNCER_LOAD_GENESIS_001, @CHAIN_SYNCER_FETCH_TIPSET_001,
//stm: @CHAIN_SYNCER_START_001, @CHAIN_SYNCER_SYNC_001, @BLOCKCHAIN_BEACON_VALIDATE_BLOCK_VALUES_01
//stm: @CHAIN_SYNCER_COLLECT_CHAIN_001, @CHAIN_SYNCER_COLLECT_HEADERS_001, @CHAIN_SYNCER_VALIDATE_TIPSET_001
//stm: @CHAIN_SYNCER_NEW_PEER_HEAD... | identifier_body |
wdpost_dispute_test.go | // stm: #integration
package itests
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/builtin"
minertypes "github.com/filecoin-project/go-state-types/builtin/... | }
params := &minertypes.SubmitWindowedPoStParams{
ChainCommitEpoch: commEpoch,
ChainCommitRand: commRand,
Deadline: dlIdx,
Partitions: []minertypes.PoStPartition{{Index: partIdx}},
Proofs: []prooftypes.PoStProof{{
PoStProof: minerInfo.WindowPoStProofType,
ProofBytes: []byte("I'm soooo ... | return err | random_line_split |
wdpost_dispute_test.go | // stm: #integration
package itests
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/builtin"
minertypes "github.com/filecoin-project/go-state-types/builtin/... |
// Try to object to the proof. This should fail.
{
params := &minertypes.DisputeWindowedPoStParams{
Deadline: targetDeadline,
PoStIndex: 0,
}
enc, aerr := actors.SerializeParams(params)
require.NoError(t, aerr)
msg := &types.Message{
To: maddr,
Method: builtin.MethodsMiner.DisputeWindow... | {
//stm: @CHAIN_STATE_MINER_CALCULATE_DEADLINE_001
di, err := client.StateMinerProvingDeadline(ctx, maddr, types.EmptyTSK)
require.NoError(t, err)
// wait until the deadline finishes.
if di.Index == ((targetDeadline + 1) % di.WPoStPeriodDeadlines) {
break
}
build.Clock.Sleep(blocktime)
} | conditional_block |
wdpost_dispute_test.go | // stm: #integration
package itests
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/builtin"
minertypes "github.com/filecoin-project/go-state-types/builtin/... | (
ctx context.Context,
client api.FullNode, owner address.Address, maddr address.Address,
di *dline.Info, dlIdx, partIdx uint64,
) error {
head, err := client.ChainHead(ctx)
if err != nil {
return err
}
//stm: @CHAIN_STATE_MINER_INFO_001
minerInfo, err := client.StateMinerInfo(ctx, maddr, head.Key())
if err... | submitBadProof | identifier_name |
deferred_call.rs | // Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.
//! Hardware-independent kernel interface for deferred calls
//!
//! This allows any struct in the kernel which implements
//! [DeferredCallClient](crate::deferred_ca... |
// To reduce monomorphization bloat, the non-generic portion of register is moved into this
// function without generic parameters.
#[inline(never)]
fn register_internal_non_generic(&self, handler: DynDefCallRef<'static>) {
// SAFETY: No accesses to DEFCALLS are via an &mut, and the Tock kerne... | {
// SAFETY: No accesses to CTR are via an &mut, and the Tock kernel is
// single-threaded so all accesses will occur from this thread.
let ctr = unsafe { &CTR };
let idx = ctr.get() + 1;
ctr.set(idx);
DeferredCall { idx }
} | identifier_body |
deferred_call.rs | // Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.
//! Hardware-independent kernel interface for deferred calls
//!
//! This allows any struct in the kernel which implements
//! [DeferredCallClient](crate::deferred_ca... | () -> bool {
// SAFETY: No accesses to BITMASK are via an &mut, and the Tock kernel is
// single-threaded so all accesses will occur from this thread.
let bitmask = unsafe { &BITMASK };
bitmask.get() != 0
}
/// This function should be called at the beginning of the kernel loop
... | has_tasks | identifier_name |
deferred_call.rs | // Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.
//! Hardware-independent kernel interface for deferred calls
//!
//! This allows any struct in the kernel which implements
//! [DeferredCallClient](crate::deferred_ca... |
}
}
| {
panic!(
"ERROR: > 32 deferred calls, or a component forgot to register a deferred call."
);
} | conditional_block |
deferred_call.rs | // Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.
//! Hardware-independent kernel interface for deferred calls
//!
//! This allows any struct in the kernel which implements
//! [DeferredCallClient](crate::deferred_ca... | DeferredCall { idx }
}
// To reduce monomorphization bloat, the non-generic portion of register is moved into this
// function without generic parameters.
#[inline(never)]
fn register_internal_non_generic(&self, handler: DynDefCallRef<'static>) {
// SAFETY: No accesses to DEFCALLS a... | // SAFETY: No accesses to CTR are via an &mut, and the Tock kernel is
// single-threaded so all accesses will occur from this thread.
let ctr = unsafe { &CTR };
let idx = ctr.get() + 1;
ctr.set(idx); | random_line_split |
cut_plane.py | """
Copyright 2018 NREL
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
un... | (self,ax=None,minSpeed=None,maxSpeed=None,levels=[-5,-4,-3,-2,-1]):
# Complete a plot in style of more recent paper
if not ax:
fig, ax = plt.subplots()
# First visualization
# print(minSpeed,maxSpeed)
im = self.visualize(ax=ax,minSpeed=minSpeed,maxSpeed=maxSpeed)
... | paper_plot | identifier_name |
cut_plane.py | """
Copyright 2018 NREL
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
un... |
# Assign the axis names
self.x1_name = x1
self.x2_name = x2
self.x3_name = [x3 for x3 in ['x','y','z'] if x3 not in [x1,x2]][0]
# Find the nearest value in 3rd dimension
search_values = np.array(sorted(df_flow[self.x3_name].unique()))
nearest_idx = (np.abs(searc... | output:
flow_file: full path name of flow file""" | random_line_split |
cut_plane.py | """
Copyright 2018 NREL
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
un... |
if crop_x2:
if crop_x2[0] < min(df_sub[x2]):
raise Exception("Invalid x_2 minimum on cropping")
if crop_x2[1] > max(df_sub[x2]):
raise Exception("Invalid x_2 maximum on cropping")
# If cropping x1 do it now
# if crop_x1:
# df... | raise Exception("Invalid x_1 maximum on cropping") | conditional_block |
cut_plane.py | """
Copyright 2018 NREL
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
un... |
# Define cross plane subclass
class CrossPlane(_CutPlane):
def __init__(self, df_flow, x_value, y_center, z_center, D, resolution=100, crop_y=None,crop_z=None,invert_x1=True):
# Set up call super
super().__init__(df_flow, x1='y', x2='z', x3_value=x_value,resolution=resolution,x1_center=y_center... | def __init__(self, df_flow, z_value, resolution=100, x1_center=0.0,x2_center=0.0, D=None):
# Set up call super
super().__init__(df_flow, x1='x', x2='y', x3_value=z_value,resolution=resolution,x1_center=x1_center,x2_center=x2_center, D=D, invert_x1=False) | identifier_body |
ground_glass.py | import tkinter as tk
import cv2 as cv
import numpy as np
from PIL import Image, ImageTk
import tkinter.filedialog
from numpy import fft
import math
import matplotlib.pyplot as graph
window = tk.Tk()
window.title('毛玻璃清晰化处理软件')
window.geometry('815x790')
address0 = 'code_image//timg.jpg'
address1 = 'code_... | t)
address1 = 'output/%s/output1.jpg' % (folder)
cv.waitKey(0)
cv.destroyAllWindows()
cavans_creat()
creat_menu()
cavans_creat()
scale_creat()
window.mainloop() | img,anchor="nw")
canvas1.create_image(image.width,0,image = img,anchor="nw")
canvas1.pack()
word_box.pack()
top1.mainloop()
def opencv():
global address1
src = cv.imread('output/%s/cutted.jpg'%(folder))
src = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
cv.imwrite('output/%s/gray.jp... | identifier_body |
ground_glass.py | import tkinter as tk
import cv2 as cv
import numpy as np
from PIL import Image, ImageTk
import tkinter.filedialog
from numpy import fft
import math
import matplotlib.pyplot as graph
window = tk.Tk()
window.title('毛玻璃清晰化处理软件')
window.geometry('815x790')
address0 = 'code_image//timg.jpg'
address1 = 'code_... | None:
n = height / float(h)
newsize = (int(n * w), height)
else:
n = width / float(w)
newsize = (width, int(h * n))
# 缩放图像
newimage = cv.resize(image, newsize, interpolation=inter)
return newimage
def on_mouse(event, x, y, flags, param):
global img, i... | if width is | conditional_block |
ground_glass.py | import tkinter as tk
import cv2 as cv
import numpy as np
from PIL import Image, ImageTk
import tkinter.filedialog
from numpy import fft
import math
import matplotlib.pyplot as graph
window = tk.Tk()
window.title('毛玻璃清晰化处理软件')
window.geometry('815x790')
address0 = 'code_image//timg.jpg'
address1 = 'code_... | int1, point2, point1_dis, point2_dis
img2 = img1.copy()
if event == cv.EVENT_LBUTTONDOWN: #左键点击
point1 = (x*4, y*4)
point1_dis = (x, y)
cv.circle(img2, point1_dis, 10, (0,255,0), 5)
cv.imshow('image', img2)
elif event == cv.EVENT_MOUSEMOVE and (flags & cv.EVENT... | img1, po | identifier_name |
ground_glass.py | import tkinter as tk
import cv2 as cv
import numpy as np
from PIL import Image, ImageTk
import tkinter.filedialog
from numpy import fft
import math
import matplotlib.pyplot as graph
window = tk.Tk()
window.title('毛玻璃清晰化处理软件')
window.geometry('815x790')
address0 = 'code_image//timg.jpg'
address1 = 'code_... | canvas1.pack()
word_box.pack()
top1.mainloop()
def opencv():
global address1
src = cv.imread('output/%s/cutted.jpg'%(folder))
src = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
cv.imwrite('output/%s/gray.jpg' % (folder),src)
#wiener_change(src)
#image_out(src, 600, 800, "input_... | canvas1.create_image(image.width,0,image = img,anchor="nw")
| random_line_split |
operator.go | // Copyright 2016 PingCAP, 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 i... |
// GetPriorityLevel get the priority level
func (o *Operator) GetPriorityLevel() core.PriorityLevel {
return o.level
}
// IsFinish checks if all steps are finished.
func (o *Operator) IsFinish() bool {
return atomic.LoadInt32(&o.currentStep) >= int32(len(o.steps))
}
// IsTimeout checks the operator's create time ... | {
o.level = level
} | identifier_body |
operator.go | // Copyright 2016 PingCAP, 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 i... | return "split region"
}
// IsFinish checks if current step is finished.
func (sr SplitRegion) IsFinish(region *core.RegionInfo) bool {
return !bytes.Equal(region.StartKey, sr.StartKey) || !bytes.Equal(region.EndKey, sr.EndKey)
}
// Influence calculates the store difference that current step make.
func (sr SplitRegi... |
func (sr SplitRegion) String() string { | random_line_split |
operator.go | // Copyright 2016 PingCAP, 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 i... |
// Remove redundant peers.
for _, peer := range sourcePeers {
if _, ok := storeIDs[peer.GetStoreId()]; ok {
continue
}
steps = append(steps, RemovePeer{FromStore: peer.GetStoreId()})
kind |= OpRegion
}
return steps, kind, nil
}
// getIntersectionStores returns the stores included in two region's peer... | {
steps = append(steps, TransferLeader{FromStore: source.Leader.GetStoreId(), ToStore: target.Leader.GetStoreId()})
kind |= OpLeader
} | conditional_block |
operator.go | // Copyright 2016 PingCAP, 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 i... | () string {
return fmt.Sprintf("merge region %v into region %v", mr.FromRegion.GetId(), mr.ToRegion.GetId())
}
// IsFinish checks if current step is finished
func (mr MergeRegion) IsFinish(region *core.RegionInfo) bool {
if mr.IsPassive {
return bytes.Compare(region.Region.StartKey, mr.ToRegion.StartKey) != 0 || b... | String | identifier_name |
date.rs | // This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (chrono) Datelike Timelike ; (format) DATEFILE MMDDhhmm ; (vars) datetime datetimes
use chrono::format::{Item,... | {
Date,
Seconds,
Ns,
}
impl<'a> From<&'a str> for Rfc3339Format {
fn from(s: &str) -> Self {
match s {
DATE => Self::Date,
SECONDS => Self::Seconds,
NS => Self::Ns,
// Should be caught by clap
_ => panic!("Invalid format: {s}"),
... | Rfc3339Format | identifier_name |
date.rs | // This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// spell-checker:ignore (chrono) Datelike Timelike ; (format) DATEFILE MMDDhhmm ; (vars) datetime datetimes
use chrono::format::{Item,... | Err(USimpleError::new(
1,
"setting the date is not supported by macOS".to_string(),
))
}
#[cfg(target_os = "redox")]
fn set_system_datetime(_date: DateTime<Utc>) -> UResult<()> {
Err(USimpleError::new(
1,
"setting the date is not supported by Redox".to_string(),
))
}
#[... | random_line_split | |
registry.go | package polaris
import (
"context"
"fmt"
"net"
"net/url"
"strconv"
"time"
"github.com/google/uuid"
"github.com/polarismesh/polaris-go"
"github.com/polarismesh/polaris-go/pkg/model"
"github.com/go-kratos/kratos/v2/registry"
)
var (
_ registry.Registrar = (*Registry)(nil)
_ registry.Discovery = (*Registry... | (timeout time.Duration) RegistryOption {
return func(o *registryOptions) { o.Timeout = timeout }
}
// WithRegistryRetryCount with RetryCount option.
func WithRegistryRetryCount(retryCount int) RegistryOption {
return func(o *registryOptions) { o.RetryCount = retryCount }
}
// Register the registration.
func (r *Reg... | WithRegistryTimeout | identifier_name |
registry.go | package polaris
import (
"context"
"fmt"
"net"
"net/url"
"strconv"
"time"
"github.com/google/uuid"
"github.com/polarismesh/polaris-go"
"github.com/polarismesh/polaris-go/pkg/model"
"github.com/go-kratos/kratos/v2/registry"
)
var (
_ registry.Registrar = (*Registry)(nil)
_ registry.Discovery = (*Registry... | }
}
}
}
// handle AddEvent
if instanceEvent.AddEvent != nil {
for _, instance := range instanceEvent.AddEvent.Instances {
if v, ok := w.ServiceInstances[instance.GetMetadata()["merge"]]; ok {
var nv []model.Instance
m := map[string]model.Instance{}
for _, in... | w.ServiceInstances[update.After.GetMetadata()["merge"]] = []model.Instance{update.After} | random_line_split |
registry.go | package polaris
import (
"context"
"fmt"
"net"
"net/url"
"strconv"
"time"
"github.com/google/uuid"
"github.com/polarismesh/polaris-go"
"github.com/polarismesh/polaris-go/pkg/model"
"github.com/go-kratos/kratos/v2/registry"
)
var (
_ registry.Registrar = (*Registry)(nil)
_ registry.Discovery = (*Registry... |
// WithRegistryTimeout with Timeout option.
func WithRegistryTimeout(timeout time.Duration) RegistryOption {
return func(o *registryOptions) { o.Timeout = timeout }
}
// WithRegistryRetryCount with RetryCount option.
func WithRegistryRetryCount(retryCount int) RegistryOption {
return func(o *registryOptions) { o.R... | {
return func(o *registryOptions) { o.TTL = TTL }
} | identifier_body |
registry.go | package polaris
import (
"context"
"fmt"
"net"
"net/url"
"strconv"
"time"
"github.com/google/uuid"
"github.com/polarismesh/polaris-go"
"github.com/polarismesh/polaris-go/pkg/model"
"github.com/go-kratos/kratos/v2/registry"
)
var (
_ registry.Registrar = (*Registry)(nil)
_ registry.Discovery = (*Registry... |
return serviceInstances
}
| {
if len(inss) == 0 {
continue
}
ins := ®istry.ServiceInstance{
ID: inss[0].GetId(),
Name: inss[0].GetService(),
Version: inss[0].GetVersion(),
Metadata: inss[0].GetMetadata(),
}
for _, item := range inss {
if item.IsHealthy() {
ins.Endpoints = append(ins.Endpoints, fmt.Spr... | conditional_block |
device_route.go | /*
* Copyright 2020-present Open Networking Foundation
*
* 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 applicabl... | (route []Hop) []Hop {
reverse := make([]Hop, len(route))
for i, j := 0, len(route)-1; j >= 0; i, j = i+1, j-1 {
reverse[i].DeviceID, reverse[i].Ingress, reverse[i].Egress = route[j].DeviceID, route[j].Egress, route[j].Ingress
}
return reverse
}
| getReverseRoute | identifier_name |
device_route.go | /*
* Copyright 2020-present Open Networking Foundation
*
* 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 applicabl... |
//concatDeviceIdPortId formats a portid using the device id and the port number
func concatDeviceIDPortID(deviceID string, portNo uint32) string {
return fmt.Sprintf("%s:%d", deviceID, portNo)
}
//getReverseRoute returns the reverse of the route
func getReverseRoute(route []Hop) []Hop {
reverse := make([]Hop, len(... | {
dr.rootPortsLock.Lock()
dr.RootPorts = make(map[uint32]uint32)
dr.rootPortsLock.Unlock()
// Do not numGetDeviceCalledLock Routes, logicalPorts as the callee function already holds its numGetDeviceCalledLock.
dr.Routes = make(map[PathID][]Hop)
dr.logicalPorts = make([]*voltha.LogicalPort, 0)
dr.devicesPonPorts... | identifier_body |
device_route.go | /*
* Copyright 2020-present Open Networking Foundation
*
* 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 applicabl... |
}
}
if copyFromNNIPort == nil {
// Trying to add the same NNI port. Just return
return nil
}
// Adding NNI Port? If we are here we already have an NNI port with a set of routes. Just copy the existing
// routes using an existing NNI port
if lp.RootPort {
dr.copyFromExistingNNIRoutes(lp, copyFromNNI... | {
copyFromNNIPort = lport
} | conditional_block |
device_route.go | /*
* Copyright 2020-present Open Networking Foundation
*
* 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 applicabl... | dr.logicalPorts = append(dr.logicalPorts, lp)
nniLogicalPortExist = nniLogicalPortExist || lp.RootPort
uniLogicalPortExist = uniLogicalPortExist || !lp.RootPort
}
// If we do not have both NNI and UNI ports then return an error
if !(nniLogicalPortExist && uniLogicalPortExist) {
fmt.Println("errors", nniLogi... | break
}
}
if !exist { | random_line_split |
controller.go | /*
Copyright 2020 The cert-manager 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... | }
return nil
})
g.Go(func() error {
log.V(logf.InfoLevel).Info("starting profiler", "address", profilerLn.Addr())
if err := profilerServer.Serve(profilerLn); err != http.ErrServerClosed {
return err
}
return nil
})
}
elected := make(chan struct{})
if opts.LeaderElect {
g.Go(func() erro... | if err := profilerServer.Shutdown(ctx); err != nil {
return err | random_line_split |
controller.go | /*
Copyright 2020 The cert-manager 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... | {
// Identity used to distinguish between multiple controller manager instances
id, err := os.Hostname()
if err != nil {
return fmt.Errorf("error getting hostname: %v", err)
}
// Set up Multilock for leader election. This Multilock is here for the
// transitionary period from configmaps to leases see
// https... | identifier_body | |
controller.go | /*
Copyright 2020 The cert-manager 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... |
kubeCfg.QPS = opts.KubernetesAPIQPS
kubeCfg.Burst = opts.KubernetesAPIBurst
// Add User-Agent to client
kubeCfg = rest.AddUserAgent(kubeCfg, util.CertManagerUserAgent)
// Create a cert-manager api client
intcl, err := clientset.NewForConfig(kubeCfg)
if err != nil {
return nil, nil, fmt.Errorf("error creati... | {
return nil, nil, fmt.Errorf("error creating rest config: %s", err.Error())
} | conditional_block |
controller.go | /*
Copyright 2020 The cert-manager 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... | (ctx context.Context, opts *options.ControllerOptions) (*controller.Context, *rest.Config, error) {
log := logf.FromContext(ctx, "build-context")
// Load the users Kubernetes config
kubeCfg, err := clientcmd.BuildConfigFromFlags(opts.APIServerHost, opts.Kubeconfig)
if err != nil {
return nil, nil, fmt.Errorf("err... | buildControllerContext | identifier_name |
agvCtrl.py | #coding=utf-8
# ycat 2017-10-20 create
# AGV的控制
import sys,os
import json
import setup
if __name__ == '__main__':
setup.setCurPath(__file__)
import utility
import enhance
import threading
import time
import log
import re
import lock
import json_codec
import driver.agv.hdcAgvApi as api
g_threads =[]
g_carts = No... | global g_carts
p = os.path.dirname(__file__)
pp = "cart.cfg"
if p:
pp = p+"/"+pp
json_codec.dump_file(pp,g_carts)
def findCart(scanId):
global g_carts
for c in g_carts:
if g_carts[c] == scanId:
return c
return "unknown"
global g_carts
if g_carts is None:
loadCart()
if cartId in g_... | def saveCart(): | random_line_split |
agvCtrl.py | #coding=utf-8
# ycat 2017-10-20 create
# AGV的控制
import sys,os
import json
import setup
if __name__ == '__main__':
setup.setCurPath(__file__)
import utility
import enhance
import threading
import time
import log
import re
import lock
import json_codec
import driver.agv.hdcAgvApi as api
g_threads =[]
g_carts = No... | _col4")
assert resulta== "begin_1"
resultb= getPoint("StockA_row8_col4")
assert resultb == "begin_2"
def testgetOrginPoint():
resulta= getOriginPoint("begin_1")
assert resulta== "StockA_row7_col4"
resultb= getOriginPoint("begin_2")
assert resultb == "StockA_row8_col4"
resultc = getOriginPoint("hhahahaa")
a... | kA_row7 | identifier_name |
agvCtrl.py | #coding=utf-8
# ycat 2017-10-20 create
# AGV的控制
import sys,os
import json
import setup
if __name__ == '__main__':
setup.setCurPath(__file__)
import utility
import enhance
import threading
import time
import log
import re
import lock
import json_codec
import driver.agv.hdcAgvApi as api
g_threads =[]
g_carts = No... | int():
resulta= getPoint("StockA_row7_col4")
assert resulta== "begin_1"
resultb= getPoint("StockA_row8_col4")
assert resultb == "begin_2"
def testgetOrginPoint():
resulta= getOriginPoint("begin_1")
assert resulta== "StockA_row7_col4"
resultb= getOriginPoint("begin_2")
assert resultb == "StockA_row8_col4"
re... | agvId2 = api.getAgvId(agvId)
api.reset(agvId2)
def Init():
import interface.dashboard.dashboardApi
locationEvent.connect(interface.dashboard.dashboardApi.reportAgvLoc)
time.sleep(3)
################# unit test #################
def testgetPo | identifier_body |
agvCtrl.py | #coding=utf-8
# ycat 2017-10-20 create
# AGV的控制
import sys,os
import json
import setup
if __name__ == '__main__':
setup.setCurPath(__file__)
import utility
import enhance
import threading
import time
import log
import re
import lock
import json_codec
import driver.agv.hdcAgvApi as api
g_threads =[]
g_carts = No... | ow%2 != 1:
row -= 1
return row*1000+col
@lock.lock(g_lock)
def checkTimeout(index,agvId,loc):
global g_stockLock
if index in g_stockLock:
if utility.ticks() - g_stockLock[index] > 10*60*1000:
unlockStockA(agvId,loc)
log.warning("delete timeout locked",index)
#解决在StockA两个车头对撞的问题
def lockStockA(agv... |
if r | conditional_block |
Exam4x2.py | from os import system
class paciente:
def __init__(self, nombre, apellido, nacimiento, pais, genero, edad):
self.nombre = nombre
self.apellido = apellido
self.nacimiento = nacimiento
self.pais = pais
self.edad = edad
if genero == "1":
self.gen... | m('cls')
nombre = input('Nombre: ')
apellido = input('Apellido: ')
fecha = input('Fecha de nacimiento: ')
pais = input('Pais de procedencia: ')
while True:
try:
edad = int(input('Edad: '))
if edad... | Principal()
genero = input('Opcion Incorrecta')
syste | conditional_block |
Exam4x2.py | from os import system
class paciente:
def __init__(self, nombre, apellido, nacimiento, pais, genero, edad):
self.nombre = nombre
self.apellido = apellido
self.nacimiento = nacimiento
self.pais = pais
self.edad = edad
if genero == "1":
self.gen... | le opc != '0':
system('cls')
print('\033[1:35m ')
print('|///////////////////|')
print('| COVID-19 |')
print('|///////////////////|')
print('\033[0:0m ')
print('''1) Acerca de Coronavirus
2) Agregar un Paciente
3) Mostrar Todos los Pacientes
4) ... | identifier_body | |
Exam4x2.py | from os import system
class paciente:
def __init__(self, nombre, apellido, nacimiento, pais, genero, edad):
self.nombre = nombre
self.apellido = apellido
self.nacimiento = nacimiento
self.pais = pais
self.edad = edad
if genero == "1":
self.gen... | print('\033[0:0m ')
print('''La COVID-19 se caracteriza por síntomas leves, como, secreciones nasales, dolor de garganta,
tos y fiebre. La enfermedad puede ser más grave en algunas personas y provocar neumonía
o dificultades respiratorias.
Más raramente puede ser mortal. Las personas de edad avanzada y la... | print('\033[1:30m ')
print('Sintomas:')
| random_line_split |
Exam4x2.py | from os import system
class paciente:
def __init__(self, nombre, apellido, nacimiento, pais, genero, edad):
self.nombre = nombre
self.apellido = apellido
self.nacimiento = nacimiento
self.pais = pais
self.edad = edad
if genero == "1":
self.gen... | (self):
system('cls')
print('\033[1:31m ')
print('|///////////////////|')
print('| MOSTRAR PACIENTES |')
print('|///////////////////|')
print('\033[0:0m ')
return f'\nGenero: {self.genero}\nNombre: {self.nombre}\nApellido: {self.apellido}' \
... | mostrar | identifier_name |
Simulated_Image_PD_points.py | # -*- coding: utf-8 -*-
import scipy.io
import numpy as np
import matplotlib.pylab as plt
from pykrige.ok import OrdinaryKriging
import time
# Define the function for computing Padova points
def _pdpts(n):
zn = np.cos(np.linspace(0, 1, n+1)*np.pi)
zn1 = np.cos(np.linspace(0, 1, n+2)*np.pi)
Pad1, Pad2 = n... |
plt.savefig('%s.eps' %fig_name,bbox_inches='tight')
plt.savefig('%s.png' %fig_name,bbox_inches='tight')
plt.close()
# Load the image
matr = scipy.io.loadmat('sm_simulata.mat')
Image_large = matr["image_temp"]
plot_image(Image_large, 'Simulated_ImageLarge')
sx, sy = Image_large.shape
lx, rx, ly, ry = 1... | plt.plot(pts[0], pts[1], 'r.') | conditional_block |
Simulated_Image_PD_points.py | # -*- coding: utf-8 -*-
import scipy.io
import numpy as np
import matplotlib.pylab as plt
from pykrige.ok import OrdinaryKriging
import time
# Define the function for computing Padova points
def | (n):
zn = np.cos(np.linspace(0, 1, n+1)*np.pi)
zn1 = np.cos(np.linspace(0, 1, n+2)*np.pi)
Pad1, Pad2 = np.meshgrid(zn, zn1)
f1 = np.linspace(0, n, n+1)
f2 = np.linspace(0, n+1, n+2)
M1, M2 = np.meshgrid(f1,f2)
h = np.array(np.mod(M1 + M2, 2))
g = np.array(np.concatenate(h.T))
findM ... | _pdpts | identifier_name |
Simulated_Image_PD_points.py | # -*- coding: utf-8 -*-
import scipy.io
import numpy as np
import matplotlib.pylab as plt
from pykrige.ok import OrdinaryKriging
import time
# Define the function for computing Padova points
def _pdpts(n):
|
# Compute the coefficients for polynomial approximation
def _wamfit(deg, wam, pts, fval):
both = np.vstack((wam, pts))
rect = [np.min(both[:,0]), np.max(both[:,0]), np.min(both[:,1]), np.max(both[:,1])]
Q, R1, R2 = _wamdop(deg, wam, rect)
DOP = _wamdopeval(deg, R1, R2, pts, rect)
cfs = np... | zn = np.cos(np.linspace(0, 1, n+1)*np.pi)
zn1 = np.cos(np.linspace(0, 1, n+2)*np.pi)
Pad1, Pad2 = np.meshgrid(zn, zn1)
f1 = np.linspace(0, n, n+1)
f2 = np.linspace(0, n+1, n+2)
M1, M2 = np.meshgrid(f1,f2)
h = np.array(np.mod(M1 + M2, 2))
g = np.array(np.concatenate(h.T))
findM = np.argw... | identifier_body |
Simulated_Image_PD_points.py | # -*- coding: utf-8 -*-
import scipy.io
import numpy as np
import matplotlib.pylab as plt
from pykrige.ok import OrdinaryKriging
import time
# Define the function for computing Padova points
def _pdpts(n):
zn = np.cos(np.linspace(0, 1, n+1)*np.pi)
zn1 = np.cos(np.linspace(0, 1, n+2)*np.pi)
Pad1, Pad2 = n... | # Define the evaluation points
X, Y = np.meshgrid(range(n), range(m));
x = X.T.flatten()
y = Y.T.flatten()
pts = np.vstack((x,y)).T
ptsv = np.vstack((np.array(x/(n-1)), np.array(y/(m-1)))).T
fvalev = np.array([Image[y[i], x[i]] for i in range(x.shape[0])])
threshold = fvalev > 0
extra_ep = np.zeros(Image.flatten().sha... | MSE_VSDK, MSE_POLY = [], []
PSNR_VSDK, PSNR_POLY = [], []
| random_line_split |
workerthread.rs | // Copyright (c) 2015-2016 Linus Färnstrand.
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be co... | Ret> {
ptr_0: *mut Ret,
offset: isize,
}
impl<Ret> Iterator for PtrIter<Ret> {
type Item = Unique<Ret>;
fn next(&mut self) -> Option<Self::Item> {
let ptr = unsafe { Unique::new(self.ptr_0.offset(self.offset)) };
self.offset += 1;
Some(ptr)
}
}
| trIter< | identifier_name |
workerthread.rs | // Copyright (c) 2015-2016 Linus Färnstrand.
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be co... | }
ResultReceiver::Channel(channel) => {
channel.lock().unwrap().send(value).unwrap();
}
}
}
}
#[cfg(feature = "threadstats")]
impl<Arg: Send, Ret: Send + Sync> Drop for WorkerThread<Arg, Ret> {
fn drop(&mut self) {
println!("Worker[{}] (t: {},... |
mem::forget(joinbarrier) // Don't drop if we are not last task
}
| conditional_block |
workerthread.rs | // Copyright (c) 2015-2016 Linus Färnstrand.
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be co... | }
|
let ptr = unsafe { Unique::new(self.ptr_0.offset(self.offset)) };
self.offset += 1;
Some(ptr)
}
| identifier_body |
workerthread.rs | // Copyright (c) 2015-2016 Linus Färnstrand.
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be co... | /// Try to steal tasks from the other workers.
/// Starts at a random worker and tries every worker until a task is stolen or
/// every worker has been tried once.
fn try_steal(&mut self) -> Option<Task<Arg,Ret>> {
let len = self.other_stealers.len();
let start_victim = self.rng.gen_rang... | }
}
| random_line_split |
server.go | package viewservice
import "net"
import "net/rpc"
import "log"
import "time"
import "sync"
import "fmt"
import (
"os"
"strconv"
)
type ViewServer struct {
mu sync.Mutex
l net.Listener
dead bool
me string
currentView View
acked bool
idle []string
pingKeeper map[string]time.Time
viewMu sync.Mutex
}... |
func idleContains(idle []string, target string) bool {
for _, server := range idle {
if server == target {
return true
}
}
return false
} | {
vs := new(ViewServer)
vs.me = me
// Your vs.* initializations here.
vs.idle = make([]string, 0)
vs.currentView = View{0, "", ""}
vs.acked = false
vs.pingKeeper = make(map[string]time.Time)
// tell net/rpc about our RPC server and handlers.
rpcs := rpc.NewServer()
rpcs.Register(vs)
// prepare to receive c... | identifier_body |
server.go | package viewservice
import "net"
import "net/rpc"
import "log"
import "time"
import "sync"
import "fmt"
import (
"os"
"strconv"
)
type ViewServer struct {
mu sync.Mutex
l net.Listener
dead bool
me string
currentView View
acked bool
idle []string
pingKeeper map[string]time.Time
viewMu sync.Mutex
}... | if vs.currentView.Backup != "" {
// fmt.Println("Put backup: ", vs.currentView.Backup, " in")
// Turn backup into primary
vs.currentView.Primary = vs.currentView.Backup
vs.currentView.Backup = ""
// Turn idle into backup
if len(vs.idle) > 0 {
// fmt.Println("TEST #150: ", ... | random_line_split | |
server.go | package viewservice
import "net"
import "net/rpc"
import "log"
import "time"
import "sync"
import "fmt"
import (
"os"
"strconv"
)
type ViewServer struct {
mu sync.Mutex
l net.Listener
dead bool
me string
currentView View
acked bool
idle []string
pingKeeper map[string]time.Time
viewMu sync.Mutex
}... | else {
// If already has backup
// put it into idle
// fmt.Println("TEST #600: put", args.Me, " in idle")
if !idleContains(vs.idle, args.Me) {
vs.idle = append(vs.idle, args.Me)
}
}
}
}
}
// Set up the return view
vs.pingKeeper[args.Me] = time.Now()
reply.View = vs.currentVi... | {
// If no backup
// put ping server into backup and set acked = false
// fmt.Println("Before backup added: ", vs.currentView)
// fmt.Println("Add backup: ", args.Me)
if (idleContains(vs.idle, args.Me)) {
vs.currentView.Backup = vs.idle[0]
vs.idle = vs.idle[1:]
} else {
vs.... | conditional_block |
server.go | package viewservice
import "net"
import "net/rpc"
import "log"
import "time"
import "sync"
import "fmt"
import (
"os"
"strconv"
)
type ViewServer struct {
mu sync.Mutex
l net.Listener
dead bool
me string
currentView View
acked bool
idle []string
pingKeeper map[string]time.Time
viewMu sync.Mutex
}... | (message string) {
// Log the put operation into log file.
f, err := os.OpenFile("TestLog.txt", os.O_APPEND|os.O_RDWR|os.O_CREATE , 0777)
if err != nil {
panic(err)
}
defer f.Close()
if _, err = f.WriteString(message + "\n"); err != nil {
panic(err)
}
}
func (vs *ViewServer) increaseViewNum() {
testLog("... | testLog | identifier_name |
listener.go | // Copyright 2017 Jump Trading
//
// 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... |
func (l *Listener) handleNatsError(err error) {
log.Printf("NATS Error: %v\n", err)
}
func (l *Listener) startStatistician() {
defer l.wg.Done()
labels := stats.NewLabels("listener", l.c.Name)
for {
lines := stats.SnapshotToPrometheus(l.stats.Snapshot(), time.Now(), labels)
l.nc.Publish(l.c.NATSSubjectMonito... | {
if l.batch.Size() < 1 {
return // Nothing to do
}
l.stats.Inc(statSent)
// The goal is for the batch size to never be bigger than what
// NATS will accept but there is a small chance that a series of
// large incoming chunks could cause the batch to grow beyond the
// intended limit. For these cases, use t... | identifier_body |
listener.go | // Copyright 2017 Jump Trading
//
// 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... |
}
func (l *Listener) setupHTTP() *http.Server {
l.wg.Add(1)
go l.oldBatchSender()
mux := http.NewServeMux()
mux.HandleFunc("/write", l.handleHTTPWrite)
return &http.Server{
Addr: fmt.Sprintf(":%d", l.c.Port),
Handler: mux,
}
}
// oldBatchSender is a goroutine which sends the batch when it reached
// th... | {
// Read deadline is used so that the stop channel can be
// periodically checked.
sc.SetReadDeadline(time.Now().Add(time.Second))
bytesRead, err := l.batch.ReadOnceFrom(sc)
if err != nil && !isTimeout(err) {
l.stats.Inc(statReadErrors)
}
if bytesRead > 0 {
if l.c.Debug {
log.Printf("listener r... | conditional_block |
listener.go | // Copyright 2017 Jump Trading
//
// 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... | (r *http.Request) (int64, error) {
l.mu.Lock()
defer l.mu.Unlock()
return l.batch.ReadFrom(r.Body)
}
func (l *Listener) readHTTPBodyWithPrecision(r *http.Request, precision string) (int, error) {
scanner := bufio.NewScanner(r.Body)
// scanLines is like bufio.ScanLines but the returned lines
// includes the trai... | readHTTPBodyNanos | identifier_name |
listener.go | // Copyright 2017 Jump Trading
//
// 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... | continue
}
newLine := applyTimestampPrecision(line, precision)
l.mu.Lock()
l.batch.Append(newLine)
l.mu.Unlock()
}
return bytesRead, scanner.Err()
}
func scanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.Inde... | random_line_split | |
messages.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ssh
import (
"bytes"
"io"
"math/big"
"reflect"
)
// These are SSH message type numbers. They are scattered around several
// documents but many we... | else {
bitLen := n.BitLen()
if bitLen%8 == 0 {
// The number will need 0x00 padding
length++
}
length += (bitLen + 7) / 8
}
return length
}
func marshalUint32(to []byte, n uint32) []byte {
to[0] = byte(n >> 24)
to[1] = byte(n >> 16)
to[2] = byte(n >> 8)
to[3] = byte(n)
return to[4:]
}
func mars... | {
// A zero is the zero length string
} | conditional_block |
messages.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ssh
import (
"bytes"
"io"
"math/big"
"reflect"
)
// These are SSH message type numbers. They are scattered around several
// documents but many we... | (in []byte) (out uint32, rest []byte, ok bool) {
if len(in) < 4 {
return
}
out = uint32(in[0])<<24 | uint32(in[1])<<16 | uint32(in[2])<<8 | uint32(in[3])
rest = in[4:]
ok = true
return
}
func nameListLength(namelist []string) int {
length := 4 /* uint32 length prefix */
for i, name := range namelist {
if i... | parseUint32 | identifier_name |
messages.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ssh
import (
"bytes"
"io"
"math/big"
"reflect"
)
// These are SSH message type numbers. They are scattered around several
// documents but many we... | return out
}
var bigOne = big.NewInt(1)
func parseString(in []byte) (out, rest []byte, ok bool) {
if len(in) < 4 {
return
}
length := uint32(in[0])<<24 | uint32(in[1])<<16 | uint32(in[2])<<8 | uint32(in[3])
if uint32(len(in)) < 4+length {
return
}
out = in[4 : 4+length]
rest = in[4+length:]
ok = true
re... | random_line_split | |
messages.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ssh
import (
"bytes"
"io"
"math/big"
"reflect"
)
// These are SSH message type numbers. They are scattered around several
// documents but many we... |
func marshalUint32(to []byte, n uint32) []byte {
to[0] = byte(n >> 24)
to[1] = byte(n >> 16)
to[2] = byte(n >> 8)
to[3] = byte(n)
return to[4:]
}
func marshalUint64(to []byte, n uint64) []byte {
to[0] = byte(n >> 56)
to[1] = byte(n >> 48)
to[2] = byte(n >> 40)
to[3] = byte(n >> 32)
to[4] = byte(n >> 24)
t... | {
length := 4 /* length bytes */
if n.Sign() < 0 {
nMinus1 := new(big.Int).Neg(n)
nMinus1.Sub(nMinus1, bigOne)
bitLen := nMinus1.BitLen()
if bitLen%8 == 0 {
// The number will need 0xff padding
length++
}
length += (bitLen + 7) / 8
} else if n.Sign() == 0 {
// A zero is the zero length string
} ... | identifier_body |
siadir.go | package siadir
import (
"encoding/json"
"io/ioutil"
"os"
"sync"
"time"
"gitlab.com/NebulousLabs/errors"
"gitlab.com/NebulousLabs/writeaheadlog"
"gitlab.com/NebulousLabs/Sia/modules"
)
const (
// SiaDirExtension is the name of the metadata file for the sia directory
SiaDirExtension = ".siadir"
// Default... |
// Delete removes the directory from disk and marks it as deleted. Once the directory is
// deleted, attempting to access the directory will return an error.
func (sd *SiaDir) Delete() error {
sd.mu.Lock()
defer sd.mu.Unlock()
return sd.delete()
}
// Deleted returns the deleted field of the siaDir
func (sd *SiaDi... | {
update := sd.createDeleteUpdate()
err := sd.createAndApplyTransaction(update)
sd.deleted = true
return err
} | identifier_body |
siadir.go | package siadir
import (
"encoding/json"
"io/ioutil"
"os"
"sync"
"time"
"gitlab.com/NebulousLabs/errors"
"gitlab.com/NebulousLabs/writeaheadlog"
"gitlab.com/NebulousLabs/Sia/modules"
)
const (
// SiaDirExtension is the name of the metadata file for the sia directory
SiaDirExtension = ".siadir"
// Default... | (b []byte) (int, error) {
return sdr.f.Read(b)
}
// Stat returns the FileInfo of the underlying file.
func (sdr *DirReader) Stat() (os.FileInfo, error) {
return sdr.f.Stat()
}
// New creates a new directory in the renter directory and makes sure there is a
// metadata file in the directory and creates one as needed... | Read | identifier_name |
siadir.go | package siadir
import (
"encoding/json"
"io/ioutil"
"os"
"sync"
"time"
"gitlab.com/NebulousLabs/errors"
"gitlab.com/NebulousLabs/writeaheadlog"
"gitlab.com/NebulousLabs/Sia/modules"
)
const (
// SiaDirExtension is the name of the metadata file for the sia directory
SiaDirExtension = ".siadir"
// Default... |
// Open file.
path := sd.siaPath.SiaDirMetadataSysPath(sd.rootDir)
f, err := os.Open(path)
if err != nil {
sd.mu.Unlock()
return nil, err
}
return &DirReader{
sd: sd,
f: f,
}, nil
}
// Metadata returns the metadata of the SiaDir
func (sd *SiaDir) Metadata() Metadata {
sd.mu.Lock()
defer sd.mu.Unlock... | {
sd.mu.Unlock()
return nil, errors.New("can't copy deleted SiaDir")
} | conditional_block |
siadir.go | package siadir
import (
"encoding/json"
"io/ioutil"
"os"
"sync"
"time"
"gitlab.com/NebulousLabs/errors"
"gitlab.com/NebulousLabs/writeaheadlog"
"gitlab.com/NebulousLabs/Sia/modules"
)
const (
// SiaDirExtension is the name of the metadata file for the sia directory
SiaDirExtension = ".siadir"
// Default... | sd.mu.Unlock()
return nil, err
}
return &DirReader{
sd: sd,
f: f,
}, nil
}
// Metadata returns the metadata of the SiaDir
func (sd *SiaDir) Metadata() Metadata {
sd.mu.Lock()
defer sd.mu.Unlock()
return sd.metadata
}
// SiaPath returns the SiaPath of the SiaDir
func (sd *SiaDir) SiaPath() modules.SiaPa... | }
// Open file.
path := sd.siaPath.SiaDirMetadataSysPath(sd.rootDir)
f, err := os.Open(path)
if err != nil { | random_line_split |
fpdf.go | // Provides routines to render flights as PDFs in various ways
package fpdf
import(
"fmt"
"io"
"math"
"time"
"github.com/jung-kurt/gofpdf" // https://godoc.org/github.com/jung-kurt/gofpdf
"github.com/skypies/geo/sfo"
fdb "github.com/skypies/flightdb"
)
type ColorScheme int
const(
ByGroundspeed ColorScheme = i... |
// }}}
// {{{ altitudeToY, distNMToX
func altitudeToY(alt float64) float64 {
distY := (alt/ApproachHeightFeet) * ApproachBoxHeight
y := ApproachBoxHeight - distY // In PDF, the Y scale goes down the page
return y + ApproachBoxOffsetY
}
func distNMToX(distNM float64) float64 {
distX := (distNM/ApproachWidthNM) * ... | {
f := delta / 4.0 // How many 5knot increments this delta is
f += 3.0 // [0,1,2] are braking, [3] is nochange, [4,5,6] are accelerating
i := int(f)
if i<0 { i = 0 }
if i>6 { i = 6 }
rgbw := DeltaGradientColors[i]
fAbs := math.Abs(delta/4.0)
widthPercent := int (fAbs * 0.33 * 100)
if widthPercent ... | identifier_body |
fpdf.go | // Provides routines to render flights as PDFs in various ways
package fpdf
import(
"fmt"
"io"
"math"
"time"
"github.com/jung-kurt/gofpdf" // https://godoc.org/github.com/jung-kurt/gofpdf
"github.com/skypies/geo/sfo"
fdb "github.com/skypies/flightdb"
)
type ColorScheme int
const(
ByGroundspeed ColorScheme = i... | DrawTrack(pdf, t, ByGroundspeed)
return pdf.Output(output)
}
// }}}
// {{{ WriteFlight
func WriteFlight(output io.Writer, f fdb.Flight) error {
pdf := NewApproachPdf(ByGroundspeed)
pdf.MoveTo(10, ApproachBoxHeight + ApproachBoxOffsetY+12)
pdf.Cell(40, 10, fmt.Sprintf("%s", f))
DrawTrack(pdf, f.AnyTrack(), ByG... | random_line_split | |
fpdf.go | // Provides routines to render flights as PDFs in various ways
package fpdf
import(
"fmt"
"io"
"math"
"time"
"github.com/jung-kurt/gofpdf" // https://godoc.org/github.com/jung-kurt/gofpdf
"github.com/skypies/geo/sfo"
fdb "github.com/skypies/flightdb"
)
type ColorScheme int
const(
ByGroundspeed ColorScheme = i... | (colorscheme ColorScheme) *gofpdf.Fpdf {
pdf := gofpdf.New("L", "mm", "Letter", "")
pdf.AddPage()
pdf.SetFont("Arial", "", 10)
DrawApproachFrame(pdf)
DrawSFOClassB(pdf)
DrawWaypoints(pdf)
if colorscheme == ByDeltaGroundspeed {
DrawDeltaGradientKey(pdf)
} else {
DrawSpeedGradientKey(pdf)
}
return pdf
}
... | NewApproachPdf | identifier_name |
fpdf.go | // Provides routines to render flights as PDFs in various ways
package fpdf
import(
"fmt"
"io"
"math"
"time"
"github.com/jung-kurt/gofpdf" // https://godoc.org/github.com/jung-kurt/gofpdf
"github.com/skypies/geo/sfo"
fdb "github.com/skypies/flightdb"
)
type ColorScheme int
const(
ByGroundspeed ColorScheme = i... |
x1,y1 := trackpointToApproachXY(t[i])
x2,y2 := trackpointToApproachXY(t[i+1])
// ... or compare against x2/y2 and clip against frame ...
if x1 < ApproachBoxOffsetX { continue }
if y1 < ApproachBoxOffsetY { continue }
rgb := []int{0xFF,0x00,0x00}
switch colorscheme {
case ByGroundspeed: rgb = groundsp... | { continue } | conditional_block |
auth.go | /*******************************************************************************
* Authentication and authorization.
*
* Copyright Scaled Markets, Inc.
*/
package server
import (
"fmt"
"net/http"
//"os"
"strings"
//"crypto/tls"
"crypto/x509"
"time"
//"errors"
"crypto/sha256"
//"crypto/sha512"
"hash"
/... |
action = i
}
}
if action == -1 { return false, nil } // no action mask fields were set.
var entries []string = party.getACLEntryIds()
for _, entryId := range entries { // for each of the party's ACL entries...
var entry ACLEntry
var err error
entry, err = dbClient.getACLEntry(entryId)
if err !=... | { return false, utilities.ConstructUserError("More than one field set in action mask") } | conditional_block |
auth.go | /*******************************************************************************
* Authentication and authorization.
*
* Copyright Scaled Markets, Inc.
*/
package server
import (
"fmt"
"net/http"
//"os"
"strings"
//"crypto/tls"
"crypto/x509"
"time"
//"errors"
"crypto/sha256"
//"crypto/sha512"
"hash"
/... |
/*******************************************************************************
* Return a session id that is guaranteed to be unique, and that is completely
* opaque and unforgeable. See also validateSessionId.
*/
func (authSvc *AuthService) createUniqueSessionId() string {
var uniqueNonRandomValue string = f... | {
var parts []string = strings.Split(sessionId, ":")
if len(parts) != 2 {
fmt.Println("Ill-formatted sessionId:", sessionId)
return false
}
var uniqueNonRandomValue string = parts[0]
var untrustedHash string = parts[1]
var empty = []byte{}
var actualSaltedHashBytes []byte = authSvc.computeHash(uniqueNonR... | identifier_body |
auth.go | /*******************************************************************************
* Authentication and authorization.
*
* Copyright Scaled Markets, Inc.
*/
package server
import (
"fmt"
"net/http"
//"os"
"strings"
//"crypto/tls"
"crypto/x509"
"time"
//"errors"
"crypto/sha256"
//"crypto/sha512"
"hash"
/... | if user.getId() == resourceId { return true, nil }
// Verify that at most one field of the actionMask is true.
var nTrue = 0
for _, b := range actionMask {
if b {
if nTrue == 1 {
return false, utilities.ConstructUserError("More than one field in mask may not be true")
}
nTrue++
}
}
// Check if... | }
// Special case: Allow user all capabilities for their own user object. | random_line_split |
auth.go | /*******************************************************************************
* Authentication and authorization.
*
* Copyright Scaled Markets, Inc.
*/
package server
import (
"fmt"
"net/http"
//"os"
"strings"
//"crypto/tls"
"crypto/x509"
"time"
//"errors"
"crypto/sha256"
//"crypto/sha512"
"hash"
/... | (pswd string) []byte {
var h []byte = authSvc.computeHash(pswd).Sum([]byte{})
return h
}
/*******************************************************************************
* Validate session Id: return true if valid, false otherwise. Thus, a return
* of true indicates that the sessionId is recognized as having bee... | CreatePasswordHash | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.