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 |
|---|---|---|---|---|
azure_logcollector.go | //go:build e2e
// +build e2e
/*
Copyright 2020 The Kubernetes 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... |
azManagedControlPlane := &infrav1.AzureManagedControlPlane{}
err := managementClusterClient.Get(ctx, key, azManagedControlPlane)
return azManagedControlPlane, err
}
func getAzureMachine(ctx context.Context, managementClusterClient client.Client, m *clusterv1.Machine) (*infrav1.AzureMachine, error) {
key := client... | key := client.ObjectKey{
Namespace: namespace,
Name: name,
} | random_line_split |
azure_logcollector.go | //go:build e2e
// +build e2e
/*
Copyright 2020 The Kubernetes 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... |
} else {
isWindows = isAzureMachinePoolWindows(am)
}
cluster, err := util.GetClusterFromMetadata(ctx, managementClusterClient, mp.ObjectMeta)
if err != nil {
return err
}
for i, instance := range mp.Spec.ProviderIDList {
if mp.Status.NodeRefs != nil && len(mp.Status.NodeRefs) >= (i+1) {
hostname := mp... | {
return err
} | conditional_block |
azure_logcollector.go | //go:build e2e
// +build e2e
/*
Copyright 2020 The Kubernetes 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... | (cluster *clusterv1.Cluster, hostname string, isWindows bool, outputPath string) error {
nodeOSType := azure.LinuxOS
if isWindows {
nodeOSType = azure.WindowsOS
}
Logf("Collecting logs for %s node %s in cluster %s in namespace %s\n", nodeOSType, hostname, cluster.Name, cluster.Namespace)
controlPlaneEndpoint :=... | collectLogsFromNode | identifier_name |
azure_logcollector.go | //go:build e2e
// +build e2e
/*
Copyright 2020 The Kubernetes 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... | {
var err error
req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, *bootDiagnostics.SerialConsoleLogBlobURI, http.NoBody)
if err != nil {
return errors.Wrap(err, "failed to create HTTP request")
}
resp, err := http.DefaultClient.Do(req)
if err != nil || resp.StatusCode != 200 {
return erro... | identifier_body | |
drkey.go | // Copyright 2021 ETH Zurich
//
// 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 wri... | (buff []byte, req *E2EReservationSetup) {
minSize := minSizeE2ESetupReq(req)
assert(len(buff) >= minSize, "buffer too short (actual %d < minimum %d)",
len(buff), minSize)
offset := minSizeBaseReq(&req.BaseRequest)
serializeBaseRequest(buff[:offset], &req.BaseRequest)
// steps:
req.Steps.Serialize(buff[offset:]... | serializeE2EReservationSetup | identifier_name |
drkey.go | // Copyright 2021 ETH Zurich
//
// 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 wri... |
func serializeE2EReservationSetup(buff []byte, req *E2EReservationSetup) {
minSize := minSizeE2ESetupReq(req)
assert(len(buff) >= minSize, "buffer too short (actual %d < minimum %d)",
len(buff), minSize)
offset := minSizeBaseReq(&req.BaseRequest)
serializeBaseRequest(buff[:offset], &req.BaseRequest)
// steps:... | {
minSize := minSizeBaseReq(req)
assert(len(buff) >= minSize, "buffer too short (actual %d < minimum %d)",
len(buff), minSize)
offset := req.Id.Len()
// ID, index and timestamp:
req.Id.Read(buff[:offset]) // ignore errors (length was already checked)
buff[offset] = byte(req.Index)
offset++
binary.BigEndian.Pu... | identifier_body |
drkey.go | // Copyright 2021 ETH Zurich
//
// 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 wri... | return validateBasic(ctx, conn, payloads, res.Authenticators,
steps, srcHost, reqTimestamp)
}
func getKeys(ctx context.Context, conn DRKeyGetter, steps []base.PathStep,
srcHost net.IP, valTime time.Time) ([]drkey.Key, error) {
if len(steps) < 2 {
return nil, serrors.New("wrong path in request")
}
return getK... | res.Authenticators = res.Authenticators[:res.FailedAS+1]
steps = steps[:res.FailedAS+1]
payloads := serializeSetupError(res, reqTimestamp) | random_line_split |
drkey.go | // Copyright 2021 ETH Zurich
//
// 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 wri... |
return nil
}
func checkValidAuthenticatorsAndPath(res interface{}, steps base.PathSteps) error {
if res == nil {
return serrors.New("no response")
}
if steps == nil {
return serrors.New("no path")
}
return nil
}
func checkEqualLength(authenticators [][]byte, steps base.PathSteps) error {
if len(steps) != ... | {
return serrors.New("validation failed for response")
} | conditional_block |
cli.rs | #[macro_use]
extern crate bma_benchmark;
#[macro_use]
extern crate prettytable;
use clap::Clap;
use log::info;
use num_format::{Locale, ToFormattedString};
use prettytable::Table;
use rand::prelude::*;
use std::collections::BTreeMap;
use std::sync::{atomic, Arc};
use std::time::{Duration, Instant};
use tokio::signal::u... | if let Some(ref msg) = opts.message {
let topic = opts.topic.expect(ERR_TOPIC_NOT_SPECIFIED);
if let Some(message_size) = msg.strip_prefix("==") {
let mut m = Vec::new();
let size = byte_unit::Byte::from_str(&message_size)
.unwrap()
... | let mut client = client::Client::connect(&config).await.unwrap(); | random_line_split |
cli.rs | #[macro_use]
extern crate bma_benchmark;
#[macro_use]
extern crate prettytable;
use clap::Clap;
use log::info;
use num_format::{Locale, ToFormattedString};
use prettytable::Table;
use rand::prelude::*;
use std::collections::BTreeMap;
use std::sync::{atomic, Arc};
use std::time::{Duration, Instant};
use tokio::signal::u... | (topic: Option<&String>) -> Vec<String> {
topic
.expect(ERR_TOPIC_NOT_SPECIFIED)
.split(',')
.into_iter()
.map(ToOwned::to_owned)
.collect::<Vec<String>>()
}
#[tokio::main(worker_threads = 1)]
async fn main() {
let opts = Opts::parse();
env_logger::Builder::new()
... | parse_topics | identifier_name |
cli.rs | #[macro_use]
extern crate bma_benchmark;
#[macro_use]
extern crate prettytable;
use clap::Clap;
use log::info;
use num_format::{Locale, ToFormattedString};
use prettytable::Table;
use rand::prelude::*;
use std::collections::BTreeMap;
use std::sync::{atomic, Arc};
use std::time::{Duration, Instant};
use tokio::signal::u... | {
let opts = Opts::parse();
env_logger::Builder::new()
.target(env_logger::Target::Stdout)
.filter_level(if opts.benchmark || opts.top {
log::LevelFilter::Info
} else {
log::LevelFilter::Trace
})
.init();
let queue_size = if opts.benchmark { 25... | identifier_body | |
cli.rs | #[macro_use]
extern crate bma_benchmark;
#[macro_use]
extern crate prettytable;
use clap::Clap;
use log::info;
use num_format::{Locale, ToFormattedString};
use prettytable::Table;
use rand::prelude::*;
use std::collections::BTreeMap;
use std::sync::{atomic, Arc};
use std::time::{Duration, Instant};
use tokio::signal::u... | ;
assert!(client.is_connected());
let bi: u32 = rng.gen();
workers.push(Arc::new(BenchmarkWorker::new(
format!("{}/{}", bi, i),
client,
r_client,
data_channel,
)));
}
let mut futures = Vec::new();
staged_benchmark_start!("subscr... | {
(client.take_data_channel().unwrap(), None)
} | conditional_block |
deephash_test.go | // Copyright (c) 2020 Tailscale Inc & 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 deephash
import (
"archive/tar"
"bufio"
"bytes"
"crypto/sha256"
"fmt"
"math"
"reflect"
"runtime"
"testing"
"go4.org/mem"
"inet.... | (b []byte) []byte {
return append(b, p...)
}
func TestHash(t *testing.T) {
type tuple [2]interface{}
type iface struct{ X interface{} }
type scalars struct {
I8 int8
I16 int16
I32 int32
I64 int64
I int
U8 uint8
U16 uint16
U32 uint32
U64 uint64
U uint
UP uintptr
F32 float3... | AppendTo | identifier_name |
deephash_test.go | // Copyright (c) 2020 Tailscale Inc & 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 deephash
import (
"archive/tar"
"bufio"
"bytes"
"crypto/sha256"
"fmt"
"math"
"reflect"
"runtime"
"testing"
"go4.org/mem"
"inet.... | func TestPrintArray(t *testing.T) {
type T struct {
X [32]byte
}
x := T{X: [32]byte{1: 1, 31: 31}}
var got bytes.Buffer
bw := bufio.NewWriter(&got)
h := &hasher{bw: bw}
h.hashValue(reflect.ValueOf(x))
bw.Flush()
const want = "\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0... | if len(got) != 1 {
t.Errorf("got %d results; want 1", len(got))
}
}
| random_line_split |
deephash_test.go | // Copyright (c) 2020 Tailscale Inc & 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 deephash
import (
"archive/tar"
"bufio"
"bytes"
"crypto/sha256"
"fmt"
"math"
"reflect"
"runtime"
"testing"
"go4.org/mem"
"inet.... |
func TestExhaustive(t *testing.T) {
seen := make(map[Sum]bool)
for i := 0; i < 100000; i++ {
s := Hash(i)
if seen[s] {
t.Fatalf("hash collision %v", i)
}
seen[s] = true
}
}
// verify this doesn't loop forever, as it used to (Issue 2340)
func TestMapCyclicFallback(t *testing.T) {
type T struct {
M ma... | {
b.ReportAllocs()
node := new(tailcfg.Node)
for i := 0; i < b.N; i++ {
sink = Hash(node)
}
} | identifier_body |
deephash_test.go | // Copyright (c) 2020 Tailscale Inc & 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 deephash
import (
"archive/tar"
"bufio"
"bytes"
"crypto/sha256"
"fmt"
"math"
"reflect"
"runtime"
"testing"
"go4.org/mem"
"inet.... |
seen[s] = true
}
}
// verify this doesn't loop forever, as it used to (Issue 2340)
func TestMapCyclicFallback(t *testing.T) {
type T struct {
M map[string]interface{}
}
v := &T{
M: map[string]interface{}{},
}
v.M["m"] = v.M
Hash(v)
}
func TestArrayAllocs(t *testing.T) {
if version.IsRace() {
t.Skip("... | {
t.Fatalf("hash collision %v", i)
} | conditional_block |
record_db.go | //
// Copyright 2019 Insolar Technologies GmbH
//
// 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... | if err != nil && err != ErrNotFound {
return err
}
lastKnowPulse = rec.ID.Pulse()
}
position++
err = setPosition(txn, rec.ID, position)
if err != nil {
return err
}
}
// set position for last record
err := setLastKnownPosition(txn, lastKnowPulse, position)
if err != nil {... | }
// fetch position for a new pulse
position, err = getLastKnownPosition(txn, rec.ID.Pulse()) | random_line_split |
record_db.go | //
// Copyright 2019 Insolar Technologies GmbH
//
// 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... |
func (k lastKnownRecordPositionKey) Scope() store.Scope {
return store.ScopeRecordPosition
}
func (k lastKnownRecordPositionKey) ID() []byte {
return bytes.Join([][]byte{{lastKnownRecordPositionKeyPrefix}, k.pn.Bytes()}, nil)
}
// NewRecordDB creates new DB storage instance.
func NewRecordDB(db *store.BadgerDB) *... | {
return fmt.Sprintf("lastKnownRecordPositionKey. pulse: %d", k.pn)
} | identifier_body |
record_db.go | //
// Copyright 2019 Insolar Technologies GmbH
//
// 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... | (pn insolar.PulseNumber) (uint32, error) {
var position uint32
var err error
err = r.db.Backend().View(func(txn *badger.Txn) error {
position, err = getLastKnownPosition(txn, pn)
return err
})
return position, err
}
// AtPosition returns record ID for a specific pulse and a position
func (r *RecordDB) AtPos... | LastKnownPosition | identifier_name |
record_db.go | //
// Copyright 2019 Insolar Technologies GmbH
//
// 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... |
}
// set position for last record
err := setLastKnownPosition(txn, lastKnowPulse, position)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
return nil
}
// setRecord is a helper method for storaging record to db in scope of txn.
func setRecord(txn *badger.Txn, key stor... | {
return err
} | conditional_block |
queueing_honey_badger.rs | #![deny(unused_must_use)]
//! Network tests for Queueing Honey Badger.
use std::collections::BTreeSet;
use std::sync::Arc;
use hbbft::dynamic_honey_badger::{DynamicHoneyBadger, JoinPlan};
use hbbft::queueing_honey_badger::{Change, ChangeState, Input, QueueingHoneyBadger};
use hbbft::sender_queue::{Message, SenderQueu... | (node_info: NewNodeInfo<SQ>, seed: TestRngSeed) -> (SQ, Step<QHB>) {
let mut rng: TestRng = TestRng::from_seed(seed);
let peer_ids = node_info.netinfo.other_ids().cloned();
let netinfo = node_info.netinfo.clone();
let dhb =
DynamicHoneyBadger::builder().build(netinfo, node_info.secret_key, node_... | new_queueing_hb | identifier_name |
queueing_honey_badger.rs | #![deny(unused_must_use)]
//! Network tests for Queueing Honey Badger.
use std::collections::BTreeSet;
use std::sync::Arc;
use hbbft::dynamic_honey_badger::{DynamicHoneyBadger, JoinPlan};
use hbbft::queueing_honey_badger::{Change, ChangeState, Input, QueueingHoneyBadger};
use hbbft::sender_queue::{Message, SenderQueu... | info!(
"{:?} has finished waiting for node removal; still waiting: {:?}",
stepped_id, awaiting_removal
);
if awaiting_removal.is_empty() {
info!("Removing first correct node from the test network");
saved_first_correct ... | random_line_split | |
queueing_honey_badger.rs | #![deny(unused_must_use)]
//! Network tests for Queueing Honey Badger.
use std::collections::BTreeSet;
use std::sync::Arc;
use hbbft::dynamic_honey_badger::{DynamicHoneyBadger, JoinPlan};
use hbbft::queueing_honey_badger::{Change, ChangeState, Input, QueueingHoneyBadger};
use hbbft::sender_queue::{Message, SenderQueu... |
fn do_test_queueing_honey_badger_first_delivery_silent(seed: TestRngSeed) {
test_queueing_honey_badger_different_sizes(NodeOrderAdversary::new, 30, seed);
}
| {
test_queueing_honey_badger_different_sizes(ReorderingAdversary::new, 30, seed);
} | identifier_body |
queueing_honey_badger.rs | #![deny(unused_must_use)]
//! Network tests for Queueing Honey Badger.
use std::collections::BTreeSet;
use std::sync::Arc;
use hbbft::dynamic_honey_badger::{DynamicHoneyBadger, JoinPlan};
use hbbft::queueing_honey_badger::{Change, ChangeState, Input, QueueingHoneyBadger};
use hbbft::sender_queue::{Message, SenderQueu... |
if rejoined_first_correct && awaiting_second_half.contains(&stepped_id) {
// Input the second half of user transactions into the stepped node.
input_second_half(&mut net, stepped_id, num_txs, &mut rng);
awaiting_second_half.remove(&stepped_id);
}
}
let node_... | {
// If the stepped node started voting to add the first correct node back,
// take a note of that and rejoin it.
if let Some(join_plan) =
net.get(stepped_id)
.unwrap()
.outputs()
.iter()
... | conditional_block |
lru_cache.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... | (&mut self) {
unsafe {
let _: ~LruEntry<K, V> = cast::transmute(self.head);
let _: ~LruEntry<K, V> = cast::transmute(self.tail);
}
}
}
#[cfg(test)]
mod tests {
use super::LruCache;
fn assert_opt_eq<V: Eq>(opt: Option<&V>, v: V) {
assert!(opt.is_some());
... | drop | identifier_name |
lru_cache.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... |
unsafe {
cur = (*cur).next;
match (*cur).key {
// should never print nil
None => try!(write!(f.buf, "nil")),
Some(ref k) => try!(write!(f.buf, "{}", *k)),
}
}
try!(write!(f.bu... | { try!(write!(f.buf, ", ")) } | conditional_block |
lru_cache.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... | write!(f.buf, r"\}")
}
}
impl<K: Hash + TotalEq, V> Container for LruCache<K, V> {
/// Return the number of key-value pairs in the cache.
fn len(&self) -> uint {
self.map.len()
}
}
impl<K: Hash + TotalEq, V> Mutable for LruCache<K, V> {
/// Clear the cache of all key-value pairs.
... | random_line_split | |
lru_cache.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... |
#[inline]
fn detach(&mut self, node: *mut LruEntry<K, V>) {
unsafe {
(*(*node).prev).next = (*node).next;
(*(*node).next).prev = (*node).prev;
}
}
#[inline]
fn attach(&mut self, node: *mut LruEntry<K, V>) {
unsafe {
(*node).next = (*self... | {
if self.len() > 0 {
let lru = unsafe { (*self.tail).prev };
self.detach(lru);
unsafe {
match (*lru).key {
None => (),
Some(ref k) => { self.map.pop(&KeyRef{k: k}); }
}
}
}
} | identifier_body |
chartdata.py | ##coding=utf-8
from Persistence import Persistent
from BTrees.OOBTree import OOBTree
from DateTime import DateTime
from AccessControl import ClassSecurityInfo
from Globals import InitializeClass
from Products.CMFCore.utils import getToolByName
from zope.app.component.hooks import getSite
class EventBrain:
"""
... | def Title(self):
return self.title
# TODO: Remover a partir de 01/04/2013
# def absolute_url_path(self):
# chart_folder = self.patient.chartFolder
# return chart_folder.absolute_url_path() + self.url_sufix
class ChartData(Persistent):
__allow_access_to_unprotected_subobjects__ =... | tal = getSite()
return getToolByName(portal, 'portal_membership').getAuthenticatedMember()
| identifier_body |
chartdata.py | ##coding=utf-8
from Persistence import Persistent
from BTrees.OOBTree import OOBTree
from DateTime import DateTime
from AccessControl import ClassSecurityInfo
from Globals import InitializeClass
from Products.CMFCore.utils import getToolByName
from zope.app.component.hooks import getSite
class EventBrain:
"""
... |
elif self.related_obj.portal_type == 'Image':
return 'Imagem '
elif self.related_obj.portal_type == 'File':
return 'Arquivo '
return ''
def posfix(self):
'''
called by eprint
'''
if self.type == Event.CREATION:
... | return 'Documento ' | conditional_block |
chartdata.py | ##coding=utf-8
from Persistence import Persistent
from BTrees.OOBTree import OOBTree
from DateTime import DateTime
from AccessControl import ClassSecurityInfo
from Globals import InitializeClass
from Products.CMFCore.utils import getToolByName
from zope.app.component.hooks import getSite
class EventBrain:
"""
... | def posfix(self):
'''
called by eprint
'''
if self.type == Event.CREATION:
if self.related_obj.meta_type == 'Visit':
return self._visit_review_state()
else:
return ' adicionado.'
def getAuthor(self):
'''
If ... | return 'Imagem '
elif self.related_obj.portal_type == 'File':
return 'Arquivo '
return ''
| random_line_split |
chartdata.py | ##coding=utf-8
from Persistence import Persistent
from BTrees.OOBTree import OOBTree
from DateTime import DateTime
from AccessControl import ClassSecurityInfo
from Globals import InitializeClass
from Products.CMFCore.utils import getToolByName
from zope.app.component.hooks import getSite
class EventBrain:
"""
... | (self):
'''
function that transform an event instance in a dictionary to be exported.
'''
if isinstance(self.related_obj, ChartItemEventWrapper):
return {'type': self.type, 'date': self.date, 'author': self.author, 'related_obj' : self.related_obj.meta_type,
... | export_dict | identifier_name |
utils.py | # This file is part of the Adblock Plus web scripts,
# Copyright (C) 2006-present eyeo GmbH
#
# Adblock Plus is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# Adblock Plus is distributed in the hop... | screenshot = reportData.get('screenshot', None)
if screenshot != None:
reportData['hasscreenshot'] = 2 if reportData.get('screenshotEdited', False) else 1
try:
saveScreenshot(guid, screenshot)
except (TypeError, UnicodeEncodeError):
reportData['hasscreenshot'] = 0... |
def saveReport(guid, reportData, isNew=False):
cursor = get_db().cursor() | random_line_split |
utils.py | # This file is part of the Adblock Plus web scripts,
# Copyright (C) 2006-present eyeo GmbH
#
# Adblock Plus is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# Adblock Plus is distributed in the hop... | (email):
return hmac.new(get_config().get('reports', 'secret'), email.encode('utf-8')).hexdigest()
def getDigestId(email):
hash = hashlib.md5()
hash.update(email.encode('utf-8'))
return hash.hexdigest()
def getDigestPath(dir, email):
return os.path.join(dir, getDigestId(email) + '.html')
def g... | getUserId | identifier_name |
utils.py | # This file is part of the Adblock Plus web scripts,
# Copyright (C) 2006-present eyeo GmbH
#
# Adblock Plus is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# Adblock Plus is distributed in the hop... |
@cached(600)
def get_db():
database = get_config().get('reports', 'database')
dbuser = get_config().get('reports', 'dbuser')
dbpasswd = get_config().get('reports', 'dbpassword')
if os.name == 'nt':
return MySQLdb.connect(user=dbuser, passwd=dbpasswd, db=database, use_unicode=True, charset='ut... | hash = hashlib.md5()
hash.update(get_config().get('reports', 'secret'))
hash.update(id)
hash.update(str(year))
hash.update(str(week))
return hash.hexdigest() | identifier_body |
utils.py | # This file is part of the Adblock Plus web scripts,
# Copyright (C) 2006-present eyeo GmbH
#
# Adblock Plus is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# Adblock Plus is distributed in the hop... |
for row in rows:
yield row
offset += len(rows)
def getReportsForUser(contact):
cursor = get_db().cursor(MySQLdb.cursors.DictCursor)
executeQuery(cursor,
'''SELECT guid, type, UNIX_TIMESTAMP(ctime) AS ctime, status, site, contact,
comment, hasscreensh... | break | conditional_block |
linux_abi.go | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | () BinaryConversion {
var certsAddress unsafe.Pointer
if len(r.Certs) != 0 {
certsAddress = unsafe.Pointer(&r.Certs[0])
}
return &SnpExtendedReportReqABI{
Data: r.Data,
CertsAddress: certsAddress,
CertsLength: r.CertsLength,
}
}
// SnpUserGuestRequestABI is Linux's sev-guest ioctl abi for issuing... | ABI | identifier_name |
linux_abi.go | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | // EsRetry is the code for a retry instruction emulation
EsRetry
)
// SevEsErr is an error that interprets SEV-ES guest-host communication results.
type SevEsErr struct {
Result EsResult
}
func (err *SevEsErr) Error() string {
if err.Result == EsUnsupported {
return "requested operation not supported"
}
if er... | EsException | random_line_split |
linux_abi.go | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
if err := r.reqConv.Finish(s.ReqData); err != nil {
return fmt.Errorf("could not finalize request data: %v", err)
}
if err := r.respConv.Finish(s.RespData); err != nil {
return fmt.Errorf("could not finalize response data: %v", err)
}
s.FwErr = r.abi.FwErr
return nil
}
// BinaryConversion is an interface th... | {
return fmt.Errorf("Finish argument is %v. Expects a *SnpUserGuestRequestSafe", reflect.TypeOf(b))
} | conditional_block |
linux_abi.go | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
// ABI returns the same object since it doesn't need a separate representation across the interface.
func (r *SnpReportRespABI) ABI() BinaryConversion { return r }
// Pointer returns a pointer to the object itself.
func (r *SnpReportRespABI) Pointer() unsafe.Pointer {
return unsafe.Pointer(r)
}
// Finish checks th... | { return nil } | identifier_body |
EachBehavior.ts | import EachAttributes from "behavior/core/each/EachAttributes";
import SimpleMap from "interface/SimpleMap";
import Nestable from "interface/ables/Nestable";
import ScopeImpl from "scope/ScopeImpl";
import ComponentFactory from "component/ComponentFactory";
import IdStrategy from "behavior/core/each/IdStrategy";
import... |
const tagText: string = validated ? elementAsString(template) : null;
const params: EachTemplateAttributes = TEMPLATE_ATTRIBUTE_PARSER.parse(template, prefix, validated, tagText);
switch (params.type) {
case EachTemplateType.EMPTY:
++emptyCount;
this.empty = this.createFactory(template, params... | {
errors.add(`template definitions must only have one top-level tag in repeat on expression: ${ this.getExpression() } and markup: ${ template.innerHTML }`);
continue;
} | conditional_block |
EachBehavior.ts | import EachAttributes from "behavior/core/each/EachAttributes";
import SimpleMap from "interface/SimpleMap";
import Nestable from "interface/ables/Nestable";
import ScopeImpl from "scope/ScopeImpl";
import ComponentFactory from "component/ComponentFactory";
import IdStrategy from "behavior/core/each/IdStrategy";
import... | import EachTemplateAttributes from "behavior/core/each/EachTemplateAttributes";
import AttributeParserImpl from "validator/AttributeParserImpl";
import { NodeTypes } from "Constants";
import { ATTRIBUTE_DELIMITER } from "const/HardValues";
import Messages from "util/Messages";
import AbstractContainerBehavior from "beh... | import AttributeParser from 'validator/AttributeParser'; | random_line_split |
EachBehavior.ts | import EachAttributes from "behavior/core/each/EachAttributes";
import SimpleMap from "interface/SimpleMap";
import Nestable from "interface/ables/Nestable";
import ScopeImpl from "scope/ScopeImpl";
import ComponentFactory from "component/ComponentFactory";
import IdStrategy from "behavior/core/each/IdStrategy";
import... | (name: string, payload?: any): void {
if (this.empty) {
this.empty.tell(name, payload);
}
if (this.first) {
this.first.tell(name, payload);
}
if (this.last) {
this.last.tell(name, payload);
}
for (const key in this.map) {
if (!this.map.hasOwnProperty(key)) {
continue;
}
const com... | tellChildren | identifier_name |
EachBehavior.ts | import EachAttributes from "behavior/core/each/EachAttributes";
import SimpleMap from "interface/SimpleMap";
import Nestable from "interface/ables/Nestable";
import ScopeImpl from "scope/ScopeImpl";
import ComponentFactory from "component/ComponentFactory";
import IdStrategy from "behavior/core/each/IdStrategy";
import... |
public onInit(): void {
this.elIsSelect = this.getEl().tagName.toLowerCase() === "select";
}
public onMount(): void {
this.initFields();
this.initScope();
this.initIdStrategy();
this.parseChildElements();
this.onTargetChange(null, this.getMediator().get());
if (this.isMutable()) {
this.getMediat... | {
super();
this.setFlag(BehaviorFlags.CHILD_CONSUMPTION_PROHIBITED);
this.setDefaults(DEFAULT_ATTRIBUTES);
this.setValidations({
idkey: [validateDefined, validateNotEmptyString],
expression: [validateNotEmptyString, validateNotNullIfFieldEquals("mode", "expression")],
mode: [validateDefined, validateOn... | identifier_body |
submittestevent.go | //(C) Copyright [2020] Hewlett Packard Enterprise Development LP
//
//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 a... |
func validSeverity(got string) bool {
severities := getAllowedSeverities()
for _, severity := range severities {
if severity == got {
return true
}
}
return false
}
func getAllowedEventTypes() []string {
return []string{
"Alert",
"MetricReport",
"Other",
"ResourceAdded",
"ResourceRemoved",
"R... | {
events := getAllowedEventTypes()
for _, event := range events {
if event == got {
return true
}
}
return false
} | identifier_body |
submittestevent.go | //(C) Copyright [2020] Hewlett Packard Enterprise Development LP
//
//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 a... | for _, event := range events {
if event == got {
return true
}
}
return false
}
func validSeverity(got string) bool {
severities := getAllowedSeverities()
for _, severity := range severities {
if severity == got {
return true
}
}
return false
}
func getAllowedEventTypes() []string {
return []str... | func validEventType(got string) bool {
events := getAllowedEventTypes() | random_line_split |
submittestevent.go | //(C) Copyright [2020] Hewlett Packard Enterprise Development LP
//
//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 a... | (reqBody []byte) (*common.Event, string, string, []interface{}) {
var testEvent common.Event
var req map[string]interface{}
json.Unmarshal(reqBody, &req)
if val, ok := req["MessageId"]; ok {
switch v := val.(type) {
case string:
testEvent.MessageID = v
default:
return nil, response.PropertyValueTypeErro... | validAndGenSubTestReq | identifier_name |
submittestevent.go | //(C) Copyright [2020] Hewlett Packard Enterprise Development LP
//
//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 a... |
// we need common.MessageData to find the correct destination to send test event
var message common.MessageData
message.Events = append(message.Events, *testEvent)
messageBytes, _ := json.Marshal(message)
eventUniqueID := uuid.NewV4().String()
for _, sub := range subscriptions {
for _, origin := range sub.Even... | {
// Internal error
errMsg := "error while trying to find the event destination"
l.LogWithFields(ctx).Error(errMsg)
return common.GeneralError(http.StatusInternalServerError, response.InternalError, errMsg, nil, nil)
} | conditional_block |
index.js | angular.module('MyApp', ['ionic', 'ui.calendar', 'ui.bootstrap'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('eventmenu', {
url: "/event",
abstract: true,
templateUrl: "templates/event-menu.html"
})
.state('eventmenu.home', {
url: "/home",
... | }).then(function(popover) {
$scope.recado = popover;
});
$ionicPopover.fromTemplateUrl('templates/user-filho.html', {
scope: $scope,
}).then(function(popover) {
$scope.UserFilho = popover;
});
$scope.scrap = [
{
id: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do e... | });
$ionicPopover.fromTemplateUrl('templates/recado.html', {
scope: $scope, | random_line_split |
index.js | angular.module('MyApp', ['ionic', 'ui.calendar', 'ui.bootstrap'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('eventmenu', {
url: "/event",
abstract: true,
templateUrl: "templates/event-menu.html"
})
.state('eventmenu.home', {
url: "/home",
... | $scope.shownGroup = group;
}
};
$scope.isGroupShown = function(group) {
return $scope.shownGroup === group;
};
$scope.demo = 'ios';
$scope.setPlatform = function(p) {
document.body.classList.remove('platform-ios');
document.body.classList.remove('platform-android');
document.body.classLis... | .shownGroup = null;
} else {
| conditional_block |
billing_controller.go | /*
Copyright 2023 sealos.
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
distrib... | me.Hour).Add(time.Hour); t.Before(currentHourTime) || t.Equal(currentHourTime); t = t.Add(time.Hour) {
if err = r.billingWithHourTime(ctx, t.UTC(), nsListStr, ns.Name, dbClient); err != nil {
r.Logger.Error(err, "billing with hour time failed", "time", t.Format(time.RFC3339))
return ctrl.Result{}, err
}
}
r... | 开右闭
for t := queryTime.Truncate(ti | conditional_block |
billing_controller.go | /*
Copyright 2023 sealos.
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
distrib... | identifier_body | ||
billing_controller.go | /*
Copyright 2023 sealos.
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
distrib... | goURI == "" {
return fmt.Errorf("env %s is empty", database.MongoURI)
}
r.Logger = ctrl.Log.WithName("controller").WithName("Billing")
if err := r.initDB(); err != nil {
r.Logger.Error(err, "init db failed")
}
r.AccountSystemNamespace = os.Getenv(ACCOUNTNAMESPACEENV)
if r.AccountSystemNamespace == "" {
r.Ac... | MongoURI); r.mon | identifier_name |
billing_controller.go | /*
Copyright 2023 sealos.
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
distrib... | //+kubebuilder:rbac:groups=account.sealos.io,resources=accountbalances,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=account.sealos.io,resources=accountbalances/status,verbs=get;list;watch;create;update;patch;delete
// Reconcile is part of the main kubernetes reconciliation loop which aims... |
//+kubebuilder:rbac:groups=core,resources=namespaces,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=core,resources=resourcequotas,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=rolebindings,verbs=get;list;watch;create;update;pa... | random_line_split |
fetch_places.rs | use crate::models::{Coord, Place};
use crate::DbOpt;
use diesel;
use diesel::prelude::*;
use diesel::result::{DatabaseErrorKind, Error as DieselError};
use log::{debug, info, warn};
use reqwest::{self, Client, Response};
use serde_json::Value;
use slug::slugify;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structo... | Some("station") => Some(18),
_ => None,
})
.or_else(|| match tag_str(tags, "amenity") {
Some("bus_station") => Some(16),
Some("exhibition_center") => Some(20),
Some("kindergarten") => Some(15),
Some("... | Some("pedestrian") => Some(15), // torg
Some("rest_area") => Some(16),
_ => None,
})
.or_else(|| match tag_str(tags, "public_transport") { | random_line_split |
fetch_places.rs | use crate::models::{Coord, Place};
use crate::DbOpt;
use diesel;
use diesel::prelude::*;
use diesel::result::{DatabaseErrorKind, Error as DieselError};
use log::{debug, info, warn};
use reqwest::{self, Client, Response};
use serde_json::Value;
use slug::slugify;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structo... |
fn tag_str<'a>(tags: &'a Value, name: &str) -> Option<&'a str> {
tags.get(name).and_then(Value::as_str)
}
fn get_or_create_place(
c: &PgConnection,
t_osm_id: i64,
name: &str,
level: i16,
) -> Result<Place, diesel::result::Error> {
use crate::schema::places::dsl::*;
places
.filter(... | {
if let Some(tags) = obj.get("tags") {
let name = tags
.get("name:sv")
//.or_else(|| tags.get("name:en"))
.or_else(|| tags.get("name"))
.and_then(Value::as_str);
let level = tags
.get("admin_level")
.and_then(Value::as_str)
... | identifier_body |
fetch_places.rs | use crate::models::{Coord, Place};
use crate::DbOpt;
use diesel;
use diesel::prelude::*;
use diesel::result::{DatabaseErrorKind, Error as DieselError};
use log::{debug, info, warn};
use reqwest::{self, Client, Response};
use serde_json::Value;
use slug::slugify;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structo... | <'a>(tags: &'a Value, name: &str) -> Option<&'a str> {
tags.get(name).and_then(Value::as_str)
}
fn get_or_create_place(
c: &PgConnection,
t_osm_id: i64,
name: &str,
level: i16,
) -> Result<Place, diesel::result::Error> {
use crate::schema::places::dsl::*;
places
.filter(
... | tag_str | identifier_name |
inbound.rs | //! The inbound thread.
//!
//! This module handles all the inbound SWIM messages.
use super::AckSender;
use crate::{member::Health,
server::{outbound,
Server},
swim::{Ack,
Ping,
PingReq,
Swim,
Swim... | (server: &Server,
socket: &UdpSocket,
tx_outbound: &AckSender,
addr: SocketAddr,
mut msg: Ack) {
trace!("Ack from {}@{}", msg.from.id, addr);
if msg.forward_to.is_some() && *server.member_id != msg.forwar... | process_ack_mlw_smw_rhw | identifier_name |
inbound.rs | //! The inbound thread.
//!
//! This module handles all the inbound SWIM messages.
use super::AckSender;
use crate::{member::Health,
server::{outbound,
Server},
swim::{Ack,
Ping,
PingReq,
Swim,
Swim... |
match socket.recv_from(&mut recv_buffer[..]) {
Ok((length, addr)) => {
let swim_payload = match server.unwrap_wire(&recv_buffer[0..length]) {
Ok(swim_payload) => swim_payload,
Err(e) => {
// NOTE: In the future, we mig... | {
thread::sleep(Duration::from_millis(100));
continue;
} | conditional_block |
inbound.rs | //! The inbound thread.
//!
//! This module handles all the inbound SWIM messages.
use super::AckSender;
use crate::{member::Health,
server::{outbound,
Server},
swim::{Ack,
Ping,
PingReq,
Swim,
Swim... | addr: SocketAddr,
mut msg: Ack) {
trace!("Ack from {}@{}", msg.from.id, addr);
if msg.forward_to.is_some() && *server.member_id != msg.forward_to.as_ref().unwrap().id {
let (forward_to_addr, from_addr) = {
let forward_to = msg.forward_to.... | fn process_ack_mlw_smw_rhw(server: &Server,
socket: &UdpSocket,
tx_outbound: &AckSender, | random_line_split |
inbound.rs | //! The inbound thread.
//!
//! This module handles all the inbound SWIM messages.
use super::AckSender;
use crate::{member::Health,
server::{outbound,
Server},
swim::{Ack,
Ping,
PingReq,
Swim,
Swim... | {
outbound::ack_mlr_smr_rhw(server, socket, &msg.from, addr, msg.forward_to);
// Populate the member for this sender with its remote address
msg.from.address = addr.ip().to_string();
trace!("Ping from {}@{}", msg.from.id, addr);
if msg.from.departed {
server.insert_member_mlw_rhw(msg.from, H... | identifier_body | |
sandbox_second.py |
#%%
# setup
#base
import os
import numpy as np
import pandas as pd
import json
import time
import random
#tensorflow
from tensorflow.keras.layers import Input, Dense, Flatten, Conv2D, MaxPooling2D, concatenate, Subtract, Dropout
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.losses imp... | (mat):
empty_array = np.full((30, 30), 0, dtype=np.float32)
if(len(mat) != 0):
mat = np.asarray(mat, dtype=np.float32)
empty_array[:mat.shape[0], : mat.shape[1]] = mat
return np.expand_dims(empty_array, axis= 2)
#%%
train_input = []
cnt = 0
# use all the tasks in train
# use inpu... | enhance_mat_30x30 | identifier_name |
sandbox_second.py | #%%
# setup
#base
import os
import numpy as np
import pandas as pd
import json
import time
import random
#tensorflow
from tensorflow.keras.layers import Input, Dense, Flatten, Conv2D, MaxPooling2D, concatenate, Subtract, Dropout
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.losses impo... |
merge = Dense(128, activation='relu')(merge)
merge = Dense(128, activation='relu')(merge)
merge = Dropout(0.3)(merge)
pretrain.mirror_tasks,
pretrain.double_line_with_multiple_colors_tasks,
# regression layers
out_1 = Dense(128, activation='relu')(merge)
out_1 = Dense(1, activation='linear', name='fzn_rows')(out_1)
... | x_2 = MaxPooling2D(pool_size=(2, 2))(x_2)
x_2 = Dropout(0.25)(x_2)
x_2 = Flatten()(x_2)
merge = concatenate([x_1, x_2]) | random_line_split |
sandbox_second.py |
#%%
# setup
#base
import os
import numpy as np
import pandas as pd
import json
import time
import random
#tensorflow
from tensorflow.keras.layers import Input, Dense, Flatten, Conv2D, MaxPooling2D, concatenate, Subtract, Dropout
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.losses imp... |
print('Thrown away samples: ')
print(cnt)
print('Total pretrain samples: ')
print(len(train_input))
#%%
# generate all the pretrain data
# 1. modified output tasks
# 2. y_labels
PRETRAIN_FUNCTIONS = [
pretrain.rotate_tasks,
pretrain.multiply_tasks,
pretrain.change_random_color_tasks,
pretrain... | _input = sample['input']
_output = sample['output']
if len(_input) > 1:
train_input.append(_input)
else:
cnt += 1
if len(_output) > 1:
train_input.append(_output)
else:
cnt += 1 | conditional_block |
sandbox_second.py |
#%%
# setup
#base
import os
import numpy as np
import pandas as pd
import json
import time
import random
#tensorflow
from tensorflow.keras.layers import Input, Dense, Flatten, Conv2D, MaxPooling2D, concatenate, Subtract, Dropout
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.losses imp... |
#%%
train_input = []
cnt = 0
# use all the tasks in train
# use input and output
for task in train_data:
for sample in task['train']:
_input = sample['input']
_output = sample['output']
if len(_input) > 1:
train_input.append(_input)
else:
... | empty_array = np.full((30, 30), 0, dtype=np.float32)
if(len(mat) != 0):
mat = np.asarray(mat, dtype=np.float32)
empty_array[:mat.shape[0], : mat.shape[1]] = mat
return np.expand_dims(empty_array, axis= 2) | identifier_body |
polyres.py | #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB 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... | paramtype = barg.param.get_type(ctx.env.schema)
arg_type_dist = barg.valtype.get_common_parent_type_distance(
paramtype, ctx.env.schema)
call_type_dist += arg_type_dist
if type_dist is None:
type_dist = call_type_dist
... | if barg.param is None:
# Skip injected bitmask argument.
continue
| random_line_split |
polyres.py | #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB 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... |
ctx.env.schema, ct = (
resolved_poly_base_type.find_common_implicitly_castable_type(
resolved,
ctx.env.schema,
)
)
if ct is not None:
# If we found a common implicitly castable type, we
... | return 0 | conditional_block |
polyres.py | #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB 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... |
def try_bind_call_args(
args: Sequence[Tuple[s_types.Type, irast.Set]],
kwargs: Mapping[str, Tuple[s_types.Type, irast.Set]],
func: s_func.CallableLike,
basic_matching_only: bool,
*,
ctx: context.ContextLevel) -> Optional[BoundCall]:
return_type = func.get_return_... | implicit_cast_distance = None
matched = []
candidates = list(candidates)
for candidate in candidates:
call = try_bind_call_args(
args, kwargs, candidate, basic_matching_only, ctx=ctx)
if call is None:
continue
total_cd = sum(barg.cast_distance for barg in c... | identifier_body |
polyres.py | #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB 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... | (NamedTuple):
func: s_func.CallableLike
args: List[BoundArg]
null_args: Set[str]
return_type: s_types.Type
has_empty_variadic: bool
_VARIADIC = ft.ParameterKind.VariadicParam
_NAMED_ONLY = ft.ParameterKind.NamedOnlyParam
_POSITIONAL = ft.ParameterKind.PositionalParam
_SET_OF = ft.TypeModifier.Se... | BoundCall | identifier_name |
httpretty.go | // Package httpretty prints your HTTP requests pretty on your terminal screen.
// You can use this package both on the client-side and on the server-side.
//
// This package provides a better way to view HTTP traffic without httputil
// DumpRequest, DumpRequestOut, and DumpResponse heavy debugging functions.
//
// You ... | () Filter {
l.mu.Lock()
f := l.filter
defer l.mu.Unlock()
return f
}
func (l *Logger) getBodyFilter() BodyFilter {
l.mu.Lock()
f := l.bodyFilter
defer l.mu.Unlock()
return f
}
func (l *Logger) cloneSkipHeader() map[string]struct{} {
l.mu.Lock()
skipped := l.skipHeader
l.mu.Unlock()
m := map[string]struct... | getFilter | identifier_name |
httpretty.go | // Package httpretty prints your HTTP requests pretty on your terminal screen.
// You can use this package both on the client-side and on the server-side.
//
// This package provides a better way to view HTTP traffic without httputil
// DumpRequest, DumpRequestOut, and DumpResponse heavy debugging functions.
//
// You ... |
if p.logger.TLS {
p.printTLSInfo(req.TLS, true)
p.printIncomingClientTLS(req.TLS)
}
p.printRequest(req)
rec := &responseRecorder{
ResponseWriter: w,
statusCode: http.StatusOK,
maxReadableBody: l.MaxResponseBody,
buf: &bytes.Buffer{},
}
defer p.printServerResponse(req, rec)
h.next.S... | {
p.printRequestInfo(req)
} | conditional_block |
httpretty.go | // Package httpretty prints your HTTP requests pretty on your terminal screen.
// You can use this package both on the client-side and on the server-side.
//
// This package provides a better way to view HTTP traffic without httputil
// DumpRequest, DumpRequestOut, and DumpResponse heavy debugging functions.
//
// You ... |
// RoundTrip implements the http.RoundTrip interface.
func (r roundTripper) RoundTrip(req *http.Request) (resp *http.Response, err error) {
tripper := r.rt
if tripper == nil {
// BUG(henvic): net/http data race condition when the client
// does concurrent requests using the very same HTTP transport.
// See G... | {
return roundTripper{
logger: l,
rt: rt,
}
} | identifier_body |
httpretty.go | // Package httpretty prints your HTTP requests pretty on your terminal screen.
// You can use this package both on the client-side and on the server-side.
//
// This package provides a better way to view HTTP traffic without httputil
// DumpRequest, DumpRequestOut, and DumpResponse heavy debugging functions.
//
// You ... | "sync"
"github.com/henvic/httpretty/internal/color"
)
// Formatter can be used to format body.
//
// If the Format function returns an error, the content is printed in verbatim after a warning.
// Match receives a media type from the Content-Type field. The body is formatted if it returns true.
type Formatter inter... | "os" | random_line_split |
fvs.py | #-*- mode: python; python-indent: 4;-*-
import argparse # For parsing input arguments
import igraph # Fast graph library
import sys # System-related stuff
from collections import deque, Counter
import copy
from itertools import dropwhile
from io import StringIO
from tempfile import TemporaryFile
# Read in command... | sole_neighbour.delete()
# discard = remove if present
small_degree_labels.discard(sole_nbr_label)
for neighbour_label in neighbour_labels:
if neighbour_label not in forbidden_set:
neighbour = H.vs.find(label = ne... | neighbour_labels = list(v['label'] for v in neighbours)
| random_line_split |
fvs.py | #-*- mode: python; python-indent: 4;-*-
import argparse # For parsing input arguments
import igraph # Fast graph library
import sys # System-related stuff
from collections import deque, Counter
import copy
from itertools import dropwhile
from io import StringIO
from tempfile import TemporaryFile
# Read in command... |
return max_vertex
# Parse command line arguments and invoke functions which do the
# actual work.
#
if __name__ == '__main__':
# Read in the command-line arguments.
args = get_args()
# Read the input file into an igraph graph object.
G = read_input(args)
#
# This call does n... | v_degree = v.degree()
if v_degree > max_degree:
max_degree = v_degree
max_vertex = v | conditional_block |
fvs.py | #-*- mode: python; python-indent: 4;-*-
import argparse # For parsing input arguments
import igraph # Fast graph library
import sys # System-related stuff
from collections import deque, Counter
import copy
from itertools import dropwhile
from io import StringIO
from tempfile import TemporaryFile
# Read in command... |
# Pick a smallest cycle from G and return its vertex list. A
# multiple edge counts as a cycle. This function does not modify
# its argument.
def pick_smallest_cycle(G):
if G.has_multiple(): # The girth function does not see multiedges.
multi_edge = next(dropwhile(lambda e: not e.is_multiple(), G.es))
... | H = G.copy()
packing_approx = 0
while H.has_multiple(): # The girth function does not see multiedges.
multi_edge = next(dropwhile(lambda e: not e.is_multiple(), H.es))
H.delete_vertices(list(multi_edge.tuple))
packing_approx += 1
H_girth_vertices = H.girth(True)
while H_girth_v... | identifier_body |
fvs.py | #-*- mode: python; python-indent: 4;-*-
import argparse # For parsing input arguments
import igraph # Fast graph library
import sys # System-related stuff
from collections import deque, Counter
import copy
from itertools import dropwhile
from io import StringIO
from tempfile import TemporaryFile
# Read in command... | (G):
n = G.vcount()
if n == 0: # Don't do anything fancy if the graph is already empty
return 0
else:
max_degree = G.maxdegree()
first_lower_bound = int((n + 2)/(max_degree + 1))
degrees = sorted(G.degree(), reverse = True) # Sorted non-increasing
mi... | fvs_lower_bound | identifier_name |
renderer_go_func.go | package gogh
import (
"fmt"
"go/types"
"regexp"
"strings"
"github.com/sirkon/gogh/internal/consts"
"github.com/sirkon/gogh/internal/heuristics"
"github.com/sirkon/protoast/ast"
)
// F function definition rendering helper.
// Here name is just a function name and params can be:
// - missing at all
// - a sin... |
switch len(results) {
case 0:
case 1:
switch v := results[0].(type) {
case Params:
r.checkSeqsUniq("argument", "arguments", v.commasSeq)
zeroes = heuristics.ZeroGuesses(v.data, nil)
r.results = v.data
case *Params:
r.checkSeqsUniq("argument", "arguments", v.commasSeq)
r.results = v.data
zer... | ]string | identifier_name |
renderer_go_func.go | package gogh
import (
"fmt"
"go/types"
"regexp"
"strings"
"github.com/sirkon/gogh/internal/consts"
"github.com/sirkon/gogh/internal/heuristics"
"github.com/sirkon/protoast/ast"
)
// F function definition rendering helper.
// Here name is just a function name and params can be:
// - missing at all
// - a sin... | ms ...any) (res [][2]string, zeroes []string) {
defer func() {
zeroes = heuristics.ZeroGuesses(res, zeroes)
}()
checker := tupleNamesChecker{
what: what,
plural: what + "s",
empties: 0,
nonEmpties: 0,
}
if len(params)%2 != 0 {
var nameMask uint
for i, param := range params {
v := te... | parameter index %d: expected it to be %T got %T",
i,
new(types.Var),
param,
))
}
checker.reg(p.Name())
r.takeVarName(what, p.Name())
res = append(res, [2]string{p.Name(), r.r.Type(p.Type())})
zeroes = append(zeroes, zeroValueOfTypesType(r.r, p.Type(), i == len(params)-1))
}
return
}
func ... | conditional_block |
renderer_go_func.go | package gogh
import (
"fmt"
"go/types"
"regexp"
"strings"
"github.com/sirkon/gogh/internal/consts"
"github.com/sirkon/gogh/internal/heuristics"
"github.com/sirkon/protoast/ast"
)
// F function definition rendering helper.
// Here name is just a function name and params can be:
// - missing at all
// - a sin... | ...any) {
checkName(r.kind(), name)
r.name = name
switch len(params) {
case 0:
case 1:
switch v := params[0].(type) {
case Params:
r.checkSeqsUniq("argument", "arguments", v.commasSeq)
r.params = v.data
case *Params:
r.checkSeqsUniq("argument", "arguments", v.commasSeq)
r.params = v.data
case ... |
}
func (r *GoFuncRenderer[T]) setFuncInfo(name string, params | identifier_body |
renderer_go_func.go | package gogh
import (
"fmt"
"go/types"
"regexp"
"strings"
"github.com/sirkon/gogh/internal/consts"
"github.com/sirkon/gogh/internal/heuristics"
"github.com/sirkon/protoast/ast"
)
// F function definition rendering helper.
// Here name is just a function name and params can be:
// - missing at all
// - a sin... | // So, the usage of this method will be like
// r.M("t", "*Type")("Name")("ctx $ctx.Context").Returns("string", "error, "").Body(func(…) {
// r.L(`return $ZeroReturnValue $errs.New("error")`)
// })
// Producing this code
// func (t *Type) Name(ctx context.Context) (string, error) {
// return... | //
// The return value is a function with a signature whose semantics matches F.
// | random_line_split |
compressor_params.rs | use super::*;
use crate::{BasisTextureFormat, UserData};
use basis_universal_sys as sys;
pub use basis_universal_sys::ColorU8;
/// The color space the image to be compressed is encoded in. Using the correct color space will
#[derive(Debug, Copy, Clone)]
pub enum ColorSpace {
/// Used for normal maps or other "data... |
// The default options that are applied when creating a new compressor or calling reset() on it
fn set_default_options(&mut self) {
// Set a default quality level. Leaving this unset results in undefined behavior, so we set
// it to a working value by default
self.set_etc1s_quality_lev... | {
unsafe {
sys::compressor_params_clear(self.0);
self.set_default_options();
self.clear_source_image_list();
}
} | identifier_body |
compressor_params.rs | use super::*;
use crate::{BasisTextureFormat, UserData};
use basis_universal_sys as sys;
pub use basis_universal_sys::ColorU8;
/// The color space the image to be compressed is encoded in. Using the correct color space will
#[derive(Debug, Copy, Clone)]
pub enum ColorSpace {
/// Used for normal maps or other "data... | (
&mut self,
print_status_to_stdout: bool,
) {
unsafe { sys::compressor_params_set_status_output(self.0, print_status_to_stdout) }
}
/// Set ETC1S quality level. The value MUST be >= [ETC1S_QUALITY_MIN](crate::ETC1S_QUALITY_MIN)
/// and <= [ETC1S_QUALITY_MAX](crate::ETC1S_QUALIT... | set_print_status_to_stdout | identifier_name |
compressor_params.rs | use super::*;
use crate::{BasisTextureFormat, UserData};
use basis_universal_sys as sys;
pub use basis_universal_sys::ColorU8;
/// The color space the image to be compressed is encoded in. Using the correct color space will
#[derive(Debug, Copy, Clone)]
pub enum ColorSpace {
/// Used for normal maps or other "data... | }
/// Set ETC1S quality level. The value MUST be >= [ETC1S_QUALITY_MIN](crate::ETC1S_QUALITY_MIN)
/// and <= [ETC1S_QUALITY_MAX](crate::ETC1S_QUALITY_MAX).
pub fn set_etc1s_quality_level(
&mut self,
quality_level: u32,
) {
assert!(quality_level >= crate::ETC1S_QUALITY_MIN);
... | print_status_to_stdout: bool,
) {
unsafe { sys::compressor_params_set_status_output(self.0, print_status_to_stdout) } | random_line_split |
manual_map.rs | use crate::{map_unit_fn::OPTION_MAP_UNIT_FN, matches::MATCH_AS_REF};
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::higher::IfLetOrMatch;
use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
use clippy_utils::ty::{is_type_diagnostic_item, peel_mid_ty_refs_is_mutable};
use ... |
f(cx, pat, 0, ctxt)
}
// Checks for an expression wrapped by the `Some` constructor. Returns the contained expression.
fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ctxt: SyntaxContext) -> Option<&'tcx Expr<'tcx>> {
// TODO: Allow more complex expressions.
match expr.kind {
ExprKi... | {
match pat.kind {
PatKind::Wild => Some(OptionPat::Wild),
PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1, ctxt),
PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone) => Some(OptionPat::None),
PatKind::TupleStruct(ref qpath, [pattern], _)
... | identifier_body |
manual_map.rs | use crate::{map_unit_fn::OPTION_MAP_UNIT_FN, matches::MATCH_AS_REF};
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::higher::IfLetOrMatch;
use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
use clippy_utils::ty::{is_type_diagnostic_item, peel_mid_ty_refs_is_mutable};
use ... | (cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ref_count: usize, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
match pat.kind {
PatKind::Wild => Some(OptionPat::Wild),
PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1, ctxt),
PatKind::Path(ref qpath) if is_lang_ctor(cx, qpat... | f | identifier_name |
manual_map.rs | use crate::{map_unit_fn::OPTION_MAP_UNIT_FN, matches::MATCH_AS_REF};
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::higher::IfLetOrMatch;
use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
use clippy_utils::ty::{is_type_diagnostic_item, peel_mid_ty_refs_is_mutable};
use ... | use rustc_hir::{
def::Res, Arm, BindingAnnotation, Block, Expr, ExprKind, HirId, Mutability, Pat, PatKind, Path, QPath,
};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::{sym, SyntaxConte... | };
use rustc_ast::util::parser::PREC_POSTFIX;
use rustc_errors::Applicability;
use rustc_hir::LangItem::{OptionNone, OptionSome}; | random_line_split |
util.rs | use std::path::{Path,PathBuf};
use std::process::{Command,Stdio};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::os::unix::fs as unixfs;
use std::env;
use std::fs::{self, File, DirEntry};
use std::ffi::CString;
use std::io::{self, Seek, Read, BufReader, SeekFrom};
use ... |
}
Ok(())
}
pub fn chown_tree(base: &Path, chown_to: (u32,u32), include_base: bool) -> Result<()> {
for entry in WalkDir::new(base) {
let entry = entry.map_err(|e| format_err!("Error reading directory entry: {}", e))?;
if entry.path() != base || include_base {
chown(entry.path()... | {
copy_path(path, &to, chown_to)
.map_err(context!("failed to copy {:?} to {:?}", path, to))?;
} | conditional_block |
util.rs | use std::path::{Path,PathBuf};
use std::process::{Command,Stdio};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::os::unix::fs as unixfs;
use std::env;
use std::fs::{self, File, DirEntry};
use std::ffi::CString;
use std::io::{self, Seek, Read, BufReader, SeekFrom};
use ... | <P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
cmd!("/usr/bin/xz", "-d {}", path.display())
.map_err(context!("failed to decompress {:?}", path))
}
pub fn mount<P: AsRef<Path>>(source: impl AsRef<str>, target: P, options: Option<&str>) -> Result<()> {
let source = source.as_ref... | xz_decompress | identifier_name |
util.rs | use std::path::{Path,PathBuf};
use std::process::{Command,Stdio};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::os::unix::fs as unixfs;
use std::env;
use std::fs::{self, File, DirEntry};
use std::ffi::CString;
use std::io::{self, Seek, Read, BufReader, SeekFrom};
use ... |
pub fn copy_tree(from_base: &Path, to_base: &Path) -> Result<()> {
_copy_tree(from_base, to_base, None)
}
pub fn copy_tree_with_chown(from_base: &Path, to_base: &Path, chown_to: (u32,u32)) -> Result<()> {
_copy_tree(from_base, to_base, Some(chown_to))
}
fn _copy_tree(from_base: &Path, to_base: &Path, chown_... | {
if to.exists() {
bail!("destination path {} already exists which is not expected", to.display());
}
let meta = from.metadata()
.map_err(context!("failed to read metadata from source file {:?}", from))?;
if from.is_dir() {
util::create_dir(to)?;
} else {
util::copy... | identifier_body |
util.rs | use std::path::{Path,PathBuf};
use std::process::{Command,Stdio};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::os::unix::fs as unixfs;
use std::env;
use std::fs::{self, File, DirEntry};
use std::ffi::CString;
use std::io::{self, Seek, Read, BufReader, SeekFrom};
use ... | is_ascii(c) && (c.is_alphanumeric() || c == '-')
}
fn is_ascii(c: char) -> bool {
c as u32 <= 0x7F
}
pub fn is_first_char_alphabetic(s: &str) -> bool {
if let Some(c) = s.chars().next() {
return is_ascii(c) && c.is_alphabetic()
}
false
}
fn search_path(filename: &str) -> Result<PathBuf> {... | fn is_alphanum_or_dash(c: char) -> bool { | random_line_split |
train_test_function.py | from tflib.queue import GeneratorRunner, queueSelection
from Nets.Models import AverageSummary
import time
import tensorflow as tf
from Nets.SRNet import SRNet
from glob import glob
def train(model_class, # SRNet模型
train_gen, # train的generator
valid_gen, # valid的generator
train_batch_... | summary = AverageSummary(accuracy, name='accuracy', num_iterations=float(ds_size) / float(batch_size))
increment_op = tf.group(loss_summary.increment_op, accuracy_summary.increment_op)
global_step = tf.get_variable(name='global_step', shape=[], dtype=tf.int32,
initializer=tf.c... | acy_ | identifier_name |
train_test_function.py | from tflib.queue import GeneratorRunner, queueSelection
from Nets.Models import AverageSummary
import time
import tensorflow as tf
from Nets.SRNet import SRNet
from glob import glob
def train(model_class, # SRNet模型
train_gen, # train的generator
valid_gen, # valid的generator
train_batch_... | TFCounter, TCounter,
FTCounter, FCounter,
TCounter, FCounter,
(TTCounter + FFCounter) * 1.0 / step_cnt))
print('\nTOTAL RESULT: ')
print('TT: %d/%d, FF: %d/%d, TF: %d/%d, FT: %d/%d || PosCount: %d,... | conditional_block | |
train_test_function.py | from tflib.queue import GeneratorRunner, queueSelection
from Nets.Models import AverageSummary
import time
import tensorflow as tf
from Nets.SRNet import SRNet
from glob import glob
def train(model_class, # SRNet模型
train_gen, # train的generator
valid_gen, # valid的generator
train_batch_... |
for j in range(0, valid_ds_size, valid_batch_size):
sess.run([increment_valid])
print('validation cnt: %d || iterations: %d || validation accuracy: %d' % (
valid_cnt, i, sess.run(valid_accuracy_s.mean_variable)))
va... | if i % valid_interval == 0:
sess.run(disable_training_op) | random_line_split |
train_test_function.py | from tflib.queue import GeneratorRunner, queueSelection
from Nets.Models import AverageSummary
import time
import tensorflow as tf
from Nets.SRNet import SRNet
from glob import glob
def train(model_class, # SRNet模型
train_gen, # train的generator
valid_gen, # valid的generator
train_batch_... | = tf.train.latest_checkpoint(weight_path)
saver.restore(sess, model_file)
runner.start_threads(sess, num_threads=1)
for step in range(0, data_size, batch_size):
# 拿出来的图像顺序就是cover, stego, cover, stego 这样的顺序
step_cnt += 1
model_label = sess.run(tf.argmax(model_... | identifier_body | |
lib.rs | //! A proportional-integral-derivative (PID) controller library.
//!
//! See [Pid] for the adjustable controller itself, as well as [ControlOutput] for the outputs and weights which you can use after setting up your controller. Follow the complete example below to setup your first controller!
//!
//! # Example
//!
//! ... | let mut pid_i32 = Pid::new(10i32, 100);
pid_i32.p(0, 100).i(0, 100).d(0, 100);
for _ in 0..5 {
assert_eq!(
pid_i32.next_control_output(0).output,
pid_i8.next_control_output(0i8).output as i32
);
}
}
/// See if the controll... | fn signed_integers_zeros() {
let mut pid_i8 = Pid::new(10i8, 100);
pid_i8.p(0, 100).i(0, 100).d(0, 100);
| random_line_split |
lib.rs | //! A proportional-integral-derivative (PID) controller library.
//!
//! See [Pid] for the adjustable controller itself, as well as [ControlOutput] for the outputs and weights which you can use after setting up your controller. Follow the complete example below to setup your first controller!
//!
//! # Example
//!
//! ... | (&mut self, setpoint: impl Into<T>) -> &mut Self {
self.setpoint = setpoint.into();
self
}
/// Given a new measurement, calculates the next [control output](ControlOutput).
///
/// # Panics
///
/// - If a setpoint has not been set via `update_setpoint()`.
pub fn next_control... | setpoint | identifier_name |
cpu.py | from functools import partial
from devito.core.operator import CoreOperator, CustomOperator, ParTile
from devito.exceptions import InvalidOperator
from devito.passes.equations import collect_derivatives
from devito.passes.clusters import (Lift, blocking, buffering, cire, cse,
factor... |
class Cpu64FsgCOperator(Cpu64FsgOperator):
_Target = CTarget
class Cpu64FsgOmpOperator(Cpu64FsgOperator):
_Target = OmpTarget
| _Target = OmpTarget | identifier_body |
cpu.py | from functools import partial
from devito.core.operator import CoreOperator, CustomOperator, ParTile
from devito.exceptions import InvalidOperator
from devito.passes.equations import collect_derivatives
from devito.passes.clusters import (Lift, blocking, buffering, cire, cse,
factor... |
return {
'buffering': lambda i: buffering(i, callback, sregistry, options),
'blocking': lambda i: blocking(i, sregistry, options),
'factorize': factorize,
'fission': fission,
'fuse': lambda i: fuse(i, options=options),
'lift': lambda i: L... | return None | conditional_block |
cpu.py | from functools import partial
from devito.core.operator import CoreOperator, CustomOperator, ParTile
from devito.exceptions import InvalidOperator
from devito.passes.equations import collect_derivatives
from devito.passes.clusters import (Lift, blocking, buffering, cire, cse,
factor... | class Cpu64FsgCOperator(Cpu64FsgOperator):
_Target = CTarget
class Cpu64FsgOmpOperator(Cpu64FsgOperator):
_Target = OmpTarget |
class Cpu64AdvOmpOperator(Cpu64AdvOperator):
_Target = OmpTarget
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.