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
run.go
func NewFlagSet(name string) *FlagSet { return &FlagSet{ FlagSet: pflag.NewFlagSet(name, pflag.ContinueOnError), Name: name, } } // Unit is the default interface an object needs to implement for it to be able // to register with a Group. // Name should return a short but good identifier of the Unit. type Unit...
(units ...Unit) []bool { g.log = logger.GetLogger(g.name) hasRegistered := make([]bool, len(units)) for idx := range units { if !g.configured { // if RunConfig has been called we can no longer register Config // phases of Units if c, ok := units[idx].(Config); ok { g.c = append(g.c, c) hasRegister...
Register
identifier_name
run.go
configured bool } // NewGroup return a Group with input name. func NewGroup(name string) Group { return Group{ name: name, readyCh: make(chan struct{}), } } // Name shows the name of the group. func (g Group) Name() string { return g.name } // Register will inspect the provided objects implementing the...
{ var ( s string t = "cli" ) if len(g.c) > 0 { s += "\n- config: " for _, u := range g.c { if u != nil { s += u.Name() + " " } } } if len(g.p) > 0 { s += "\n- prerun: " for _, u := range g.p { if u != nil { s += u.Name() + " " }
identifier_body
run.go
. func NewFlagSet(name string) *FlagSet { return &FlagSet{ FlagSet: pflag.NewFlagSet(name, pflag.ContinueOnError), Name: name, } } // Unit is the default interface an object needs to implement for it to be able // to register with a Group. // Name should return a short but good identifier of the Unit. type Un...
fmt.Println(g.ListUnits()) return true, nil } // Validate Config inputs for idx := range g.c { // a Config might have been deregistered during Run if g.c[idx] == nil { g.log.Debug().Uint32("ran", uint32(idx+1)).Msg("skipping validate") continue } g.log.Debug().Str("name", g.c[idx].Name()).Uint32("...
case g.showRunGroup:
random_line_split
run.go
*FlagSet readyCh chan struct{} log *logger.Logger name string r run.Group c []Config p []PreRunner s []Service showRunGroup bool configured bool } // NewGroup return a Group with input name. func NewGroup(name string) Group { return Group{ ...
{ s += "\n- config: " for _, u := range g.c { if u != nil { s += u.Name() + " " } } }
conditional_block
test.pb.go
PrintKVRequest_Value `protobuf_oneof:"Value"` } func (m *PrintKVRequest) Reset() { *m = PrintKVRequest{} } func (m *PrintKVRequest) String() string { return proto.CompactTextString(m) } func (*PrintKVRequest) ProtoMessage() {} func (*PrintKVRequest) Descriptor() ([]byte, []i...
func (m *PrintKVRequest) GetValueInt() int32 { if x, ok := m.GetValue().(*PrintKVRequest_ValueInt); ok { return x.ValueInt } return 0 } // XXX_OneofFuncs is for the internal use of the proto package. func (*PrintKVRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message,...
{ if x, ok := m.GetValue().(*PrintKVRequest_ValueString); ok { return x.ValueString } return "" }
identifier_body
test.pb.go
PrintKVRequest_Value `protobuf_oneof:"Value"` } func (m *PrintKVRequest) Reset() { *m = PrintKVRequest{} } func (m *PrintKVRequest) String() string { return proto.CompactTextString(m) } func (*PrintKVRequest) ProtoMessage() {} func (*PrintKVRequest) Descriptor() ([]byte, []i...
info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/grpctest.Test/Double", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TestServer).Double(ctx, req.(*TestRequest)) } return interceptor(ctx, in, info, handler) } func _Test_PrintKV_Handler(srv interface...
{ return srv.(TestServer).Double(ctx, in) }
conditional_block
test.pb.go
isPrintKVRequest_Value `protobuf_oneof:"Value"` } func (m *PrintKVRequest) Reset() { *m = PrintKVRequest{} } func (m *PrintKVRequest) String() string { return proto.CompactTextString(m) } func (*PrintKVRequest) ProtoMessage() {} func (*PrintKVRequest) Descriptor() ([]byte, ...
} // Server API for Test service type TestServer interface { Double(context.Context, *TestRequest) (*TestResponse, error) PrintKV(context.Context, *PrintKVRequest) (*PrintKVResponse, error) } func RegisterTestServer(s *grpc.Server, srv TestServer) { s.RegisterService(&_Test_serviceDesc, srv) } func _Test_Double_...
random_line_split
test.pb.go
PrintKVRequest_Value `protobuf_oneof:"Value"` } func (m *PrintKVRequest) Reset() { *m = PrintKVRequest{} } func (m *PrintKVRequest) String() string { return proto.CompactTextString(m) } func (*PrintKVRequest) ProtoMessage() {} func (*PrintKVRequest) Descriptor() ([]byte, []i...
() ([]byte, []int) { return fileDescriptor0, []int{3} } func init() { proto.RegisterType((*TestRequest)(nil), "grpctest.TestRequest") proto.RegisterType((*TestResponse)(nil), "grpctest.TestResponse") proto.RegisterType((*PrintKVRequest)(nil), "grpctest.PrintKVRequest") proto.RegisterType((*PrintKVResponse)(nil), "...
Descriptor
identifier_name
mesintiket-gen3.py
(QtCore.QThread): update = QtCore.pyqtSignal(str) def __init__(self, tosay): QtCore.QThread.__init__(self) self.tosay = tosay def __del__(self): self.wait() def run(self): subprocess.call('espeak -vid+f3 "%s"' % self.tosay, shell=True) #~ self.terminate() class MainApp(QtCore.QObject): def __init__(se...
SpeechThread
identifier_name
mesintiket-gen3.py
_power'], '', ) logger.debug('SENDGPSINFO: %s' % gpsmsg) self.redis.rpush('mq', gpsmsg) else: logger.info('SENDGPSINFO: GPS not set, not sending position to server..') except Exception: e = sys.exc_info() logger.error('SENDGPSINFO: Error sending GPS info: %s %s' % (e[0], e[1])) def g...
self.redis.set(curdt.strftime('%Y%m%d:setoran'), 0)
conditional_block
mesintiket-gen3.py
import logging import logging.handlers logger = logging.getLogger('') logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s %(thread)d %(levelname)-5s %(message)s') fh = logging.handlers.RotatingFileHandler('log.txt', maxBytes=10000000, backupCount=5) fh.setFormatter(formatter) ch = logging.Stream...
from gpslistener import GpsListener from gpiolistener import GPIOListener from LCD40X4 import GPIO, lcd_init, lcd_goto, lcd_string, GPIO
random_line_split
mesintiket-gen3.py
# E #GPIO.setup(LCD_E2, GPIO.OUT) # E2 #GPIO.setup(LCD_RS, GPIO.OUT) # RS #GPIO.setup(LCD_D4, GPIO.OUT) # DB4 #GPIO.setup(LCD_D5, GPIO.OUT) # DB5 #GPIO.setup(LCD_D6, GPIO.OUT) # DB6 #GPIO.setup(LCD_D7, GPIO.OUT) # DB7 #GPIO.setup(LED_ON, GPIO.OUT) # Backlight enable # Initialise display lcd_init...
else: logger.info('SENDGPSINFO: GPS not set, not sending position to server..') except Exception: e = sys.exc_info() logger.error('SENDGPSINFO: Error sending GPS info: %s %s' % (e[0], e[1])) def gpsReceived(self, gpsPos): #~ print newpos logger.debug('type of gpsPos: %s %s' % (type(gpsPos), repr...
try: if self.gpsThread.lastpos: # ITPRO861001000786141,11025.595867,-659.625256,31,20121008035615.000,15,0,13,1, gprmclon = 100 *(int(self.gpsThread.lastpos['lon']) + ((self.gpsThread.lastpos['lon'] - int(self.gpsThread.lastpos['lon'])) / 100 * 60)) gprmclat = 100 *(int(self.gpsThread.lastpos['lat']) + (...
identifier_body
lp.go
(waiting, leftID) } // TODO why only in this case? } else { leftID := tree.CreateLeftChild(nextID, first.Phi, false) waiting = append(waiting, leftID) } if second.Final { if len(second.Phi) != 0 { rightID := tree.CreateRightChild(nextID, second.Phi, true) waiting = append(waiting, rightID)...
ewDNF = make([]br.Clause, len(phi)) // clone each clause // we'll do that concurrently var wg sync.WaitGroup wg.Add(len(phi)) for i := 0; i < len(phi); i++ { go func(index int) { clause := phi[index] var newClause br.Clause = make([]int, len(clause)) for j, oldID := range clause { newClaus...
renaming[row[len(row)-1]] = newVariableId reverseRenaming[newVariableId] = row[len(row)-1] } n
conditional_block
lp.go
:= len(p1) for k := 0; k < size; k++ { val1, val2 := p1[k], p2[k] if (!val1) && val2 { return true } else if val1 && (!val2) { return false } } if debug { panic("Must not reach this state in ComputeMFPs") } return false } sort.Slice(mtps, cmp) } // compute nu, we do t...
// add eq constraing entry2.Col = j
random_line_split
lp.go
(waiting, leftID) } // TODO why only in this case? } else { leftID := tree.CreateLeftChild(nextID, first.Phi, false) waiting = append(waiting, leftID) } if second.Final { if len(second.Phi) != 0 { rightID := tree.CreateRightChild(nextID, second.Phi, true) waiting = append(waiting, rightID)...
}() for k := 0; k < len(mtps); k++ { go func(index int) { mtp := mtps[index] check := true for i := 0; i < numRuns; i++ { if (!mtp[i]) && (mtp[i+1]) { // change the positions in the point, after the implicant test // we will change them again mtp[i] = true mtp[i+1] = false isIm...
{ numRuns := tree.Nbvar - 1 res := true // we will do this concurrently: // for each mtp iterate over all variable combinations and perform the test // and write the result to a channel // this also has some drawback: we need to wait for all mtps to finish // otherwise we would need some context wish would be to...
identifier_body
lp.go
); k++ { u := tree.Content[uID] if tree.IsLeaf(uID) { return true } leftChild, rightChild := u.leftChild, u.rightChild if mtp[k] { if leftChild >= 0 { uID = leftChild continue } else { if debug { if rightChild < 0 { panic("rightChild must not be nil in IsImplicant") } ...
eMTPs(phi b
identifier_name
nexus_label.rs
pub guid: GptGuid, /// lba of where to find the partition table pub lba_table: u64, /// number of partitions, most tools set this to 128 pub num_entries: u32, /// Size of element pub entry_size: u32, /// CRC32 checksum of the partition array. pub table_crc: u32, } impl GPTHeader { ...
t mut out = Vec::new(); let mut end = false; loop { match seq.next_element()? { Some(0) => { end = true; } Some(e) if !end => out.push(e), _ => break, } } if end { Ok(...
identifier_body
nexus_label.rs
4.0 MiB FFFF MayaMeta //! 2 10240 2097118 1019.0 MiB FFFF MayaData //! ``` //! //! Notice how two partitions have been created when accessing the disk //! when shared by the nexus: //! //! ```bash //! $ mctl share gpt //! "/dev/nbd0" //! //! TODO: also note how it complains about a MBR //! ...
impl GptGuid { pub(crate) fn new_random() -> Self { let fields = uuid::Uuid::new_v4(); let fields = fields.as_fields(); GptGuid { time_low: fields.0, time_mid: fields.1, time_high: fields.2, node: *fields.3, } } } #[derive(Debug, D...
.to_string() ) } }
random_line_split
nexus_label.rs
0 200G 0 disk /code //! //! The nbd0 zero device does not show the partitions //! ``` use crate::bdev::nexus::Error; use bincode::{deserialize_from, serialize}; use crc::{crc32, Hasher32}; use serde::{ de::{Deserialize, Deserializer, SeqAccess, Unexpected, Visitor}, ser::{Serialize, SerializeTuple, Serialize...
: &
identifier_name
jira-api.service.ts
jql: searchQuery, }, }, cfg, }); } getIssueById$(issueId: string, cfg: JiraCfg): Observable<JiraIssue> { return this._getIssueById$(issueId, cfg, true); } getReducedIssueById$(issueId: string, cfg: JiraCfg): Observable<JiraIssueReduced> { return this._getIssueById$(is...
{ return ssVal; }
conditional_block
jira-api.service.ts
InterfacesReadyIfNeeded$: Observable<boolean> = IS_ELECTRON ? of(true).pipe() : this._chromeExtensionInterfaceService.onReady$.pipe(mapTo(true), shareReplay(1)); constructor( private _chromeExtensionInterfaceService: ChromeExtensionInterfaceService, private _electronService: ElectronService, priv...
(): void { this._isBlockAccess = false; sessionStorage.removeItem(BLOCK_ACCESS_KEY); } issuePicker$(searchTerm: string, cfg: JiraCfg): Observable<SearchResultItem[]> { const searchStr = `${searchTerm}`; return this._sendRequest$({ jiraReqCfg: { pathname: 'issue/picker', follo...
unblockAccess
identifier_name
jira-api.service.ts
ReadyIfNeeded$: Observable<boolean> = IS_ELECTRON ? of(true).pipe() : this._chromeExtensionInterfaceService.onReady$.pipe(mapTo(true), shareReplay(1)); constructor( private _chromeExtensionInterfaceService: ChromeExtensionInterfaceService, private _electronService: ElectronService, private _globa...
return this._sendRequest$({ jiraReqCfg: { transform: mapIssuesResponse as (res: any, cfg?: JiraCfg) => any, pathname: 'search', method: 'POST', body: { ...options, jql: searchQuery, }, }, cfg, }); } getIssueById$(issueId: string...
{ const options = { maxResults, fields: [ ...JIRA_ADDITIONAL_ISSUE_FIELDS, ...(cfg.storyPointFieldId ? [cfg.storyPointFieldId] : []), ], }; const searchQuery = cfg.autoAddBacklogJqlQuery; if (!searchQuery) { this._snackService.open({ type: 'ERROR', ...
identifier_body
jira-api.service.ts
) ); } private _sendRequest$({ jiraReqCfg, cfg, isForce = false, }: { jiraReqCfg: JiraRequestCfg; cfg: JiraCfg; isForce?: boolean; }): Observable<any> { return this._isInterfacesReadyIfNeeded$.pipe( take(1), concatMap(() => IS_ELECTRON && cfg.isWonkyCookieMod...
});
random_line_split
home.go
AllLimited: false, // Include also all public repositories of limited organisations Archived: util.OptionalBoolFalse, HasMilestones: util.OptionalBoolTrue, // Just needs display repos has milestones } if ctxUser.IsOrganization() && ctx.Org.Team != nil { repoOpts.TeamID = ctx.Org.Team.ID } var ( ...
{ if unit.TypeIssues.UnitGlobalDisabled() && unit.TypePullRequests.UnitGlobalDisabled() { log.Debug("Milestones overview page not available as both issues and pull requests are globally disabled") ctx.Status(http.StatusNotFound) return } ctx.Data["Title"] = ctx.Tr("milestones") ctx.Data["PageIsMilestonesDash...
identifier_body
home.go
10, 64) // If the repo id specified by query is not parseable or not accessible by user, just ignore it. if err == nil { repoIDs = append(repoIDs, rIDint64) } } } if len(repoIDs) > 0 { // Don't just let repoCond = builder.In("id", repoIDs) because user may has no permission on repoIDs...
ctx.ServerError("SearchMilestones", err) return } showRepos, _, err := repo_model.SearchRepositoryByCondition(ctx, &repoOpts, userRepoCond, false) if err != nil { ctx.ServerError("SearchRepositoryByCondition", err) return } sort.Sort(showRepos) for i := 0; i < len(milestones); { for _, repo := range s...
if err != nil {
random_line_split
home.go
err != nil { ctx.ServerError("LoadTotalTrackedTime", err) return } } i++ } milestoneStats, err := issues_model.GetMilestonesStatsByRepoCondAndKw(repoCond, keyword) if err != nil { ctx.ServerError("GetMilestoneStats", err) return } var totalMilestoneStats *issues_model.MilestonesStats if len(...
{ ctx.ServerError("StringsToInt64s", err) return }
conditional_block
home.go
10, 64) // If the repo id specified by query is not parseable or not accessible by user, just ignore it. if err == nil { repoIDs = append(repoIDs, rIDint64) } } } if len(repoIDs) > 0 { // Don't just let repoCond = builder.In("id", repoIDs) because user may has no permission on repoIDs...
(ctx *context.Context, unitType unit.Type) { // ---------------------------------------------------- // Determine user; can be either user or organization. // Return with NotFound or ServerError if unsuccessful. // ---------------------------------------------------- ctxUser := getDashboardContextUser(ctx) if ct...
buildIssueOverview
identifier_name
lib.rs
/// Update read buffer fn check(&mut self) -> Poll<(), std::io::Error> { loop { // Why do I have a loop here? I forgot?? self.read_buffer.reserve(512); let n = try_ready!(self.socket.read_buf(&mut self.read_buffer)); if n == 0 { return Ok(Async::Ready(())...
pub fn send(&self, t: T) -> Result<(), ()> { match self { Transmitter::Synchronous(sender) => sender.send(t).map_err(|_| ()), Transmitter::Asynchronous(sender) => { tokio::spawn({ let sender = sender.clone(); sender.send(t).into...
Asynchronous(futures::sync::mpsc::Sender<T>) } impl<T> Transmitter<T> where T: 'static + Send { /// Send a message through the underlying Sender
random_line_split
lib.rs
} #[cfg(feature = "master")] type EncryptedStream = tokio_tls::TlsStream<TcpStream>; /// A TCP stream adapter to convert between byte stream and objects #[cfg(feature = "master")] #[derive(Debug)] pub struct SprinklerProto { socket: EncryptedStream, read_buffer: BytesMut, } #[cfg(feature = "master")] impl S...
{ let next = self.counter; self.counter += 1; T::build(SprinklerOptions { _id: next, _hostname: hostname, ..self.params.clone() }) }
identifier_body
lib.rs
Update read buffer fn check(&mut self) -> Poll<(), std::io::Error> { loop { // Why do I have a loop here? I forgot?? self.read_buffer.reserve(512); let n = try_ready!(self.socket.read_buf(&mut self.read_buffer)); if n == 0 { return Ok(Async::Ready(())); ...
(&self) -> AnomalyTransition { (*self >> Anomaly::Negative).unwrap() } } #[derive(PartialEq, Debug, Copy, Clone)] pub enum AnomalyTransition { Normal, // Negative -> Negative Occurred, // Negative -> Positive Unhandled, // Positive -> Positive Disappeared, // Positive ...
diminish
identifier_name
lib.rs
TOTAL_SYSTEM_MEMORY), format_size(total_memory) ) .unwrap(); } if total_swap > 0 { write!( buf, " swap={}->{}", format_size(*TOTAL_SYSTEM_SWAP), format_size(total_swap) ) .unwrap(); } if nr_cpus > 0 { ...
let mut path = dir.to_owned(); path.push(name); if let Ok(path) = path.canonicalize() { if is_executable(&path
random_line_split
lib.rs
M', 60.0), ('H', 3600.0), ('D', 3600.0 * 24.0), ('Y', 3600.0 * 24.0 * 365.0), ] .iter() .cloned() .collect(); } let mut num = String::new(); let mut sum = 0.0; for ch in input.chars() { if UNITS.contains_key(&ch) { ...
ProgState
identifier_name
trie.rs
<u8>>) -> Self { let include_dense = K_INCLUDE_DENSE; let sparse_dense = K_SPARSE_DENSE_RATIO; let mut builder = builder::Builder::new(include_dense, sparse_dense); builder.build(&keys); let louds_dense = LoudsDense::new(&builder); let louds_sparse = LoudsSparse::new(&bu...
ec<Vec
identifier_name
trie.rs
sparse_dense = K_SPARSE_DENSE_RATIO; let mut builder = builder::Builder::new(include_dense, sparse_dense); builder.build(&keys); let louds_dense = LoudsDense::new(&builder); let louds_sparse = LoudsSparse::new(&builder); let mut num_keys = 0; for level in 0..louds_spar...
d_key(key, ret.2); } return (ret.0, ret.1); } fn _traverse( &self, key: &key_t, ) -> (position_t, level_t) { let ret = self.louds_dense.find_key(key); if ret.0 != K_NOT_FOUND { return (ret.0, ret.1); } if ret.2 != K_NOT_FOUND { ...
OT_FOUND { return louds_sparse.fin
conditional_block
trie.rs
0; // continue; // } // let mut num_match = 0; // while num_match < curr_suffix.contents.len() // && num_match < prev_suffix.contents.len() // && prev_suffix.contents[num_match] == curr_suffix.contents[num_match] // { ...
identifier_body
trie.rs
!= 0 && keys[i] == keys[i - 1] { continue; } let (key_id, level) = Trie::traverse(&louds_dense, &louds_sparse, keys[i].as_slice()); assert!(key_id < num_keys); let contents = keys[i][level..].to_vec(); suffix_builder[key_id] = Suffix { conten...
break; } else { updated |= mask; }
random_line_split
tau0305.py
].flatten()) #update chunk id step_j += n_j step_i += n_i del X_global, Y_global, out_global for metric in metrics: distances = [] mean_distances = [] max_dis = [] #Split cpu's data to gpus n = int(len(featu...
return torch.tensor(mynan) return torch.cat([nan_to_num(l).unsqueeze(0) for l in t],0) def get_tau(data,maxval,tailfrac=.25,pcent=.999): #tw = weibull.weibull(translateAmountTensor=.001)
random_line_split
tau0305.py
(X, Y, out): i, j = cuda.grid(2) if i < out.shape[0] and j < out.shape[1]: u = X[i] v = Y[j] out[i, j] = euclidean_gpu(u, v) ##################################################################################### def tau(args, features, gpus): #Now only support Cosine and Euclidean on...
euclidean_dis_gpu
identifier_name
tau0305.py
@cuda.jit def euclidean_dis_gpu(X, Y, out): i, j = cuda.grid(2) if i < out.shape[0] and j < out.shape[1]: u = X[i] v = Y[j] out[i, j] = euclidean_gpu(u, v) ##################################################################################### def tau(args, features, gpus): #Now onl...
i, j = cuda.grid(2) if i < out.shape[0] and j < out.shape[1]: u = X[i] v = Y[j] out[i, j] = cosine_gpu(u, v)
identifier_body
tau0305.py
, j = cuda.grid(2) if i < out.shape[0] and j < out.shape[1]: u = X[i] v = Y[j] out[i, j] = euclidean_gpu(u, v) ##################################################################################### def tau(args, features, gpus): #Now only support Cosine and Euclidean on GPU if args.d...
#Number of threads depend on how many gpus you have for t in threads: t.setDaemon(True) t.start() #Re-group final distance data from gpus for t in threads: whole_distances = [] t.join() distances.extend(np.array(whole_distances...
whole_distances = [] split = split_double(args, mutilple_features[p]) n = int(len(mutilple_features[p]) / split) chunks = [mutilple_features[p][i * n:(i + 1) * n] for i in range((len(mutilple_features[p]) + n - 1) // n )] step_i = 0 threads.append(threading.Th...
conditional_block
verifier.rs
if bytes.len() % 4 != 1 && bytes.len() > 0 { let mut rv = vec![]; let mut pos = 0; while pos + 4 <= bytes.len() { let s = maybe!(triplet(&bytes[pos..pos + 4])); rv.extend_from_slice(&s); pos += 4; } if bytes.len() - pos == 2 { ...
rv } fn debase64_no_pad(bytes: &[u8]) -> Option<Vec<u8>> {
random_line_split
verifier.rs
} Some(rv) } else { None } } struct Parser<'a> { enc: &'a [u8], pos: usize, } impl<'a> fmt::Debug for Parser<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", String::from_utf8_lossy(&self.enc[..self.pos]))?; write!(f, "<-- {} -...
{ if bytes.len() % 4 != 1 && bytes.len() > 0 { let mut rv = vec![]; let mut pos = 0; while pos + 4 <= bytes.len() { let s = maybe!(triplet(&bytes[pos..pos + 4])); rv.extend_from_slice(&s); pos += 4; } if bytes.len() - pos == 2 { ...
identifier_body
verifier.rs
2 | b >> 4); } else if bytes.len() - pos == 3 { let a = maybe!(delut(bytes[pos])); let b = maybe!(delut(bytes[pos + 1])); let c = maybe!(delut(bytes[pos + 2])); rv.push(a << 2 | b >> 4); rv.push(b << 4 | c >> 2); } Some(rv) } else ...
(&self) -> Vec<u8> { let vcode = |v| match v { Variant::Argon2i => "i", Variant::Argon2d => "d", Variant::Argon2id => "id", }; let b64 = |x| String::from_utf8(base64_no_pad(x)).unwrap(); let k_ = match &b64(&self.key[..]) { bytes if bytes.l...
to_u8
identifier_name
disk.rs
to convert a standard disk image to an async disk image. This conversion and the /// inverse are needed so that the `Send` DiskImage can be given to the block thread where it is /// converted to a non-`Send` AsyncDisk. The AsyncDisk can then be converted back and returned /// to the main device thread if t...
write_zeroes_at
identifier_name
disk.rs
Sparse; #[cfg(feature = "android-sparse")] use android_sparse::SPARSE_HEADER_MAGIC; /// Nesting depth limit for disk formats that can open other disk files. pub const MAX_NESTING_DEPTH: u32 = 10; #[derive(ThisError, Debug)] pub enum Error { #[error("failed to create block device: {0}")] BlockDeviceNew(base::E...
// max_nesting_depth is only used if the composite-disk or qcow features are enabled. #[allow(unused_variables)] mut max_nesting_depth: u32, // image_path is only used if the composite-disk feature is enabled. #[allow(unused_variables)] image_path: &Path, ) -> Result<Box<dyn DiskFile>> { if max_nest...
/// Inspect the image file type and create an appropriate disk file to match it. pub fn create_disk_file( raw_image: File, is_sparse_file: bool,
random_line_split
disk.rs
; #[cfg(feature = "android-sparse")] use android_sparse::SPARSE_HEADER_MAGIC; /// Nesting depth limit for disk formats that can open other disk files. pub const MAX_NESTING_DEPTH: u32 = 10; #[derive(ThisError, Debug)] pub enum Error { #[error("failed to create block device: {0}")] BlockDeviceNew(base::Error),...
#[cfg(feature = "qcow")] ImageType::Qcow2 => { Box::new(QcowFile::from(raw_image, max_nesting_depth).map_err(Error::QcowError)?) as Box<dyn DiskFile> } #[cfg(feature = "composite-disk")] ImageType::CompositeDisk => { // Valid composite dis...
{ sys::apply_raw_disk_file_options(&raw_image, is_sparse_file)?; Box::new(raw_image) as Box<dyn DiskFile> }
conditional_block
gen_functionalization_type.py
. def unwrap_tensor_args(sig: DispatcherSignature) -> Tuple[str, List[Binding]]: context: List[Binding] = [] unwrapped_tensor_args: List[str] = [] for arg in sig.arguments(): if is_tensor_like(arg.argument): # for tensor inputs, we want to unwrap them before passing them into the redispa...
mutable_input_post_processing = '\n'.join([ f""" auto {a.name}_functional = at::functionalization::impl::unsafeGetFunctionalWrapper({a.name}); {a.name}_functional->replace_(tmp_output);
functional_exprs = [keyset] + [e.expr for e in translate(unwrapped_args_ctx, functional_sig.arguments(), method=False)]
random_line_split
gen_functionalization_type.py
List[str] = [] for arg in sig.arguments(): if is_tensor_like(arg.argument): # for tensor inputs, we want to unwrap them before passing them into the redispatch calls. # for tensor inputs, we want to unwrap them before passing them into the redispatch calls. a_ = arg.name...
gen_functionalization_registration
identifier_name
gen_functionalization_type.py
. def unwrap_tensor_args(sig: DispatcherSignature) -> Tuple[str, List[Binding]]: context: List[Binding] = [] unwrapped_tensor_args: List[str] = [] for arg in sig.arguments(): if is_tensor_like(arg.argument): # for tensor inputs, we want to unwrap them before passing them into the redispa...
dispatcher_sig = DispatcherSignature.from_schema(f.func) keyset = 'dispatchKeySet & c10::after_func_keyset' return_type = dispatcher_sig.returns_type().remove_const_ref().cpp_type() unwrap_tensor_args_str, unwrapped_args_ctx = unwrap_tensor_args(dispatcher_sig) view_redispatch_args = [keyset] + [e...
assert f.is_view_op if f.tag is Tag.inplace_view: # This op is both an inplace op AND a view op. # See Note [Functionalization Pass - Inplace View Ops] for details. # I currently have the view meta call into the out-of-place variant of the view, to avoid # having to define an extra ...
identifier_body
gen_functionalization_type.py
=*/c10::make_optional({a_}.scalar_type()), /*layout=*/c10::make_optional({a_}.layout()), \ /*device=*/c10::make_optional(c10::Device(kMeta)), /*pin_memory=*/c10::nullopt);" ) context.append(arg.with_name(unwrapped_name)) else: # for non-tensor inputs, we want to pass them dir...
return None
conditional_block
iterative_gmm.py
: def __init__(self): self.XY = None def plot_cov(self,means, covariances,ct): if ct == 'spherical': return color_iter = itertools.cycle(['navy', 'navy', 'cornflowerblue', 'gold', 'darkorange']) ax =plt.gca() for i, (...
I_gmm
identifier_name
iterative_gmm.py
else: length = 68 # This is code for just looking at the ratio of the bins if mode == 'fraction': # initialize vector for fraction X2 = np.zeros([X1.shape[0],int(scipy.special.comb(5,2))]) result = [x for x in itertools.combinations(np.arange(5),2)] ...
print(jj) b = a == jj b = [i for i, x in enumerate(b) if x] if jj == 0: c = b ax0.scatter(X1[b,0],X1[b,1],c=colorz[(jj-a.min())])
conditional_block
iterative_gmm.py
ell = Ellipse(mean, v[0]*4, v[1]*2, 180. + angle, color=color) ell.set_clip_box(ax.bbox) ell.set_alpha(alpha) ell = Ellipse(mean, v[0]*2, v[1]*2, 180. + angle, color=color) ell.set_clip_box(ax.bbox) ell.set_alpha(alpha) ax.add_artist(el...
if ct == 'spherical': return color_iter = itertools.cycle(['navy', 'navy', 'cornflowerblue', 'gold', 'darkorange']) ax =plt.gca() for i, (mean, covar, color) in enumerate(zip( means, covariances, color_iter)): ...
identifier_body
iterative_gmm.py
grey',zorder=10,s=100) def iterative_gmm(self,dataset = 'bb',fake = True,mode = 'gmm',binary = False,im_dir = './images/',savegif = False,title ='temp',bic_thresh = 0,maxiter = 40,nc =5,v_and_1 = False,thresh = 0.9,cov=[],n_components=2,covt='spherical',ra=False,pca = True): ''' da...
colorz = ['b','r','g','m'] for jj,color in zip(range(a.min(),a.max()+1),colorz): print(jj) b = a == jj b = [i for i, x in enumerate(b) if x] if jj == 0: c = b ax0.scatter(X1[b,0],X1[b,1],c=colorz[...
a = -(y_pred - label_true.squeeze()) y_reshape = np.reshape(a, (20,length), order="F")
random_line_split
error_format.rs
of type String. Usage: string.ends_with_regex(\"regex\")"; pub const ERROR_STRING_FROM_JSON: &str = "[from_json] [!] string to object failed]"; pub const ERROR_STRING_SPLIT: &str = "[split] takes one parameter of type String. Usage: string.split(\"separator\")"; pub const ERROR_STRING_MATCH_REGEX: &str = "[mat...
{ Err::Error(E::add_context( span, error, E::from_error_kind(span, ErrorKind::Tag), )) }
identifier_body
error_format.rs
= "Url component expects one argument of type string and 2 optional string arguments: text, title. Example: Url(\"hola\", text = \"text\", title = \"title\")"; pub const ERROR_VIDEO: &str = "Video component expects one argument of type string. Example: Video(url = \"hola\")"; pub const ERROR_AUDIO: &str = "Aud...
random_line_split
error_format.rs
string.ends_with_regex(\"regex\")"; pub const ERROR_STRING_FROM_JSON: &str = "[from_json] [!] string to object failed]"; pub const ERROR_STRING_SPLIT: &str = "[split] takes one parameter of type String. Usage: string.split(\"separator\")"; pub const ERROR_STRING_MATCH_REGEX: &str = "[match_regex] takes one par...
gen_nom_failure
identifier_name
types.go
2(len(result))) b.write([]byte(result)) case *ast.DUuid: // Start at offset 4 because `putInt32` clobbers the first 4 bytes. s := b.putbuf[4 : 4+36] v.UUID.StringBytes(s) b.putInt32(int32(len(s))) b.write(s) case *ast.DIPAddr: b.writeLengthPrefixedString(v.IPAddr.String()) case *ast.DString: b.wri...
else { b.writeByte(0) } case *ast.DInt: switch t.Oid() { case oid.T_int2: b.putInt32(2) b.putInt16(int16(*v)) case oid.T_int4: b.putInt32(4) b.putInt32(int32(*v)) case oid.T_int8: b.putInt32(8) b.putInt64(int64(*v)) default: b.setError(errors.Errorf("unsupported int oid: %v", t.Oi...
{ b.writeByte(1) }
conditional_block
types.go
s := strconv.AppendInt(b.putbuf[4:4], int64(*v), 10) b.putInt32(int32(len(s))) b.write(s) case *ast.DFloat: // Start at offset 4 because `putInt32` clobbers the first 4 bytes. s := strconv.AppendFloat(b.putbuf[4:4], float64(*v), 'g', conv.GetFloatPrec(), 64) b.putInt32(int32(len(s))) b.write(s) case *...
{ if log.V(2) { log.Infof(ctx, "pgwire writing TEXT datum of type: %T, %#v", d, d) } if d == ast.DNull { // NULL is encoded as -1; all other values have a length prefix. b.putInt32(-1) return } switch v := ast.UnwrapDatum(nil, d).(type) { case *ast.DBitArray: b.textFormatter.FormatNode(v) b.writeFromF...
identifier_body
types.go
oid oid.Oid // Variable-size types have size=-1. // Note that the protocol has both int16 and int32 size fields, // so this attribute is an unsized int and should be cast // as needed. // This field does *not* correspond to the encoded length of a // data type, so it's unclear what, if anything, it is used for....
) // pgType contains type metadata used in RowDescription messages. type pgType struct {
random_line_split
types.go
igits := strings.TrimLeftFunc(alloc.bigI.Abs(&v.Coeff).String(), isZero) dweight := len(digits) - int(alloc.pgNum.Dscale) - 1 digits = strings.TrimRightFunc(digits, isZero) if dweight >= 0 { alloc.pgNum.Weight = int16((dweight+1+pgwirebase.PGDecDigits-1)/pgwirebase.PGDecDigits - 1) } else { alloc.pgNum.W...
formatTimeTZ
identifier_name
lmdb_backend.rs
x| x.1), )) } fn get_tx_log_by_slate_id(&self, slate_id: &str) -> Result<Option<TxLogEntry>> { let key = to_key(TX_LOG_ENTRY_PREFIX, &mut slate_id.as_bytes().to_vec()); self.db()?.get_ser(&key).map_err(|e| e.into()) } fn tx_logs<'a>(&'a self) -> Result<Box<dyn Iterator<Item = TxLogEntry> + 'a>> { Ok(Box::...
next_tx_log_id
identifier_name
lmdb_backend.rs
.deref())?; self.password = Some(password); Ok(()) } /// Clear out backend fn clear(&mut self) -> Result<()> { self.disconnect()?; let root_path = Path::new(&self.config.data_file_dir); if !root_path.exists() { return Ok(()); } let backup_dir = Utc::now().format("%Y%m%d-%H%M%S").to_string(); le...
Ok(()) }
random_line_split
lmdb_backend.rs
None, password: Some(ZeroingString::from(password)), keychain: None, parent_key_id: K::derive_key_id(2, 0, 0, 0, 0), config: config.clone(), w2n_client: n_client, }; Ok(res) }*/ } impl<C, K> WalletBackend<C, K> for Backend<C, K> where C: NodeClient, K: Keychain, { /// Check whether the backend ...
self.db = Some(store); Ok(()) } /// Disconnect from backend fn disconnect(&mut self) -> Result<()> { self.db = None; Ok(()) } /// Set password fn set_password(&mut self, password: ZeroingString) -> Result<()> { let _ = WalletSeed::from_file(&self.config, password.deref())?; self.password = Some(pa...
{ let batch = store.batch()?; batch.put_ser(&acct_key, &default_account)?; batch.commit()?; }
conditional_block
lmdb_backend.rs
None, password: Some(ZeroingString::from(password)), keychain: None, parent_key_id: K::derive_key_id(2, 0, 0, 0, 0), config: config.clone(), w2n_client: n_client, }; Ok(res) }*/ } impl<C, K> WalletBackend<C, K> for Backend<C, K> where C: NodeClient, K: Keychain, { /// Check whether the backend ...
fn accounts<'a>(&'a self) -> Result<Box<dyn Iterator<Item = AcctPathMapping> + 'a>> { Ok(Box::new( self.db()? .iter(&[ACCOUNT_PATH_MAPPING_PREFIX]) .unwrap() .map(|x| x.1), )) } fn get_acct_path(&self, label: &str) -> Result<Option<AcctPathMapping>> { let acct_key = to_key(ACCOUNT_PATH_MAPPIN...
{ let ctx_key = to_key_u64( PRIVATE_TX_CONTEXT_PREFIX, &mut slate_id.to_vec(), participant_id as u64, ); let (blind_xor_key, nonce_xor_key) = private_ctx_xor_keys(self.keychain(), slate_id)?; let mut ctx: Context = option_to_not_found(self.db()?.get_ser(&ctx_key), || { format!("Slate id: {:x?}", sl...
identifier_body
lib.rs
str, fields: Option<&[(&str, u32)]>,
fn update_field(&self, sc: &Scope, update: &[(&str, u32)]) -> Result<()>; } /// A collection of methods to interact with the datapath. #[derive(Clone)] pub struct Datapath<T: Ipc> { sock_id: u32, sender: BackendSender<T>, programs: Rc<HashMap<String, Scope>>, } impl<T: Ipc> DatapathTrait for Datapath<...
) -> Result<Scope>; /// Update the value of a register in an already-installed fold function.
random_line_split
lib.rs
str, fields: Option<&[(&str, u32)]>, ) -> Result<Scope>; /// Update the value of a register in an already-installed fold function. fn update_field(&self, sc: &Scope, update: &[(&str, u32)]) -> Result<()>; } /// A collection of methods to interact with the datapath. #[derive(Clone)] pub struct Data...
{ pub sock_id: u32, pub init_cwnd: u32, pub mss: u32, pub src_ip: u32, pub src_port: u32, pub dst_ip: u32, pub dst_port: u32, } /// Contains the values of the pre-defined Report struct from the fold function. /// Use `get_field` to query its values using the names defined in the fold funct...
DatapathInfo
identifier_name
lib.rs
str, fields: Option<&[(&str, u32)]>, ) -> Result<Scope>; /// Update the value of a register in an already-installed fold function. fn update_field(&self, sc: &Scope, update: &[(&str, u32)]) -> Result<()>; } /// A collection of methods to interact with the datapath. #[derive(Clone)] pub struct Data...
/// Configuration parameters for the portus runtime. /// Defines a `slog::Logger` to use for (optional) logging #[derive(Clone, Default)] pub struct Config { pub logger: Option<slog::Logger>, } /// The set of information passed by the datapath to CCP /// when a connection starts. It includes a unique 5-tuple (CC...
{ let msg = serialize::install::Msg { sid: sock_id, program_uid: sc.program_uid, num_events: bin.events.len() as u32, num_instrs: bin.instrs.len() as u32, instrs: bin, }; let buf = serialize::serialize(&msg)?; sender.send_msg(&buf[..])?; Ok(()) }
identifier_body
models.py
_lazy from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ from django_prometheus.models import ExportModelOperationsMixin from guardian.mixins import GuardianUserMixin from jinja2 import Undefined from jinja2.exceptions import TemplateSyntaxError, UndefinedError from jinja2.nati...
: permissions = (("reset_user_password", "Reset Password"),) class Provider(ExportModelOperationsMixin("provider"), models.Model): """Application-independent Provider instance. For example SAML2 Remote, OAuth2 Application""" property_mappings = models.ManyToManyField( "PropertyMapping", defa...
Meta
identifier_name
models.py
_lazy from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ from django_prometheus.models import ExportModelOperationsMixin from guardian.mixins import GuardianUserMixin from jinja2 import Undefined from jinja2.exceptions import TemplateSyntaxError, UndefinedError from jinja2.nati...
class DebugPolicy(Policy): """Policy used for debugging the PolicyEngine. Returns a fixed result, but takes a random time to process.""" result = models.BooleanField(default=False) wait_min = models.IntegerField(default=5) wait_max = models.IntegerField(default=30) form = "passbook.core.for...
"""Check if user instance passes this policy""" raise PolicyException()
identifier_body
models.py
_lazy from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ from django_prometheus.models import ExportModelOperationsMixin from guardian.mixins import GuardianUserMixin from jinja2 import Undefined from jinja2.exceptions import TemplateSyntaxError, UndefinedError from jinja2.nati...
"""Policy used for debugging the PolicyEngine. Returns a fixed result, but takes a random time to process.""" result = models.BooleanField(default=False) wait_min = models.IntegerField(default=5) wait_max = models.IntegerField(default=30) form = "passbook.core.forms.policies.DebugPolicyForm" ...
raise PolicyException() class DebugPolicy(Policy):
random_line_split
models.py
_lazy from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ from django_prometheus.models import ExportModelOperationsMixin from guardian.mixins import GuardianUserMixin from jinja2 import Undefined from jinja2.exceptions import TemplateSyntaxError, UndefinedError from jinja2.nati...
return super().__str__() class PolicyModel(UUIDModel, CreatedUpdatedModel): """Base model which can have policies applied to it""" policies = models.ManyToManyField("Policy", blank=True) class Factor(ExportModelOperationsMixin("factor"), PolicyModel): """Authentication factor, multiple instanc...
return getattr(self, "name")
conditional_block
Ui_Offer_Home.py
_16px_528836_easyicon.net.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.Button_audit.setIcon(icon1) self.Button_audit.setObjectName("Button_audit") self.horizontalLayout.addWidget(self.Button_audit) self.Box_group = QtWidgets.QComboBox(Offer_Home) self.Box_group.setObjectName(...
j in range(vol_3): temp_data = data_3[i][j] # 临时记录,不能直接插入表格 data3 = QTableWidgetItem(str(temp_data)) # 转换后可插入表格 self.Widget_details.setItem(i, j, data3) self.Widget_details.resizeColumnsToContents() #自适应宽度 self.Widget_de...
identifier_body
Ui_Offer_Home.py
db='mrp',charset='utf8',) cur = db.cursor() cur.execute("SELECT * FROM 报价基本信息") data = cur.fetchall() #接收全部的返回结果行 col_lst = [tup[0] for tup in cur.description] #数据列字段名 tup:数组 #description:种类 #数据的大小 row = len(data) ...
identifier_name
Ui_Offer_Home.py
.setToolTip("") self.verticalLayout = QtWidgets.QVBoxLayout(Offer_Home) self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.Button_offernew = QtWidgets.QPushButton(Offer_H...
conn = db.cursor() sql = "SELECT * FROM 报价明细 WHERE 报价单号 LIKE 'BJ18011516'" #'%"+bjdh+"%'" conn.execute(sql) col_lst_1 = [tup[0] for tup in conn.description] #数据列字段名 tup:数组 #description:种类 vol_1 = len(conn.description) #获得data的卷数.第一行的数量(...
og.resizeRowsToContents() #自适应行高,这两句放最后可以等数据写入后自动适应表格数据宽度 db.close cur.close #报价明细区域 # db = pymysql.connect(host='127.0.0.1', port=3308, user='root', password='root', db='mrp',charset='utf8',)
conditional_block
Ui_Offer_Home.py
ome.setToolTip("")
self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.Button_offernew = QtWidgets.QPushButton(Offer_Home) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("images/A...
self.verticalLayout = QtWidgets.QVBoxLayout(Offer_Home)
random_line_split
utils.rs
.to_string())) } pub fn address_to_string(address: &Address) -> String { format!("0x{}", address.encode_hex::<String>()) } #[derive(Debug, Clone, Copy)] pub enum UploadMode { Auto, Azure, Direct, } pub fn upload_mode_from_str(upload_mode: &str) -> Result<UploadMode> { match upload_mode { ...
{ File::create(path)?.write_all( format_attestation( &attestation.id, &attestation.address, &attestation.signature, ) .as_bytes(), )?; Ok(()) }
identifier_body
utils.rs
ANGE, format!("bytes={}-{}", start, end)) .header(CONTENT_LENGTH, 0) .timeout(std::time::Duration::from_secs( DEFAULT_CHUNK_TIMEOUT_IN_SECONDS, )) .send() .await? ...
.parse::<u64>()?) } pub async fn get_ceremony(url: &str) -> Result<Ceremony> { let response = reqwest::get(url).await?.error_for_status()?; let data = response.text().await?; let ceremony: Ceremony = serde_json::from_str::<Response<Ceremony>>(&data)?.result; Ok(ceremony) } use crate::transcrip...
.to_str()?
random_line_split
utils.rs
message = format!("{} /{}", method.to_lowercase(), path.to_lowercase()); let signature: Signature = futures::executor::block_on(private_key.sign_message(message))?; let authorization = format!("Celo 0x{}:0x{}", address, signature.to_string()); Ok(authorization) } pub fn create_parameters_for_chunk<E: Pair...
backup_transcript
identifier_name
schema.py
=_( "Name of the source system (e.g. 'myhelsinki', 'ahti', " "'ulkoliikuntakartta', 'digitransit')" ), ) type = graphene.String( required=True, description=_( "Type of the feature in the source system, if applicable (e.g. 'place', " "'activ...
ngoObjectType): """Tags are associated with things (like features).""" class Meta: model = models.Tag fields = ("id", "features") name = graphene.String(required=True, description=_("Display name of the tag")) class OpeningHoursPeriod(DjangoObjectType): """A period during which certa...
Dja
identifier_name
schema.py
minimum depth (or lower end of the range)" ), ) max = graphene.Float( required=True, description=_( "An approximation of the maximum depth (or deeper end of the range)" ), ) class HarborDetails(ObjectType): """Information specific to harbors (and piers)."""...
ahti_id=String(description=_("Ahti ID of the object")), description=_("Retrieve a single feature"), ) tags = graphene.List(Tag, description=_("Retrieve all tags"))
random_line_split
schema.py
) main = graphene.String(description=_("The meat of the deal, '7€/day' part")) class FeatureTranslations(DjangoObjectType): "Values in other languages for the feature attributes that can have translations." language_code = LanguageEnum(required=True) class Meta: model = apps.get_model("feat...
et_address = graphene.String() postal_code = graphene.String() municipality = graphene.String() phone_number = graphene.String() email = graphene.String() c
identifier_body
schema.py
), ) class HarborDetails(ObjectType): """Information specific to harbors (and piers).""" moorings = graphene.List( graphene.NonNull(HarborMooringTypeEnum), description=_("Mooring types available in the harbor"), ) depth = graphene.Field( Depth, description=_("Appro...
rn relay.Node.get_node_from_global_id(info, id, only_type=Feature)
conditional_block
config.go
levant(n.IPAM) { return nil, "", NewInvalidPluginError(n.IPAM.Type) } args := types.IPAMEnvArgs{} if err := cnitypes.LoadArgs(envArgs, &args); err != nil { return nil, "", fmt.Errorf("LoadArgs - CNI Args Parsing Error: %s", err) } n.IPAM.PodName = string(args.K8S_POD_NAME) n.IPAM.PodNamespace = string(args.K...
else { firstip, ipNet, err := netutils.ParseCIDRSloppy(n.IPAM.IPRanges[idx].Range) if err != nil { return nil, "", fmt.Errorf("invalid CIDR %s: %s", n.IPAM.IPRanges[idx].Range, err) } n.IPAM.IPRanges[idx].Range = ipNet.String() if n.IPAM.IPRanges[idx].RangeStart == nil { firstip = netutils.Parse...
{ firstip := netutils.ParseIPSloppy(r[0]) if firstip == nil { return nil, "", fmt.Errorf("invalid range start IP: %s", r[0]) } lastip, ipNet, err := netutils.ParseCIDRSloppy(r[1]) if err != nil { return nil, "", fmt.Errorf("invalid CIDR (do you have the 'range' parameter set for Whereabouts?) '%s...
conditional_block
config.go
// as `bytes`. At the moment values provided in envArgs are ignored so there // is no possibility to overload the json configuration using envArgs func LoadIPAMConfig(bytes []byte, envArgs string, extraConfigPaths ...string) (*types.IPAMConfig, string, error) { var n types.Net if err := json.Unmarshal(bytes, &n); er...
} return fmt.Errorf("IP %s not v4 nor v6", *ip) } // LoadIPAMConfig creates IPAMConfig using json encoded configuration provided
random_line_split
config.go
(bytes []byte, envArgs string, extraConfigPaths ...string) (*types.IPAMConfig, string, error) { var n types.Net if err := json.Unmarshal(bytes, &n); err != nil { return nil, "", fmt.Errorf("LoadIPAMConfig - JSON Parsing Error: %s / bytes: %s", err, bytes) } if n.IPAM == nil { return nil, "", fmt.Errorf("IPAM ...
LoadIPAMConfig
identifier_name
config.go
flatipam, foundflatfile, err := GetFlatIPAM(false, n.IPAM, extraConfigPaths...) if err != nil { return nil, "", err } // Now let's try to merge the configurations... // NB: Don't try to do any initialization before this point or it won't account for merged flat file. var OverlappingRanges bool = n.IPAM.Overlap...
{ var n types.Net if err := json.Unmarshal(bytes, &n); err != nil { return nil, "", fmt.Errorf("LoadIPAMConfig - JSON Parsing Error: %s / bytes: %s", err, bytes) } if n.IPAM == nil { return nil, "", fmt.Errorf("IPAM config missing 'ipam' key") } else if !isNetworkRelevant(n.IPAM) { return nil, "", NewInval...
identifier_body
ontology.js
function displayGeography(){ document.getElementById("ontology_lookup").style.display='none'; document.getElementById("geographic_location").style.display=''; document.getElementById("map_canvas").style.visibility='visible'; } /* Initializes the Google Map. */ function initialize(){ geocoder = new go...
{ document.getElementById("ontology_lookup").style.display=''; document.getElementById("geographic_location").style.display='none'; document.getElementById("map_canvas").style.visibility='hidden'; }
identifier_body
ontology.js
loading_status').innerHTML='Completed'",timer_ms) } } /* This function gets the Lat/Long using Google Maps Geocoder API. */ function geocode_results(i){ //query google maps for lat/lngs geocoder.geocode( { 'address': unique_addresses[i]}, function(results, status) { if (status == google.maps...
(){ //generate the output content type=document.getElementById('latlngType').value var content=''; for (var i=0; i<saved_address_array.length; i++) { if (type=='Latitude'){ content=content+latitude[saved_address_array[i]]+'<br>'; }else if (type=='Longitude'){ ...
output_latlong
identifier_name
ontology.js
_address_array[i]]+'<br>'; }else if (type=='Elevation'){ content=content+elevation[saved_address_array[i]]+'<br>'; } } //write page top.consoleRef=window.open('','myconsole','width=350,height=400,menubar=0,toolbar=1,status=0,scrollbars=1,resizable=1') to...
if (original_ont_term_array[j]==original_unique_terms[k]){
random_line_split
ontology.js
} }); }else{ alert(status) alert("Unable to find the Location you specified!"); } }) } /* This function outputs the Lat/Long/Elev to the Console. */ function output_latlong(){ //generate the output content type=document.getElementById('latlngType').valu...
{ alert('You need choose valid terms!'); return; }
conditional_block
render.js
(); if (neighboorDistance <= distance) { walk(cells, edges, neighboorCell, distance - neighboorDistance); } } } } window.addEventListener("keyup", function (e) { var char = String.fromCharCode(e.keyCode); if (char == 'R') { newVoronoi(); } else i...
function makeFlat(f) { function mf(g) { if (!g.old) { g.old = g.vertices.map(function(v,i) { return v.y; }); } g.vertices.map(function (v, i) { if (f) { v.y = 0; } else { v.y = g.old[i]; } }); g.dynamic = g.vertic...
{ if (!map) { return; } var cells = map.voronoi.cells; for (var i = 0; i < cells.length; i++) { var cell = cells[i]; var faces = cell.faces; for (var j = 0; j < faces.length; j++) { var f = faces[j]; var c = f.color; c...
identifier_body
render.js
length(); if (neighboorDistance <= distance) { walk(cells, edges, neighboorCell, distance - neighboorDistance); } } } } window.addEventListener("keyup", function (e) { var char = String.fromCharCode(e.keyCode); if (char == 'R') { newVoronoi(); } ...
this.seaLevel = 0.45; this.heightFrequency = 1.2; this.heightScale = 0.3; this.render = "biome"; } var gui = new dat.GUI(); var settings = new Settings(); gui.add(settings, "sites", 0).step(50).onFinishChange(newVoronoi); gui.add(settings, "heightScale", 0, 1).step(0.01); gui.add(settings, "heightFreque...
this.flat = false;
random_line_split
render.js
(); if (neighboorDistance <= distance) { walk(cells, edges, neighboorCell, distance - neighboorDistance); } } } } window.addEventListener("keyup", function (e) { var char = String.fromCharCode(e.keyCode); if (char == 'R') { newVoronoi(); } else i...
(f) { function mf(g) { if (!g.old) { g.old = g.vertices.map(function(v,i) { return v.y; }); } g.vertices.map(function (v, i) { if (f) { v.y = 0; } else { v.y = g.old[i]; } }); g.dynamic = g.verticesNeedUpdate = true...
makeFlat
identifier_name
build_all.py
") as f: data = json.loads(strip_comments(f.read().decode("utf-8"))) value = data for part in json_path.split("."): if part in value: value = value[part] else: raise ValueError("'$.{}' not found in {}".format(json_path, file_path)) return value def get_dock...
image_list.append(image)
conditional_block
build_all.py
file_path = os.path.abspath(os.path.join(cwd, file_path)) # fix json_path if json_path.startswith("$."): json_path = json_path.replace("$.", "", 1) with open(file_path, "rb") as f: data = json.loads(strip_comments(f.read().decode("utf-8"))) value = data for part in json_path.spli...
random_line_split
build_all.py
(string, comment_symbols=frozenset(('#', '//'))): """ Strip comments from json string. :param string: A string containing json with comments started by comment_symbols. :param comment_symbols: Iterable of symbols that start a line comment (default # or //). :return: The string with the comments remo...
strip_comments
identifier_name
build_all.py
: Iterable of symbols that start a line comment (default # or //). :return: The string with the comments removed. """ lines = string.splitlines() for k in range(len(lines)): for symbol in comment_symbols: lines[k] = strip_comment_line_with_symbol(lines[k], start=symbol) return '\...
dockerhub_username = DOCKER_HUB_USERNAME # type: str dir_repo_root = None # type: str dir_tag_root = None # type: str is_state_exists = None # type: bool _repo_name = None # type: str @property def repo_name(self): if self._repo_name is None: self._repo_name = re...
""" datetime type of ``last_update`` """ return datetime.strptime(self.last_update, "%Y-%m-%d %H:%M:%S.%f")
identifier_body
admission_test.go
("", "") if err != nil { t.Fatalf("Unexpected error while creating temporary file: %v", err) } p := tempfile.Name() defer os.Remove(p) kubeconfig := ` clusters: - name: foo cluster: server: https://example.com users: - name: alice user: token: deadbeef contexts: - name: default con...
} controller, err := newControllerWithTestServer(serve, true) if err != nil { t.Errorf("%v: Unexpected error while creating test admission controller/server: %v", tc.note, err) continue } obj := makeReplicaSet() attrs := admission.NewAttributesRecord(obj, nil, obj.GroupVersionKind(), obj.Namespace...
{ w.Write([]byte(tc.body)) }
conditional_block
admission_test.go
("", "") if err != nil { t.Fatalf("Unexpected error while creating temporary file: %v", err) } p := tempfile.Name() defer os.Remove(p) kubeconfig := ` clusters: - name: foo cluster: server: https://example.com users: - name: alice user: token: deadbeef contexts: - name: default con...
configFile, err := makeAdmissionControlConfigFile(kubeConfigFile) if err != nil { return nil, err } defer os.Remove(configFile) file, err := os.Open(configFile) if err != nil { return nil, err } controller, err := newAdmissionController(file) if err != nil { return nil, err } mockClient := &fake.C...
} defer os.Remove(kubeConfigFile)
random_line_split