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 |
|---|---|---|---|---|
main_test.go | Client // resolver
esClient elastic.ESClient // elastic client to verify the results
elasticsearchAddr string // elastic address
elasticsearchName string // name of the elasticsearch server name; used to stop the server
elasticsearchDir... | if t.evtsMgr != nil {
t.evtsMgr.Stop()
t.evtsMgr = nil
}
t.evtProxyServices.Stop()
if t.apiServer != nil {
t.apiServer.Stop()
t.apiServer = nil
}
// stop certificate server
testutils.CleanupIntegTLSProvider()
if t.mockResolver != nil {
t.mockResolver.Stop()
t.mockResolver = nil
}
// remove th... | {
t.recorders.close()
if t.apiClient != nil {
t.apiClient.ClusterV1().Version().Delete(context.Background(), &api.ObjectMeta{Name: t.testName})
t.apiClient.Close()
t.apiClient = nil
}
if t.esClient != nil {
t.esClient.Close()
}
testutils.StopElasticsearch(t.elasticsearchName, t.elasticsearchDir)
if t... | identifier_body |
main_test.go | Client // resolver
esClient elastic.ESClient // elastic client to verify the results
elasticsearchAddr string // elastic address
elasticsearchName string // name of the elasticsearch server name; used to stop the server
elasticsearchDir... | (tst *testing.T) error {
var err error
logConfig := log.GetDefaultConfig("events_test")
logConfig.Format = log.JSONFmt
logConfig.Filter = log.AllowInfoFilter
t.logger = log.GetNewLogger(logConfig).WithContext("t_name", tst.Name())
t.logger.Infof("Starting test %s", tst.Name())
t.mockResolver = mockresolver.New(... | setup | identifier_name |
main_test.go | elasticsearchDir string // name of the directory where Elastic credentials and logs are stored
apiServer apiserver.Server // venice API server
apiServerAddr string // API server address
evtsMgr *evtsmgr.EventsManager ... | logger log.Logger
mockResolver *mockresolver.ResolverClient // resolver
esClient elastic.ESClient // elastic client to verify the results
elasticsearchAddr string // elastic address
elasticsearchName string //... | random_line_split | |
mod.rs | ;
pub type VirtualAddress = usize;
/// Copy so that it can be used after passing 'map_to' and similar functions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Page {
number: usize,
}
impl Page {
/// The address space is split into two halves , high/low, where the higher
/// h... | use core::ops::Range;
// Create a temporary page at some page number, in this case 0xcafebabe
let mut temporary_page =
TemporaryPage::new(Page { number: 0xcafebabe }, allocator);
// Created by constructor
let mut active_table = unsafe { ActivePageTable::new() };
// Created by constructor... | }
/// Remaps the kernel sections by creating a temporary page.
pub fn remap_the_kernel<A>(allocator: &mut A, boot_info: &BootInformation, sdt_loc: &mut SDT_Loc)
-> ActivePageTable
where A: FrameAllocator{ | random_line_split |
mod.rs | pub type VirtualAddress = usize;
/// Copy so that it can be used after passing 'map_to' and similar functions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Page {
number: usize,
}
impl Page {
/// The address space is split into two halves , high/low, where the higher
/// hal... |
/// Returns inclusive range iterator of pages
pub fn range_inclusive(start: Page, end: Page) -> PageIter {
PageIter {
start: start,
end: end
}
}
}
pub struct PageIter {
start: Page,
end: Page
}
impl Iterator for PageIter {
type Item = Page;
fn nex... | {
(self.number >> 0) & 0o777
} | identifier_body |
mod.rs | pub type VirtualAddress = usize;
/// Copy so that it can be used after passing 'map_to' and similar functions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Page {
number: usize,
}
impl Page {
/// The address space is split into two halves , high/low, where the higher
/// hal... | (&self) -> usize {
(self.number >> 0) & 0o777
}
/// Returns inclusive range iterator of pages
pub fn range_inclusive(start: Page, end: Page) -> PageIter {
PageIter {
start: start,
end: end
}
}
}
pub struct PageIter {
start: Page,
end: Page
}
imp... | p1_index | identifier_name |
mod.rs | pub type VirtualAddress = usize;
/// Copy so that it can be used after passing 'map_to' and similar functions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Page {
number: usize,
}
impl Page {
/// The address space is split into two halves , high/low, where the higher
/// hal... |
}
}
let ioapic_start = Frame::containing_address(sdt_loc.ioap | {
mapper.identity_map(next_header_frame, PRESENT, allocator);
} | conditional_block |
revoked.go | ededFlag
CessationOfOperationFlag
CertificateHoldFlag
PrivilegeWithdrawnFlag
AACompromiseFlag
)
// CertificateList represents the ASN.1 structure of the same name from RFC 5280, s5.1.
// It has the same content as pkix.CertificateList, but the contents include parsed versions
// of any extensions.
type Certificate... | }
if certList.TBSCertList.BaseCRLNumber < 0 {
errs.AddID(ErrNegativeCertListDeltaCRL, certList.TBSCertList.BaseCRLNumber)
}
case e.Id.Equal(OIDExtensionIssuingDistributionPoint):
parseIssuingDistributionPoint(e.Value, &certList.TBSCertList.IssuingDistributionPoint, &certList.TBSCertList.IssuingDPFullN... | errs.AddID(ErrTrailingCertListDeltaCRL) | random_line_split |
revoked.go | ededFlag
CessationOfOperationFlag
CertificateHoldFlag
PrivilegeWithdrawnFlag
AACompromiseFlag
)
// CertificateList represents the ASN.1 structure of the same name from RFC 5280, s5.1.
// It has the same content as pkix.CertificateList, but the contents include parsed versions
// of any extensions.
type Certificate... |
certList.TBSCertList.AuthorityKeyID = a.Id
case e.Id.Equal(OIDExtensionIssuerAltName):
// RFC 5280 s5.2.2
if err := parseGeneralNames(e.Value, &certList.TBSCertList.IssuerAltNames); err != nil {
errs.AddID(ErrInvalidCertListIssuerAltName, err)
}
case e.Id.Equal(OIDExtensionCRLNumber):
// RFC 528... | {
errs.AddID(ErrTrailingCertListAuthKeyID)
} | conditional_block |
revoked.go | ityDate.String(): false, // s5.3.2
OIDExtensionCertificateIssuer.String(): true, // s5.3.3
}
// IssuingDistributionPoint represents the ASN.1 structure of the same
// name
type IssuingDistributionPoint struct {
DistributionPoint distributionPointName `asn1:"optional,tag:0"`
OnlyContainsUserCerts b... | parseIssuingDistributionPoint | identifier_name | |
revoked.go | ededFlag
CessationOfOperationFlag
CertificateHoldFlag
PrivilegeWithdrawnFlag
AACompromiseFlag
)
// CertificateList represents the ASN.1 structure of the same name from RFC 5280, s5.1.
// It has the same content as pkix.CertificateList, but the contents include parsed versions
// of any extensions.
type Certificate... |
// ParseCertificateListDER parses a DER encoded CertificateList from the given bytes.
// For non-fatal errors, this function returns both an error and a CertificateList
// object.
func ParseCertificateListDER(derBytes []byte) (*CertificateList, error) {
var errs Errors
// First parse the DER into the pkix structure... | {
if bytes.HasPrefix(clBytes, pemCRLPrefix) {
block, _ := pem.Decode(clBytes)
if block != nil && block.Type == pemType {
clBytes = block.Bytes
}
}
return ParseCertificateListDER(clBytes)
} | identifier_body |
module.rs | import::Info> + '_ {
self.enumerate_imports().map(|(_, import)| import)
}
/// Check if module contains import with given id.
pub fn contains_import(&self, id: import::Id) -> bool {
self.iter_imports().any(|import| import.id() == id)
}
/// Add a new line to the module's block.
... |
add_line(Some(ast));
if blank_line == BlankLinePlacement::After {
add_line(None);
}
Ok(())
}
/// Add a new method definition to the module.
pub fn add_method(
&mut self,
method: definition::ToAdd,
location: Placement,
parser: &pa... | {
add_line(None);
} | conditional_block |
module.rs | = import::Info> + '_ {
self.enumerate_imports().map(|(_, import)| import)
}
/// Check if module contains import with given id.
pub fn contains_import(&self, id: import::Id) -> bool {
self.iter_imports().any(|import| import.id() == id)
}
/// Add a new line to the module's block.
... | (
&mut self,
parser: &parser::Parser,
to_add: import::Info,
) -> Option<usize> {
(!self.contains_import(to_add.id())).then(|| self.add_import(parser, to_add))
}
/// Place the line with given AST in the module's body.
///
/// Unlike `add_line` (which is more low-level... | add_import_if_missing | identifier_name |
module.rs | /// The segments of all parent modules, from the top module to the direct parent. Does **not**
/// include project name.
pub parent_modules: Vec<ImString>,
}
impl Id {
/// Create module id from list of segments. The list shall not contain the project name nor
/// namespace. Fails if the list is emp... | pub struct Id {
/// The last segment being a module name. For project's main module it should be equal
/// to [`PROJECTS_MAIN_MODULE`].
pub name: ImString, | random_line_split | |
init.rs | Handler, SigSet, SigmaskHow, Signal, SIGCHLD, SIGKILL},
},
unistd::{self, Uid},
};
use sched::CloneFlags;
use std::{
collections::HashSet, env, ffi::CString, io::Read, os::unix::prelude::RawFd, process::exit,
};
use sys::wait::{waitpid, WaitStatus};
// Init function. Pid 1.
#[allow(clippy::too_many_argumen... | set_no_new_privs(true);
// Capabilities
drop_capabilities(manifest.capabilities.as_ref());
// Close and dup fds
file_descriptors(fds);
// Clone
match clone(CloneFlags::empty(), Some(SIGCHLD as i32)) {
Ok(result) => match result {
unistd::ForkResult::Parent { child } =>... | setgroups(groups);
// No new privileges | random_line_split |
init.rs | , SigSet, SigmaskHow, Signal, SIGCHLD, SIGKILL},
},
unistd::{self, Uid},
};
use sched::CloneFlags;
use std::{
collections::HashSet, env, ffi::CString, io::Read, os::unix::prelude::RawFd, process::exit,
};
use sys::wait::{waitpid, WaitStatus};
// Init function. Pid 1.
#[allow(clippy::too_many_arguments)]
pu... | (value: bool) {
#[cfg(target_os = "android")]
const PR_SET_CHILD_SUBREAPER: c_int = 36;
#[cfg(not(target_os = "android"))]
use libc::PR_SET_CHILD_SUBREAPER;
let value = if value { 1u64 } else { 0u64 };
let result = unsafe { nix::libc::prctl(PR_SET_CHILD_SUBREAPER, value, 0, 0, 0) };
Errno::... | set_child_subreaper | identifier_name |
init.rs | that would otherwise receive the signal.
// If the child is spawn when the signal is sent to this group it shall exit and the init returns from waitpid.
set_init_signal_handlers();
// Become a session group leader
setsid();
// Sync with parent
checkpoint.wait(Start::Start);
checkpoint.sen... | {
unistd::setsid().expect("Failed to call setsid");
} | identifier_body | |
tessbatman.py | suffix (str): append suffix to config and curve file names
"""
params = {}
params["curves_fname"] = p.join(path, 'batmanCurves{}.csv'.format(suffix))
params["params_fname"] = p.join(path, 'batmanParams{}.csv'.format(suffix))
params["tmin"] = tmin
params["tmax"] = tmax
params["tstep"] = t... | wmax (num): maximum width
wnum (num): number of widths to generate
wlog (bool): use logspace for widths if True, else use linspace | random_line_split | |
tessbatman.py | ): path to write output curve and param files
norm (bool): normalize curves to unit integrated area
write (bool): write param and curve tables to files
verbose (bool): print logging and timing info
"""
# read batman param file
if verbose:
print("Reading param file", flush=True)
with... | conv_start = time()
curves = []
times = np.zeros(num_keep)
convs = np.zeros(num_keep)
print("Starting convolutions...",flush=True)
for i, curvename in enumerate(curve_names):
# do convolution
batman_curve = batmanCurves[curvename]
conv = np.abs(sig.fftconvolve(1-tess_flux, (1... | identifier_body | |
tessbatman.py | (tmin, tmax, tstep, wmin, wmax, wnum, wlog=True, suffix="", path="."):
"""
Write batman parameters to a JSON param file used to generate batmanCurves.
Parameters
----------
tmin (num): minimum time
tmax (num): maximum time
tnum (num): time step
wmin (num): minimum width
wmax (num): ... | make_batman_config | identifier_name | |
tessbatman.py | [curveID, radii, incs, widths, per, u, ld, t0, e, w]
colnames = ['curveID', 'rp', 'i', 'width', 'per', 'u', 'ld', 't0', 'e', 'w']
batmanParams = tbl.Table(cols, names=colnames)
# generate curves
if verbose:
print("Generating curves", flush=True)
start = time()
batmanDict = {'times'... | print("No batman curves found, quitting....")
return None | conditional_block | |
topic.go | // PlacementStrategyCrossRack is a strategy in which the leaders are balanced
// and the replicas in each partition are spread to separate racks.
PlacementStrategyCrossRack PlacementStrategy = "cross-rack"
// PlacementStrategyStatic uses a static placement defined in the config. This is for
// testing only and sho... |
switch placement.Strategy {
case PlacementStrategyBalancedLeaders:
if numRacks > 0 && t.Spec.Partitions%numRacks != 0 {
// The balanced-leaders strategy requires that the
// partitions be a multiple of the number of racks, otherwise it's impossible
// to find a placement that satisfies the strategy.
e... | {
err = multierror.Append(
err,
fmt.Errorf(
"PickerMethod must in %+v",
allPickerMethods,
),
)
} | conditional_block |
topic.go | // PlacementStrategyCrossRack is a strategy in which the leaders are balanced
// and the replicas in each partition are spread to separate racks.
PlacementStrategyCrossRack PlacementStrategy = "cross-rack"
// PlacementStrategyStatic uses a static placement defined in the config. This is for
// testing only and sho... | "PlacementStrategy must in %+v",
allPlacementStrategies,
),
)
}
pickerIndex := -1
for p, pickerMethod := range allPickerMethods {
if pickerMethod == placement.Picker {
pickerIndex = p
break
}
}
if pickerIndex == -1 {
err = multierror.Append(
err,
fmt.Errorf(
"PickerMethod must ... |
if strategyIndex == -1 {
err = multierror.Append(
err,
fmt.Errorf( | random_line_split |
topic.go | // PlacementStrategyCrossRack is a strategy in which the leaders are balanced
// and the replicas in each partition are spread to separate racks.
PlacementStrategyCrossRack PlacementStrategy = "cross-rack"
// PlacementStrategyStatic uses a static placement defined in the config. This is for
// testing only and sho... | }
if settingsErr := t.Spec.Settings.Validate(); settingsErr != nil {
err = multierror.Append(err, settingsErr)
}
if t.Spec.RetentionMinutes < 0 {
err = multierror.Append(err, errors.New("RetentionMinutes must be >= 0"))
}
if t.Spec.RetentionMinutes > 0 && t.Spec.Settings["retention.ms"] != nil {
err = mul... | {
var err error
if t.Meta.Name == "" {
err = multierror.Append(err, errors.New("Name must be set"))
}
if t.Meta.Cluster == "" {
err = multierror.Append(err, errors.New("Cluster must be set"))
}
if t.Meta.Region == "" {
err = multierror.Append(err, errors.New("Region must be set"))
}
if t.Meta.Environment... | identifier_body |
topic.go | Method = "cluster-use"
// PickerMethodLowestIndex uses broker frequency in the topic, breaking ties by
// choosing the broker with the lowest index.
PickerMethodLowestIndex PickerMethod = "lowest-index"
// PickerMethodRandomized uses broker frequency in the topic, breaking ties by
// using a repeatably random ch... | TopicConfigFromTopicInfo | identifier_name | |
oid.rs | }
#[cfg(feature = "std")]
impl ToDer for Oid<'_> {
fn to_der_len(&self) -> Result<usize> {
// OID/REL-OID tag will not change header size, so we don't care here
let header = Header::new(
Class::Universal,
false,
Self::TAG,
Length::Definite(self.asn1.l... | impl DerAutoDerive for Oid<'_> {}
impl<'a> Tagged for Oid<'a> {
const TAG: Tag = Tag::Oid; | random_line_split | |
oid.rs | - id.leading_zeros();
let octets_needed = ((bit_count + 6) / 7).max(1);
(0..octets_needed).map(move |i| {
let flag = if i == octets_needed - 1 { 0 } else { 1 << 7 };
((id >> (7 * (octets_needed - 1 - i))) & 0b111_1111) as u8 | flag
})
})
}
impl<'a> Oid<'a> {
///... | if max_bits > 64 {
return None;
}
Some(SubIdentifierIterator {
oid: self,
pos: 0,
first: false,
n: PhantomData,
})
}
pub fn from_ber_relative(bytes: &'a [u8]) -> ParseResult<'a, Self> {
let (rem, any) = Any::f... | {
// Check that every arc fits into u64
let bytes = if self.relative {
&self.asn1
} else if self.asn1.is_empty() {
&[]
} else {
&self.asn1[1..]
};
let max_bits = bytes
.iter()
.fold((0usize, 0usize), |(max, cur),... | identifier_body |
oid.rs | u8]) -> ParseResult<'a, Self> {
let (rem, any) = Any::from_ber(bytes)?;
any.header.assert_primitive()?;
any.header.assert_tag(Tag::RelativeOid)?;
let asn1 = Cow::Borrowed(any.data);
Ok((rem, Oid::new_relative(asn1)))
}
pub fn from_der_relative(bytes: &'a [u8]) -> ParseRe... | test_compare_oid | identifier_name | |
oid.rs | 1 << 7 };
((id >> (7 * (octets_needed - 1 - i))) & 0b111_1111) as u8 | flag
})
})
}
impl<'a> Oid<'a> {
/// Create an OID from the ASN.1 DER encoded form. See the [module documentation](index.html)
/// for other ways to create oids.
pub const fn new(asn1: Cow<'a, [u8]>) -> Oid {
... | {
break;
} | conditional_block | |
map.rs | //less wonky math when dealing with negatives
pub fn new(width:i32, height:i32, default_tile:Tile) -> Self {
assert!(width > 0, "width must be greater than 0!");
assert!(height > 0, "height must be greater than 0!");
Map {
tiles: vec![default_tile; (height * width) as usiz... |
fn create_v_tunnel(&mut self, y1: i32, y2: i32, x: i32) {
for y in cmp::min(y1, y2)..(cmp::max(y1, y2) + 1) {
self.set(x,y, Tile::empty());
}
}
fn create_h_tunnel(&mut self, x1: i32, x2: i32, y: i32) {
for x in cmp::min(x1, x2)..(cmp::max(x1, x2) + 1) {
self... | {
for x in (room.x1 + 1) .. room.x2 {
for y in (room.y1 + 1) .. room.y2 {
self.set(x,y,Tile::empty());
}
}
} | identifier_body |
map.rs | //less wonky math when dealing with negatives
pub fn new(width:i32, height:i32, default_tile:Tile) -> Self {
assert!(width > 0, "width must be greater than 0!");
assert!(height > 0, "height must be greater than 0!");
Map {
tiles: vec![default_tile; (height * width) as u... | let y = rng.gen_range(0, map.height());
let tile_blocked = is_blocked(x,y, &map, objects);
if !tile_blocked {
let mut monster = if rand::random::<f32>() < 0.8 { // 80% chance of getting an orc
// create an orc
Ob... | random_line_split | |
map.rs | //less wonky math when dealing with negatives
pub fn new(width:i32, height:i32, default_tile:Tile) -> Self {
assert!(width > 0, "width must be greater than 0!");
assert!(height > 0, "height must be greater than 0!");
Map {
tiles: vec![default_tile; (height * width) as usiz... |
}
let sim_steps = 6;
for _ in 0 .. sim_steps {
map.caves_sim_step();
}
let max_spawn_chances = 200;
let mut spawn_attempts = 0;
let desired_monsters = 15;
let mut spawn_amount = 0;
while spawn_attempts < max_spaw... | {
*tile = Tile::empty();
} | conditional_block |
map.rs | //less wonky math when dealing with negatives
pub fn | (width:i32, height:i32, default_tile:Tile) -> Self {
assert!(width > 0, "width must be greater than 0!");
assert!(height > 0, "height must be greater than 0!");
Map {
tiles: vec![default_tile; (height * width) as usize],
width:width,
height:height,
... | new | identifier_name |
encode.rs | num_bytes = 0;
let mut output = BufWriter::new(output);
self.check_options()?;
if self.parts == 1 {
write!(
output,
"=ybegin line={} size={} name={}\r\n",
self.line_length, length, input_filename
)?;
} else {
... | 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148,
149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
165, 166, 167, 168, 13, 10, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
... | random_line_split | |
encode.rs | .1);
2
}
DOT if col == 0 => {
v.push(DOT);
2
}
_ => 1,
};
if col >= line_length {
v.push(CR);
v.push(LF);
col = 0;
}
});
writer.write_all(&v)?;
Ok(col)
... | {
let encode_options = EncodeOptions::new().parts(2).part(1).end(38400);
let vr = encode_options.check_options();
assert!(vr.is_err());
} | identifier_body | |
encode.rs | only
/// one part is encoded. In case of multipart, the part number, begin and end offset need
/// to be specified in the `EncodeOptions`. When directly encoding to an NNTP stream, the
/// caller needs to take care of the message header and end of multi-line block (`".\r\n"`).
///
/// # Example
... |
_ => 1,
};
if col >= line_length {
v.push(CR);
v.push(LF);
col = 0;
}
});
writer.write_all(&v)?;
Ok(col)
}
#[inline(always)]
fn encode_byte(input_byte: u8) -> (u8, u8) {
let mut output = (0, 0);
let output_byte = input_byte.o... | {
v.push(DOT);
2
} | conditional_block |
encode.rs | only
/// one part is encoded. In case of multipart, the part number, begin and end offset need
/// to be specified in the `EncodeOptions`. When directly encoding to an NNTP stream, the
/// caller needs to take care of the message header and end of multi-line block (`".\r\n"`).
///
/// # Example
... | <R, W>(
&self,
input: R,
output: W,
length: u64,
input_filename: &str,
) -> Result<(), EncodeError>
where
R: Read + Seek,
W: Write,
{
let mut rdr = BufReader::new(input);
let mut checksum = crc32fast::Hasher::new();
let mut buff... | encode_stream | identifier_name |
messagepass.py | 0) # find product of incoming msgs & normalize
for f in model.factorsWith(v): beliefs_V[i] *= msg[f,v]
beliefs_V[i] /= beliefs_V[i].sum() # divide by f->i to get msg i->f
for f in model.factorsWith(v): msg[v,f] = beliefs_V[i]/msg[f,v]
#for f in model... |
################ DECOMPOSITION METHODS #############################################
#@do_profile(follow=[get_number])
def DualDecomposition(model, maxIter=100, verbose=False):
""" ub,lb,xhat = DualDecomposition( model [,maxiter,verbose] )
Compute a decomposition-based upper bound & estimate of the MAP of ... | if verbose: print("Iter "+str(t)+": "+str(lnZ))
return lnZ,beliefs
| random_line_split |
messagepass.py | 0) # find product of incoming msgs & normalize
for f in model.factorsWith(v): beliefs_V[i] *= msg[f,v]
beliefs_V[i] /= beliefs_V[i].sum() # divide by f->i to get msg i->f
for f in model.factorsWith(v): msg[v,f] = beliefs_V[i]/msg[f,v]
#for f in model... | (thetas,weights,pri,Xi,steps,threshold=1e-4,direction=+1, optTol=1e-8,progTol=1e-8):
import copy
f0,f1 = None, calc_bound(thetas,weights,pri) # init prev, current objective values
match = reduce(lambda a,b: a&b, [th.vars for th in thetas], thetas[0].vars)
idx = [th.v.index(... | armijo | identifier_name |
messagepass.py | m *= beliefs[v]
lnZ += m.sum()
if verbose: print("Iter 0: "+str(lnZ))
for t in xrange(1,maxIter+1): # for each iteration:
# Update all the beliefs via coordinate ascent:
for Xi in model.X: # for each variable,
bNew = 0.0 ... | th.t[:] = nth.t # rewrite tables | conditional_block | |
messagepass.py | 0) # find product of incoming msgs & normalize
for f in model.factorsWith(v): beliefs_V[i] *= msg[f,v]
beliefs_V[i] /= beliefs_V[i].sum() # divide by f->i to get msg i->f
for f in model.factorsWith(v): msg[v,f] = beliefs_V[i]/msg[f,v]
#for f in model... |
def calc_bound( thetas, weights, pri):
return sum([wt_elim(th,wt,pri) for th,wt in zip(thetas,weights)])
def calc_deriv(th,w,pri,match,Xi=None):
elim_ord = np.argsort( [pri[x] for x in th.vars] )
lnZ0 = th.copy()
lnmu = 0.0 * lnZ0
for i in elim_ord: # run over v[i],w[i]... | elim_ord = np.argsort( [pri[x] for x in f.vars] )
tmp = f
for i in elim_ord: tmp = tmp.lsePower([f.v[i]],1.0/w[i])
return tmp | identifier_body |
ledgerstate.go | DAG: branchDAG,
UTXODAG: ledgerstate.NewUTXODAG(tangle.Options.Store, branchDAG),
}
}
// Shutdown shuts down the LedgerState and persists its state.
func (l *LedgerState) Shutdown() {
l.UTXODAG.Shutdown()
l.BranchDAG.Shutdown()
}
// InheritBranch implements the inheritance rules for Branches in the Tangle. It ... |
// include only transactions with at least one unspent output
if includeTransaction {
snapshot.Transactions[transaction.ID()] = ledgerstate.Record{
Essence: transaction.Essence(),
UnlockBlocks: transaction.UnlockBlocks(),
UnspentOutputs: unspentOutputs,
}
}
}
// TODO ??? due to poss... | {
l.CachedOutputMetadata(output.ID()).Consume(func(outputMetadata *ledgerstate.OutputMetadata) {
if outputMetadata.ConfirmedConsumer() == ledgerstate.GenesisTransactionID { // no consumer yet
unspentOutputs[i] = true
includeTransaction = true
} else {
tx := copyLedgerState[outputMetadata.Confi... | conditional_block |
ledgerstate.go | DAG: branchDAG,
UTXODAG: ledgerstate.NewUTXODAG(tangle.Options.Store, branchDAG),
}
}
// Shutdown shuts down the LedgerState and persists its state.
func (l *LedgerState) Shutdown() {
l.UTXODAG.Shutdown()
l.BranchDAG.Shutdown()
}
// InheritBranch implements the inheritance rules for Branches in the Tangle. It ... |
startSnapshot := time.Now()
copyLedgerState := l.Transactions() // consider that this may take quite some time
for _, transaction := range copyLedgerState {
// skip unconfirmed transactions
inclusionState, err := l.TransactionInclusionState(transaction.ID())
if err != nil || inclusionState != ledgerstate.Con... | random_line_split | |
ledgerstate.go | ) {
if referencedBranchIDs.Contains(ledgerstate.InvalidBranchID) {
inheritedBranch = ledgerstate.InvalidBranchID
return
}
branchIDsContainRejectedBranch, inheritedBranch := l.BranchDAG.BranchIDsContainRejectedBranch(referencedBranchIDs)
if branchIDsContainRejectedBranch {
return
}
cachedAggregatedBranch, ... | CachedOutputMetadata | identifier_name | |
ledgerstate.go | DAG: branchDAG,
UTXODAG: ledgerstate.NewUTXODAG(tangle.Options.Store, branchDAG),
}
}
// Shutdown shuts down the LedgerState and persists its state.
func (l *LedgerState) Shutdown() |
// InheritBranch implements the inheritance rules for Branches in the Tangle. It returns a single inherited Branch
// and automatically creates an AggregatedBranch if necessary.
func (l *LedgerState) InheritBranch(referencedBranchIDs ledgerstate.BranchIDs) (inheritedBranch ledgerstate.BranchID, err error) {
if refer... | {
l.UTXODAG.Shutdown()
l.BranchDAG.Shutdown()
} | identifier_body |
evaluation_utils.py | is None:
subword_option = 'None'
subword_option += metric[pos:]
metric = metric[0:pos]
if metric.lower() == "bleu":
evaluation_score = _bleu(ref_file, trans_file,
subword_option=subword_option)
elif len(metric.lower()) > 4 and metric.lower()[0:4]=='bleu':
max_ord... | sentence = sentence.replace(" ", "")
sentence = sentence.replace("<SPACE>"," ")
if subword_option_1 == 'char':
sentence = sentence.replace("<SPACE>", "")
sentence = sentence.replace("@@", "")
sentence = sentence.replace(" ","")
sentence = " ".join(sentence)
elif subword_option_1 == 'char2cha... | """Clean and handle BPE or SPM outputs."""
sentence = sentence.strip()
if subword_option is not None and '@' in subword_option:
subword_option_0 = subword_option.split('@')[0]
subword_option_1 = subword_option.split('@')[1]
else:
subword_option_0 = None
subword_option_1 = None
# BPE
if subword... | identifier_body |
evaluation_utils.py | is None:
subword_option = 'None'
subword_option += metric[pos:]
metric = metric[0:pos]
if metric.lower() == "bleu":
evaluation_score = _bleu(ref_file, trans_file,
subword_option=subword_option)
elif len(metric.lower()) > 4 and metric.lower()[0:4]=='bleu':
max_ord... |
elif metric.lower()[0:len('distinct_c')] == 'distinct_c':
max_order = int(metric.lower()[len('distinct_c')+1:])
evaluation_score = _distinct_c(trans_file,max_order,subword_option=subword_option)
else:
raise ValueError("Unknown metric %s" % metric)
return evaluation_score
def _clean(sentence, subwo... | max_order = int(metric.lower()[len('distinct')+1:])
evaluation_score = _distinct(trans_file,max_order,subword_option=subword_option) | conditional_block |
evaluation_utils.py | is None:
subword_option = 'None'
subword_option += metric[pos:]
metric = metric[0:pos]
if metric.lower() == "bleu":
evaluation_score = _bleu(ref_file, trans_file,
subword_option=subword_option)
elif len(metric.lower()) > 4 and metric.lower()[0:4]=='bleu':
max_ord... | # bleu_score, precisions, bp, ratio, translation_length, reference_length
bleu_score, _, _, _, _, _ = bleu.compute_bleu(
per_segment_references, translations, max_order, smooth)
return 100 * bleu_score
def _rouge(ref_file, summarization_file, subword_option=None):
"""Compute ROUGE scores and handling BP... | for line in fh:
line = _clean(line, subword_option=subword_option)
translations.append(line.split(" "))
print(translations[0:15]) | random_line_split |
evaluation_utils.py | is None:
subword_option = 'None'
subword_option += metric[pos:]
metric = metric[0:pos]
if metric.lower() == "bleu":
evaluation_score = _bleu(ref_file, trans_file,
subword_option=subword_option)
elif len(metric.lower()) > 4 and metric.lower()[0:4]=='bleu':
max_ord... | (trans_file,max_order=1, subword_option=None):
"""Compute Distinct Score"""
translations = []
with codecs.getreader("utf-8")(tf.gfile.GFile(trans_file, "rb")) as fh:
for line in fh:
line = _clean(line, subword_option=subword_option)
translations.append(line.split(" "))
num_tokens = 0
unique_... | _distinct | identifier_name |
router.go | InProgressCh chan struct{}
closedCh chan struct{}
closed bool
closedLock sync.Mutex
logger watermill.LoggerAdapter
publisherDecorators []PublisherDecorator
subscriberDecorators []SubscriberDecorator
isRunning bool
running chan struct{}
}
// Logger returns the Router's log... |
func (r *Router) addRouterLevelMiddleware(m ...HandlerMiddleware) {
for _, handlerMiddleware := range m {
middleware := middleware{
Handler: handlerMiddleware,
HandlerName: "",
IsRouterLevel: true,
}
r.middlewares = append(r.middlewares, middleware)
}
}
func (r *Router) addHandlerLevelMiddle... | {
r.logger.Debug("Adding middleware", watermill.LogFields{"count": fmt.Sprintf("%d", len(m))})
r.addRouterLevelMiddleware(m...)
} | identifier_body |
router.go | scribeTopic string,
subscriber Subscriber,
handlerFunc NoPublishHandlerFunc,
) *Handler {
handlerFuncAdapter := func(msg *Message) ([]*Message, error) {
return nil, handlerFunc(msg)
}
return r.AddHandler(handlerName, subscribeTopic, subscriber, "", disabledPublisher{}, handlerFuncAdapter)
}
// Run runs all plu... | Stopped | identifier_name | |
router.go | losingInProgressCh chan struct{}
closedCh chan struct{}
closed bool
closedLock sync.Mutex
logger watermill.LoggerAdapter
publisherDecorators []PublisherDecorator
subscriberDecorators []SubscriberDecorator
isRunning bool
running chan struct{}
}
// Logger returns the Router... | // Handlers returns all registered handlers.
func (r *Router) Handlers() map[string]HandlerFunc {
handlers := map[string]HandlerFunc{}
for handlerName, handler := range r.handlers {
handlers[handlerName] = handler.handlerFunc
}
return handlers
}
// DuplicateHandlerNameError is sent in a panic when you try to a... |
r.subscriberDecorators = append(r.subscriberDecorators, dec...)
}
| random_line_split |
router.go | }
r.logger.Debug("Subscribing to topic", watermill.LogFields{
"subscriber_name": h.name,
"topic": h.subscribeTopic,
})
ctx, cancel := context.WithCancel(ctx)
messages, err := h.subscriber.Subscribe(ctx, h.subscribeTopic)
if err != nil {
cancel()
return errors.Wrapf(err, "cannot subs... | {
ctx := msg.Context()
if h.name != "" {
ctx = context.WithValue(ctx, handlerNameKey, h.name)
}
if h.publisherName != "" {
ctx = context.WithValue(ctx, publisherNameKey, h.publisherName)
}
if h.subscriberName != "" {
ctx = context.WithValue(ctx, subscriberNameKey, h.subscriberName)
}
if h.subs... | conditional_block | |
entry_query.go | int, err error) {
var ids []int
if ids, err = eq.Limit(1).IDs(setContextOp(ctx, eq.ctx, "FirstID")); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{entry.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (eq *EntryQuery) FirstIDX(ctx conte... | (ctx context.Context) (int, error) {
ctx = setContextOp(ctx, eq.ctx, "Count")
if err := eq.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, eq, querierCount[*EntryQuery](), eq.inters)
}
// CountX is like Count, but panics if an error occurs.
func (eq *EntryQuery) CountX(ctx conte... | Count | identifier_name |
entry_query.go | id int, err error) {
var ids []int
if ids, err = eq.Limit(1).IDs(setContextOp(ctx, eq.ctx, "FirstID")); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{entry.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (eq *EntryQuery) FirstIDX(ctx con... | id, err := eq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Entries.
func (eq *EntryQuery) All(ctx context.Context) ([]*Entry, error) {
ctx = setContextOp(ctx, eq.ctx, "All")
if err := eq.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierA... | return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (eq *EntryQuery) OnlyIDX(ctx context.Context) int { | random_line_split |
entry_query.go | int, err error) {
var ids []int
if ids, err = eq.Limit(1).IDs(setContextOp(ctx, eq.ctx, "FirstID")); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{entry.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (eq *EntryQuery) FirstIDX(ctx conte... |
}
}
for _, f := range eq.ctx.Fields {
if !entry.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if eq.path != nil {
prev, err := eq.path(ctx)
if err != nil {
return err
}
eq.sql = prev
}
return nil
}
func (eq *EntryQuery) sqlAll(ct... | {
return err
} | conditional_block |
entry_query.go | id int, err error) {
var ids []int
if ids, err = eq.Limit(1).IDs(setContextOp(ctx, eq.ctx, "FirstID")); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{entry.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (eq *EntryQuery) FirstIDX(ctx con... | }
eq.sql = prev
}
return nil
}
func (eq *EntryQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Entry, error) {
var (
nodes = []*Entry{}
_spec = eq.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Entry).scanValues(nil, columns)
}
_spec.Assign = func(columns ... | {
for _, inter := range eq.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, eq); err != nil {
return err
}
}
}
for _, f := range eq.ctx.Fields {
if !entry.ValidColu... | identifier_body |
volumes.go | [string]struct{}
// byName is a mapping of volume names to swarmkit volume IDs.
byName map[string]string
}
// volumeUsage contains information about the usage of a Volume by a specific
// task.
type volumeUsage struct {
nodeID string
readOnly bool
}
// volumeInfo contains scheduler information about a given vol... | () *volumeSet {
return &volumeSet{
volumes: map[string]volumeInfo{},
byGroup: map[string]map[string]struct{}{},
byName: map[string]string{},
}
}
// getVolume returns the volume object for the given ID as stored in the
// volumeSet, or nil if none exists.
//
//nolint:unused // TODO(thaJeztah) this is currently... | newVolumeSet | identifier_name |
volumes.go | [string]struct{}
// byName is a mapping of volume names to swarmkit volume IDs.
byName map[string]string
}
// volumeUsage contains information about the usage of a Volume by a specific
// task.
type volumeUsage struct {
nodeID string
readOnly bool
}
// volumeInfo contains scheduler information about a given vol... |
// chooseTaskVolumes selects a set of VolumeAttachments for the task on the
// given node. it expects that the node was already validated to have the
// necessary volumes, but it will return an error if a full set of volumes is
// not available.
func (vs *volumeSet) chooseTaskVolumes(task *api.Task, nodeInfo *NodeInf... | {
if info, ok := vs.volumes[volumeID]; ok {
// if the volume exists in the set, look up its group ID and remove it
// from the byGroup mapping as well
group := info.volume.Spec.Group
delete(vs.byGroup[group], volumeID)
delete(vs.volumes, volumeID)
delete(vs.byName, info.volume.Spec.Annotations.Name)
}
} | identifier_body |
volumes.go | "github.com/moby/swarmkit/v2/api"
"github.com/moby/swarmkit/v2/manager/state/store"
)
// the scheduler package does double duty -- in addition to choosing nodes, it
// must also choose volumes. this is because volumes are fungible, and can be
// scheduled to several nodes, and used by several tasks. we should endeav... | random_line_split | ||
volumes.go | [string]struct{}
// byName is a mapping of volume names to swarmkit volume IDs.
byName map[string]string
}
// volumeUsage contains information about the usage of a Volume by a specific
// task.
type volumeUsage struct {
nodeID string
readOnly bool
}
// volumeInfo contains scheduler information about a given vol... |
}
}
func (vs *volumeSet) reserveVolume(volumeID, taskID, nodeID string, readOnly bool) {
info, ok := vs.volumes[volumeID]
if !ok {
// TODO(dperny): don't just return nothing.
return
}
info.tasks[taskID] = volumeUsage{nodeID: nodeID, readOnly: readOnly}
// increment the reference count for this node.
info.... | {
if mount.Source == va.Source && mount.Target == va.Target {
vs.reserveVolume(va.ID, task.ID, task.NodeID, mount.ReadOnly)
}
} | conditional_block |
handlers.go | (c chan bool, longRunningRequestCheck LongRunningRequestCheck, handler http.Handler) http.Handler {
if c == nil {
return handler
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if longRunningRequestCheck(r) {
// Skip tracking long running events.
handler.ServeHTTP(w, r)
return
... | (req *http.Request) authorizer.Attributes {
attribs := authorizer.AttributesRecord{}
ctx, ok := r.requestContextMapper.Get(req)
if ok {
user, ok := api.UserFrom(ctx)
if ok {
attribs.User = user
}
}
requestInfo, _ := r.requestInfoResolver.GetRequestInfo(req)
// Start with common attributes that apply t... | GetAttribs | identifier_name |
handlers.go | (c chan bool, longRunningRequestCheck LongRunningRequestCheck, handler http.Handler) http.Handler {
if c == nil {
return handler
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if longRunningRequestCheck(r) {
// Skip tracking long running events.
handler.ServeHTTP(w, r)
return
... |
tw.timedOut = true
}
func (tw *baseTimeoutWriter) closeNotify() <-chan bool {
return tw.w.(http.CloseNotifier).CloseNotify()
}
func (tw *baseTimeoutWriter) hijack() (net.Conn, *bufio.ReadWriter, error) {
tw.mu.Lock()
defer tw.mu.Unlock()
if tw.timedOut {
return nil, nil, http.ErrHandlerTimeout
}
conn, rw, e... | {
tw.w.WriteHeader(http.StatusGatewayTimeout)
if msg != "" {
tw.w.Write([]byte(msg))
} else {
enc := json.NewEncoder(tw.w)
enc.Encode(errors.NewServerTimeout(api.Resource(""), "", 0))
}
} | conditional_block |
handlers.go | (c chan bool, longRunningRequestCheck LongRunningRequestCheck, handler http.Handler) http.Handler {
if c == nil {
return handler
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if longRunningRequestCheck(r) {
// Skip tracking long running events.
handler.ServeHTTP(w, r)
return
... |
type timeoutHandler struct {
handler http.Handler
timeout func(*http.Request) (<-chan time.Time, string)
}
func (t *timeoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
after, msg := t.timeout(r)
if after == nil {
t.handler.ServeHTTP(w, r)
return
}
done := make(chan struct{}, 1)
tw := newT... | {
return &timeoutHandler{h, timeoutFunc}
} | identifier_body |
handlers.go | (c chan bool, longRunningRequestCheck LongRunningRequestCheck, handler http.Handler) http.Handler {
if c == nil {
return handler
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if longRunningRequestCheck(r) {
// Skip tracking long running events.
handler.ServeHTTP(w, r)
return
... |
type hijackTimeoutWriter struct {
*baseTimeoutWriter
}
func (tw *hijackTimeoutWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return tw.hijack()
}
type closeHijackTimeoutWriter struct {
*baseTimeoutWriter
}
func (tw *closeHijackTimeoutWriter) CloseNotify() <-chan bool {
return tw.closeNotify()
}
func (... |
func (tw *closeTimeoutWriter) CloseNotify() <-chan bool {
return tw.closeNotify()
} | random_line_split |
test.py | tf.app.flags.DEFINE_integer(
'replicas_to_aggregate', 1,
'The Number of gradients to collect before updating params.')
tf.app.flags.DEFINE_float(
'moving_average_decay', None,
'The decay to use for the moving average.'
'If left as None, then moving averages are not used.')
#######################
... |
def main(_):
if not FLAGS.dataset_dir:
raise ValueError('You must supply the dataset directory with --dataset_dir')
tf.logging.set_verbosity(tf.logging.INFO)
graph = tf.Graph()
with graph.as_default():
######################
# Config model_deploy#
###################... | """Returns a list of variables to train.
Returns:
A list of variables to train by the optimizer.
"""
if FLAGS.trainable_scopes is None:
return tf.trainable_variables()
else:
scopes = [scope.strip() for scope in FLAGS.trainable_scopes.split(',')]
variables_to_train = []
fo... | identifier_body |
test.py | elif FLAGS.optimizer == 'ftrl':
optimizer = tf.train.FtrlOptimizer(
learning_rate,
learning_rate_power=FLAGS.ftrl_learning_rate_power,
initial_accumulator_value=FLAGS.ftrl_initial_accumulator_value,
l1_regularization_strength=FLAGS.ftrl_l1,
l2_regular... | # opt=optimizer,
# replicas_to_aggregate=FLAGS.replicas_to_aggregate,
# variable_averages=variable_averages,
# variables_to_average=moving_average_variables, | random_line_split | |
test.py | .app.flags.DEFINE_integer(
'replicas_to_aggregate', 1,
'The Number of gradients to collect before updating params.')
tf.app.flags.DEFINE_float(
'moving_average_decay', None,
'The decay to use for the moving average.'
'If left as None, then moving averages are not used.')
#######################
# ... | (_):
if not FLAGS.dataset_dir:
raise ValueError('You must supply the dataset directory with --dataset_dir')
tf.logging.set_verbosity(tf.logging.INFO)
graph = tf.Graph()
with graph.as_default():
######################
# Config model_deploy#
######################
... | main | identifier_name |
test.py | _clones,
clone_on_cpu=FLAGS.clone_on_cpu,
replica_id=FLAGS.task,
num_replicas=FLAGS.worker_replicas,
num_ps_tasks=FLAGS.num_ps_tasks)
# # Create global_step
# with tf.device(deploy_config.variables_device()):
# global_step = slim.create_global... | start_idx = i * FLAGS.batch_size
end_idx = (i + 1) * FLAGS.batch_size
speech, mouth, label = fileh.root.speech[start_idx:end_idx], fileh.root.mouth[
start_idx:end_idx], fileh.root.label[
... | conditional_block | |
run.go | ) {
processLock.Lock()
val := integrations[id]
if val != "" {
processLock.Unlock()
return val, nil
}
var res integrationResult
if err := gclient.Query(integrationQuery, graphql.Variables{"id": id}, &res); err != nil {
processLock.Unlock()
return "", err
}
if res.Data == nil {
processLock.... | random_line_split | ||
run.go | )
func vetDBChange(evt event.SubscriptionEvent, enrollmentID string) (integrationInstruction, *agent.IntegrationInstance, error) {
var dbchange DBChange
if err := json.Unmarshal([]byte(evt.Data), &dbchange); err != nil {
return 0, nil, fmt.Errorf("error decoding dbchange: %w", err)
}
var instance agent.Integrati... |
if instance.Active == true && instance.Setup == agent.IntegrationInstanceSetupReady {
return shouldStart, &instance, nil
}
if instance.Active == false && instance.Deleted == true {
return shouldStop, &instance, nil
}
return doNothing, nil, nil
}
type integrationResult struct {
Data *struct {
Integration s... | {
return doNothing, nil, nil
} | conditional_block |
run.go | )
func vetDBChange(evt event.SubscriptionEvent, enrollmentID string) (integrationInstruction, *agent.IntegrationInstance, error) {
var dbchange DBChange
if err := json.Unmarshal([]byte(evt.Data), &dbchange); err != nil {
return 0, nil, fmt.Errorf("error decoding dbchange: %w", err)
}
var instance agent.Integrati... |
func setIntegrationRunning(client graphql.Client, integrationInstanceID string) error {
vars := graphql.Variables{
agent.IntegrationInstanceModelSetupColumn: agent.IntegrationInstanceSetupRunning,
}
if err := agent.ExecIntegrationInstanceSilentUpdateMutation(client, integrationInstanceID, vars, false); err != ni... | {
log.Info(logger, "updating enrollment", "setting", datefield, "enrollment_id", enrollmentID, "active", active)
now := datetime.NewDateNow()
vars := make(graphql.Variables)
if datefield != "" {
vars[datefield] = now
vars[agent.EnrollmentModelRunningColumn] = active
}
vars[agent.EnrollmentModelLastPingDateCol... | identifier_body |
run.go | (config *runner.ConfigFile, channel string, force bool) (bool, error) {
var resp struct {
Expired bool `json:"expired"`
Valid bool `json:"valid"`
}
if !force {
res, err := api.Get(context.Background(), channel, api.AuthService, "/validate?customer_id="+config.CustomerID, config.APIKey)
if err != nil {
r... | validateConfig | identifier_name | |
admin-bro.ts | TranslateFunctions, createFunctions } from './utils/translate-functions.factory'
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf-8'))
export const VERSION = pkg.version
const defaults: AdminBroOptionsWithDefault = {
rootPath: DEFAULT_PATHS.rootPath,
logoutPath: DEFAULT_PATHS.... | }
/**
* Returns resource base on its ID
*
* @example
* const User = admin.findResource('users')
* await User.findOne(userId)
*
* @param {String} resourceId ID of a resource defined under {@link BaseResource#id}
* @return {BaseResource} found resource
* @throws {Error} ... | * the form
* @return {Promise<string>} HTML of the rendered page
*/
async renderLogin({ action, errorMessage }): Promise<string> {
return loginTemplate(this, { action, errorMessage }) | random_line_split |
admin-bro.ts | = pkg.version
const defaults: AdminBroOptionsWithDefault = {
rootPath: DEFAULT_PATHS.rootPath,
logoutPath: DEFAULT_PATHS.logoutPath,
loginPath: DEFAULT_PATHS.loginPath,
databases: [],
resources: [],
branding: {
companyName: 'Company',
softwareBrothers: true,
},
dashboard: {},
assets: {
s... | {
const resource = this.resources.find(m => m._decorated?.id() === resourceId)
if (!resource) {
throw new Error([
`There are no resources with given id: "${resourceId}"`,
'This is the list of all registered resources you can use:',
this.resources.map(r => r._decorated?.id() || r.id... | identifier_body | |
admin-bro.ts | * // see how `admin-bro-expressjs` plugin does it.
* })
*/
public static Router: RouterType
/**
* An abstract class for all Database Adapters.
* External adapters have to implement it.
*
* @example <caption>Creating Database Adapter for some ORM</caption>
* const { BaseDatabase } = require(... | {
const stack = ((new Error()).stack || '').split('\n')
// Node = 8 shows stack like that: '(/path/to/file.ts:77:27)
const pathNode8 = stack[2].match(/\((.*):[0-9]+:[0-9]+\)/)
// Node >= 10 shows stack like that: 'at /path/to/file.ts:77:27
const pathNode10 = stack[2].match(/at (.*):[0-9]+:... | conditional_block | |
admin-bro.ts | Functions, createFunctions } from './utils/translate-functions.factory'
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf-8'))
export const VERSION = pkg.version
const defaults: AdminBroOptionsWithDefault = {
rootPath: DEFAULT_PATHS.rootPath,
logoutPath: DEFAULT_PATHS.logoutPath... | ({ action, errorMessage }): Promise<string> {
return loginTemplate(this, { action, errorMessage })
}
/**
* Returns resource base on its ID
*
* @example
* const User = admin.findResource('users')
* await User.findOne(userId)
*
* @param {String} resourceId ID of a resource defined under ... | renderLogin | identifier_name |
movies.go |
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
// IMPORTANT, use defer cancel() so we can cancel the context before Get() returns.
defer cancel()
// Execute the query NOTE: that we have to use pg.Array() here
// err := m.DB.QueryRow(stmt, id).Scan(
// &[]byte{}, // for the pg_sleep(10... | RecordNotFound
}
return nil
| conditional_block | |
movies.go | .
if id < 1 {
return nil, ErrRecordNotFound
}
// Sql query
// pq_sleep(10) to simulate a long running query
// stmt := `SELECT pg_sleep(10),id,created_at,title,year,runtime,genres,version
// FROM movies
// WHERE id = $1`
stmt := `SELECT id,created_at,title,year,runtime,genres,version
FROM mov... | 4) err | identifier_name | |
movies.go | v.Check(movie.Title != "", "title", "must be provided")
v.Check(len(movie.Title) <= 500, "title", "must not be more than 500 bytes long")
v.Check(movie.Runtime != 0, "runtime", "must be provided")
v.Check(movie.Runtime > 0, "runtime", "must be a positive integer")
v.Check(movie.Genres != nil, "genres", "must be ... | he SQL query for inserting a new record in the movies table and returning the system generated data
query := `INSERT INTO movies (title, year, runtime, genres)
VALUES ($1, $2, $3, $4)
RETURNING id, created_at, version`
// Create an args slice containing the values for the placeholder parameters from the... | identifier_body | |
movies.go | 3 second timeout deadline.
// emtpy context.Background() is the parent context
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
// IMPORTANT, use defer cancel() so we can cancel the context before Get() returns.
defer cancel()
// Execute the query NOTE: that we have to use pg.Array() here... | random_line_split | ||
GetSolStats.py | s):
global Verbose
if Verbose > 0:
print s
def dprint (s):
global Verbose
if Verbose > 2:
print '---\n', s
#----------------------------------------------------------------------------
# HTTP utils
# TODO: move to a lib
#
def open_http( url, user, passwd):
|
def post_http (req, url = '/SEMP'):
global Hdrs
dprint ("request: %s" % req)
dprint ("Posting to URL %s" % url)
Conn.request("POST", url, req, Hdrs)
res = Conn.getresponse()
if not res:
raise Exception ("No SEMP response")
resp = res.read()
if resp is None:
... | global Hdrs
auth = string.strip(base64.encodestring(user+":"+passwd))
Hdrs = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
Hdrs["Authorization"] = "Basic %s" % auth
print ("Opening HTTP connection to [%s]" % url)
dprint ("Headers: %s" % Hdrs.items())
t... | identifier_body |
GetSolStats.py | (s):
global Verbose
if Verbose > 0:
print s
def dprint (s):
global Verbose
if Verbose > 2:
print '---\n', s
#----------------------------------------------------------------------------
# HTTP utils
# TODO: move to a lib
#
def open_http( url, user, passwd):
global Hdrs
aut... | vprint | identifier_name | |
GetSolStats.py | s):
global Verbose
if Verbose > 0:
|
def dprint (s):
global Verbose
if Verbose > 2:
print '---\n', s
#----------------------------------------------------------------------------
# HTTP utils
# TODO: move to a lib
#
def open_http( url, user, passwd):
global Hdrs
auth = string.strip(base64.encodestring(user+":"+passwd))
... | print s | conditional_block |
GetSolStats.py | s):
global Verbose
if Verbose > 0:
print s
def dprint (s):
global Verbose
if Verbose > 2:
print '---\n', s
#----------------------------------------------------------------------------
# HTTP utils
# TODO: move to a lib
#
def open_http( url, user, passwd):
global Hdrs
auth ... | stats['timestamp'] = time.strftime("%Y%m%d %H:%M:%S")
print ("%-3d/%-3s) %s" % (n+1, r.samples, stats['timestamp']))
# Post SEMP Request -- vpn_stats
print (' Processing SEMP Request %s' % 'show/vpn_stats.xml')
semp_req = read_semp_req ('show/vpn_stats.xml') % (SEMP_VERSION, r.vpn)
dprint ("SEMP R... |
# Gather and save stats
vprint ("Collecting %s stats every %s seconds" % (r.samples, nap))
n = 0
while (n < int(r.samples)): | random_line_split |
minwinbase.rs | HANDLE
}
}
pub
type
LPOVERLAPPED
=
*
mut
OVERLAPPED
;
STRUCT
!
{
struct
OVERLAPPED_ENTRY
{
lpCompletionKey
:
ULONG_PTR
lpOverlapped
:
LPOVERLAPPED
Internal
:
ULONG_PTR
dwNumberOfBytesTransferred
:
DWORD
}
}
pub
type
LPOVERLAPPED_ENTRY
=
*
mut
OVERLAPPED_ENTRY
;
STRUCT
!
{
struct
SYSTEMTIME
{
wYear
:
WORD
wMonth
:
WORD
... | REASON_CONTEXT_Reason
{
[
u32
;
4
]
[
u64
;
3
]
Detailed
Detailed_mut
:
REASON_CONTEXT_Detailed
SimpleReasonString
SimpleReasonString_mut
:
LPWSTR
}
}
STRUCT
!
{
struct
REASON_CONTEXT
{
Version
:
ULONG
Flags
:
DWORD
Reason
:
REASON_CONTEXT_Reason
}
}
pub
type
PREASON_CONTEXT
=
*
mut
REASON_CONTEXT
;
pub
const
EXCEPTION... | UNION
!
{
union | random_line_split |
server.py | ():
g.db, g.headers, g.queries = getDb()
h = g.headers.keys()
h.sort()
h.reverse()
i = {}
for k in h:
i[k] = g.headers[k].keys()
i[k].sort()
g.headersNames = h
g.colsNames = i
@app.after_request
def after_request(response):
return response
@app.teardown_request... | before_request | identifier_name | |
server.py | = []
res = None
if len(g.queries[sessionId]) == 0:
res = None
print "no queries to session %s" % (str(sessionId))
else:
if qry in [x[0] for x in g.queries[sessionId]]:
print "session %s has qry in store (%d)" % (str(sessionId), len(g.queries[sessionId]))
f... | if db is None:
init_db(joiner.dbfile, joiner.indexfile)
return [db, headers, queries] | identifier_body | |
server.py | ardown_request
def teardown_request(exception):
pass
#APPLICATION CODE :: ROUTE
@app.route('/', methods=['GET'])
def initial():
sessionId = time.time()
if session.get('id'):
sessionId = session['id']
print "getting stored ID %s" % (sessionId)
else:
session['id'] = sessionId... |
if page > maxPage:
page = maxPage
perc = int((float(page) / maxPage) * 100)
beginPos = (page - 1) * PER_PAGE
print " count %d page %d max page %d perc %d%% begin pos %d" % (count, page, maxPage, perc, beginPos)
resPage = res
... | maxPage += 1 | conditional_block |
server.py | ardown_request
def teardown_request(exception):
pass
#APPLICATION CODE :: ROUTE
@app.route('/', methods=['GET'])
def initial():
sessionId = time.time()
if session.get('id'):
sessionId = session['id']
print "getting stored ID %s" % (sessionId)
else:
session['id'] = sessionId... | g.queries[sessionId] = []
res = None
if len(g.queries[sessionId]) == 0:
res = None
print "no queries to session %s" % (str(sessionId))
else:
if qry in [x[0] for x in g.queries[sessionId]]:
print "session %s has qry in store (%d)" % (str(sessionId), len(g.queries... |
#APPLICATION CODE :: ACESSORY FUNCTIONS
def queryBuffer(sessionId, qry):
if sessionId not in g.queries:
print g.queries.keys() | random_line_split |
metar.py | i = 0
inserts = []
INSBUF = cursor.arraysize
today_prefix = datetime.utcnow().strftime('%Y%m')
yesterday_prefix = (datetime.utcnow() + timedelta(days=-1)).strftime('%Y%m')
today = datetime.utcnow().strftime('%d')
for line in f.readlines():
if line[0].isalp... | run | identifier_name | |
metar.py | * FROM airports
WHERE icao = ? AND metar NOT NULL LIMIT 1''', (icao.upper(), ))
ret = res.fetchall()
if len(ret) > 0:
return ret[0]
return ret
def getCycle(self):
now = datetime.utcnow()
# Cycle is updated until the houre has arr... | cursor = db.cursor()
try:
f = open(os.sep.join([self.conf.syspath, 'METAR.rwx']), 'w')
except:
print "ERROR updating METAR.rwx file: %s %s" % (sys.exc_info()[0], sys.exc_info()[1])
return False
res = cursor.execute('SELECT icao, metar FROM airports WHERE met... | identifier_body | |
metar.py | .cachepath = os.sep.join([conf.cachepath, 'metar'])
if not os.path.exists(self.cachepath):
os.makedirs(self.cachepath)
self.database = os.sep.join([self.cachepath, 'metar.db'])
self.th_db = False
# Weather variables
self.weather = None
self.reparse = True
... |
m = self.RE_TEMPERATURE2.search(metar)
if m:
tp, temp, dp, dew = m.groups()
temp = float(temp) * 0.1
dew = float(dew) * 0.1
if tp == '1': temp *= -1
if dp == '1': dew *= -1
weather['temperature'] = [temp, dew]
else:
... | unit, press = m.groups()
press = float(press)
if unit:
if unit == 'A':
press = press/100
elif unit == 'SLP':
if press > 500:
press = c.pa2inhg((press / 10 + 900) * 100)
else:
... | conditional_block |
metar.py | achepath = os.sep.join([conf.cachepath, 'metar'])
if not os.path.exists(self.cachepath):
os.makedirs(self.cachepath)
self.database = os.sep.join([self.cachepath, 'metar.db'])
self.th_db = False
# Weather variables
self.weather = None
self.reparse = True
... |
def dbCreate(self, db):
cursor = db.cursor()
cursor.execute('''CREATE TABLE airports (icao text KEY UNIQUE, lat real, lon real, elevation int,
timestamp int KEY, metar text)''')
db.commit()
def updateStations(self, db, path):
''' Updates aiports db from ... |
self.last_latlon, self.last_station, self.last_timestamp = [False]*3
def dbConnect(self, path):
return sqlite3.connect(path, check_same_thread=False) | random_line_split |
lib.rs | proxy.set_authorization(Basic {
//! username: "John Doe".into(),
//! password: Some("Agent1234".into()),
//! });
//! let connector = HttpConnector::new(4, &handle);
//! let proxy_connector = ProxyConnec... | (&self, uri: &Uri) -> Option<&Proxy> {
self.proxies.iter().find(|p| p.intercept.matches(uri))
}
}
impl<C> Service for ProxyConnector<C>
where
C: Service<Request = Uri, Error = io::Error> + 'static,
C::Future: 'static,
<C::Future as Future>::Item: AsyncRead + AsyncWrite + 'static,
{
type Req... | match_proxy | identifier_name |
lib.rs | proxy.set_authorization(Basic {
//! username: "John Doe".into(),
//! password: Some("Agent1234".into()),
//! });
//! let connector = HttpConnector::new(4, &handle);
//! let proxy_connector = ProxyConnec... |
}
impl<F: Fn(&Uri) -> bool + Send + Sync + 'static> From<F> for Intercept {
fn from(f: F) -> Intercept {
Intercept::Custom(f.into())
}
}
/// A Proxy strcut
#[derive(Clone, Debug)]
pub struct Proxy {
intercept: Intercept,
headers: Headers,
uri: Uri,
}
impl Proxy {
/// Create a new `Pr... | {
match (self, uri.scheme()) {
(&Intercept::All, _)
| (&Intercept::Http, Some("http"))
| (&Intercept::Https, Some("https")) => true,
(&Intercept::Custom(Custom(ref f)), _) => f(uri),
_ => false,
}
} | identifier_body |
lib.rs | proxy.set_authorization(Basic {
//! username: "John Doe".into(),
//! password: Some("Agent1234".into()),
//! });
//! let connector = HttpConnector::new(4, &handle);
//! let proxy_connector = Pro... | pub struct Proxy {
intercept: Intercept,
headers: Headers,
uri: Uri,
}
impl Proxy {
/// Create a new `Proxy`
pub fn new<I: Into<Intercept>>(intercept: I, uri: Uri) -> Proxy {
Proxy {
intercept: intercept.into(),
uri: uri,
headers: Headers::new(),
... | #[derive(Clone, Debug)] | random_line_split |
ahrs_serv.py | # Funciones que sacan los valores de los sensores.
def accel_read():
global ahrs
global accel_addr
accel_data = [0,0,0]
##Sacamos los datos de acceleracion de los 3 ejes
#Eje X
xl = format(ahrs.read_byte_data(accel_addr,0x28), '#010b')[2:6]
xh = format(ahrs.read_byte_data(accel_addr,0x29), ... | random_line_split | ||
ahrs_serv.py |
def gyro_setup():
global ahrs
global gyro_addr
ahrs.write_byte_data(gyro_addr,0x20,0x8F) #DataRate 400Hz, BW 20Hz, All Axis enabled, Gyro ON
ahrs.write_byte_data(gyro_addr,0x23,0xA0) #Escala 2000dps, BlockUpdates
ahrs.write_byte_data(gyro_addr,0x24,0x02) #OutSel = 10h, use ... | global ahrs
global magn_addr
ahrs.write_byte_data(magn_addr,0x00,0x10) #Seteamos la velocidad de las mediciones a 15Hz
ahrs.write_byte_data(magn_addr,0x01,0x20) #Ponemos la escala +-1.3g
ahrs.write_byte_data(magn_addr,0x02,0x00) #Prendemos el magnetometro | identifier_body | |
ahrs_serv.py | twoSEq_2 * SEqHatDot_4 - twoSEq_3 * SEqHatDot_1 - twoSEq_4 * SEqHatDot_2
w_err_z = twoSEq_1 * SEqHatDot_4 - twoSEq_2 * SEqHatDot_3 + twoSEq_3 * SEqHatDot_2 - twoSEq_4 * SEqHatDot_1
# print "w_err_x: {}, w_err_y:{}, w_err_z:{}".format(w_err_x, w_err_y, w_err_z)
# print "zeta: {}".format(zeta)
# print "... | accel_data = accel_read()
magn_data = magn_read()
gyro_data = gyro_read()
#medimos tiempo
time_new = time.time()
#corremos el filtro
madgwicks_filter(accel_data, magn_data, gyro_data, time_new - time_old)
#Actualizamos el tiempo
time_old = time_new
#Calculamos los Angulos de Eule... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.