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 |
|---|---|---|---|---|
neurosky_ecg.py | t1.daemon = True
t1.start()
print "Started CardioChip reader"
def check(self):
""" checks if thread currently exists """
return self.connected
def stop(self):
""" stops running thread """
self.connected = False
def setHRVUpdate(self, numRRI):
... | (self):
"""
return the total number of RRIs held in the algorithm buffer
"""
return self.analyze.tg_ecg_get_total_rri_count()
def ecgalgAnalyzeRaw(self, D, nHRV=30): #, dataqueue):
"""
test to see if we have values in the ecg_buffer, and if so, pass
the most... | getTotalNumRRI | identifier_name |
neurosky_ecg.py | """
if sys.maxsize > (2**32)/2-1: #running 64 bit
print "loading Neurosky tg_ecg library, 64 bit"
libname = 'TgEcgAlg64.dll'
else:
print "loading Neurosky tg_ecg library, 32 bit"
#libname = 'TgEcgAlg.dll'
libname = 'tg_ecg.so'
print "... | plt.axes(ax2)
ymin = float(min(hrv))-10
ymax = float(max(hrv))+10
ax2.set_ylim((ymin,ymax))
hrvtrace.set_xdata(hrv_t)
hrvtrace.set_ydata(hrv)
ax2.relim()
ax2.autoscale_view() | conditional_block | |
cloud4.py |
if batchnorm:
self.bn = nn.BatchNorm1d(hiddendim, track_running_stats = True)
self.fc2 = nn.Linear(hiddendim, inputdim)
def forward(self, x):
z = self.bn(self.fc1(x)) if self.batchnorm else self.fc1(x)
z = functional.relu(z)
z = self.fc2(z)
return z + x, z
class OneRepResNet(nn.Module):
def __init__... | g, h = (c - a) / (b - d), (f - e) / (b - d)
if nblocks < 10 : # point cloud
x = np.linspace(- 20, 10, 100)
y = g * x + h
fig, ax = plt.subplots(3, 3, sharex = 'all', sharey = 'all')
fig.set_size_inches(18, 18)
fig.suptitle('Transformed test data after epoch {}. Linear classifier slope {} intercept {}'.forma... |
def plotmetrics(outs_, X_test, Y_test, gouts_, epoch, model, nblocks, folder):
F, C, W = [], [], []
a, b, c, d = model.fcOut.weight[0, 0].item(), model.fcOut.weight[0, 1].item(), model.fcOut.weight[1, 0].item(), model.fcOut.weight[1, 1].item()
e, f = model.fcOut.bias[0].item(), model.fcOut.bias[1].item() | random_line_split |
cloud4.py |
def forward(self, x):
z = self.bn(self.fc1(x)) if self.batchnorm else self.fc1(x)
z = functional.relu(z)
z = self.fc2(z)
return z + x, z
class OneRepResNet(nn.Module):
def __init__(self, nblocks, inputdim, hiddendim, batchnorm, nclasses, learnclassifier, yintercept, initialize):
super(OneRepResNet, self).... | super(ResBlock, self).__init__()
self.batchnorm = batchnorm
self.fc1 = nn.Linear(inputdim, hiddendim)
if batchnorm:
self.bn = nn.BatchNorm1d(hiddendim, track_running_stats = True)
self.fc2 = nn.Linear(hiddendim, inputdim) | identifier_body | |
cloud4.py | (ndata, testsize, data, noise, factor, dataseed, modelseed, nblocks, datadim, hiddendim, batchnorm, nclasses, learnclassifier,
yintercept, biginit, biginitstd, lambdatransport, lambdaloss0, tau, uzawasteps, batchsize, nepochs, learningrate, beta1, beta2):
folder0 = ('circles' if data == 1 else 'moons') + '-dd' ... | makefolder | identifier_name | |
cloud4.py | _test, Y_test, epoch, nblocks, folder)
print('[epoch %d] lambda loss: %.3f train loss: %.3f train accuracy: %.3f test accuracy: %.3f' % (epoch, lambdaloss, epochloss, epochacc, acc))
losses.append(epochloss)
train_accuracy.append(epochacc)
test_accuracy.append(acc)
if epoch > 3 and test_accuracy[-1] == test_a... | torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.manual_seed(modelseed)
np.random.seed(modelseed) | conditional_block | |
BAAFNet.py | t.name for t in e.op.inputs])
print([t.name for t in e.op.outputs])
a = 1 / 0
print('finished')
self.sess.close()
def evaluate(self, dataset):
# Initialise iterator with validation data
self.sess.run(dataset.val_init_op)
gt_classes = [0 fo... | nearest_interpolation | identifier_name | |
BAAFNet.py | .op)
print(e.op.name)
print([t.name for t in e.op.inputs])
print([t.name for t in e.op.outputs])
a = 1 / 0
print('finished')
self.sess.close()
def evaluate(self, dataset):
# Initialise iterator with validation data
s... | """
:param feature: [B, N, d] input features matrix
:param pool_idx: [B, N', max_num] N' < N, N' is the selected position after pooling
:return: pool_features = [B, N', d] pooled features matrix
"""
feature = tf.squeeze(feature, axis=2)
num_neigh = tf.shape(pool_idx)[-1]
... | identifier_body | |
BAAFNet.py | )
f_weights_decoders.append(curr_weight)
# regress the fusion parameters
f_weights = tf.concat(f_weights_decoders, axis=-1)
f_weights = tf.nn.softmax(f_weights, axis=-1)
# adptively fuse them by calculating a weighted sum
f_decoder_final = tf.zeros_like(f_multi_decode... | neigh_xyz_offsets = helper_tf_util.conv2d(feat_info, xyz.get_shape()[-1].value, [1, 1], name + 'mlp5', [1, 1], 'VALID', True, is_training) # B, N, k, 3
shifted_neigh_xyz = neigh_xyz + neigh_xyz_offsets # B, N, k, 3
xyz_info = tf.concat([neigh_xyz - tile_xyz, shifted_neigh_xyz, tile_xyz],... | random_line_split | |
BAAFNet.py |
else:
return tf.gather_nd(pts, idx), tf.gather_nd(feature, idx)
class Network:
def __init__(self, dataset, config):
flat_inputs = dataset.flat_inputs
self.config = config
# Path of the result folder
if self.config.saving:
if self.config.saving_path is None:... | return tf.gather_nd(pts, idx) | conditional_block | |
mod.rs | /html/rfc7230#section-2.6).
fn parse_request_version<T>(it: &mut StreamReader<T>) -> Result<(u8, u8), ParseError>
where T: Read {
let expected_it = "HTTP/".bytes();
for expected in expected_it {
match it.next() {
Some(b) if b == expected => (),
S... | aders(&self | identifier_name | |
mod.rs | , &mut it)?;
// Sanity checks
Request::parse_body(&mut builder, &mut it)?;
Ok(builder.into_request().unwrap())
}
/// Parse the request line, which is the first line of the request
///
/// It should have the form `Method Target HTTP/Version`, as defined in
/// [R... | match it.get_inner().read_to_end(builder.get_body()) {
Ok(0) => Ok(()),
Ok(_) => {
println!("Body read complete");
Ok(())
},
Err(e) => Err(ParseError::new_server | random_line_split | |
listing.go | "`
SubPrefixInclude []string `env:"key=SUB_PREFIX_INCLUDE decode=yaml"`
// private (non-exported) vars for processing only; e.g. lookup maps
subPrefixExcludeLookup map[string]bool
subPrefixIncludeLookup map[string]bool
}
var cfg *config
// Don't take seriously, just playing around with func objects and redire... | {
log.Printf("Retrieving object listing for %v/%v using service: %+v", bucket, prefix, svc.ClientInfo.Endpoint)
params := &s3.ListObjectsInput{
Bucket: aws.String(bucket), // Required
MaxKeys: aws.Int64(int64(cfg.MaxKeys)),
}
if delimiter != "" {
params.Delimiter = aws.String(delimiter)
}
if prefix != "... | identifier_body | |
listing.go | "`
OutputFormat string `env:"key=OUTPUT_FORMAT default=csv"`
OutputLocation string `env:"key=OUTPUT_LOCATION default=./target"`
ListAllWorkersCount int `env:"key=LIST_ALL_WORKERS_COUNT default=5"`
SubPrefixExclude []string `env:"key=SUB_PREFIX_EXCLUDE decode=yaml"`
SubPrefixInclude []str... | params := &s3.ListObjectsInput{
Bucket: aws.String(bucket), // Required
MaxKeys: aws.Int64(int64(cfg.MaxKeys)), | random_line_split | |
listing.go | Keys int `env:"key=FILE_MAX_KEYS default=1000"`
Force bool `env:"key=FORCE default=false"`
Region string `env:"key=AWS_REGION required=true"`
Bucket string `env:"key=AWS_BUCKET required=true"`
Prefix string `env:"key=AWS_PREFIX required=tru... |
go func() {
ListAllObjectsProducer(listAllObjectsQueue)
close(listAllObjectsQueue)
}()
wg.Wait()
}
func ListAllObjectsProducer(listAllObjectsQueue chan ListAllObjectsRequest) {
log.Println("Starting producer")
// Create services we will use, inlining the config instead of using `session`
// V4 signing req... | {
log.Printf("Starting worker%d", i+1)
worker := NewListObjectRequestWorker(i+1, listAllObjectsQueue, doneCallback)
wg.Add(1)
go func() {
// wg.Add(1)
worker.Start()
}()
} | conditional_block |
listing.go | Keys int `env:"key=FILE_MAX_KEYS default=1000"`
Force bool `env:"key=FORCE default=false"`
Region string `env:"key=AWS_REGION required=true"`
Bucket string `env:"key=AWS_BUCKET required=true"`
Prefix string `env:"key=AWS_PREFIX required=tru... | () {
output = stdoutOutput
listAllObjectsQueue := make(chan ListAllObjectsRequest, 5)
var wg sync.WaitGroup
doneCallback := func() {
defer wg.Done()
log.Printf("worker done")
}
for i := 0; i < cfg.ListAllWorkersCount; i++ {
log.Printf("Starting worker%d", i+1)
worker := NewListObjectRequestWorker(i+1, ... | run | identifier_name |
spacing.rs | Field ( .. ) |
ast::ExprKind::MethodCall(.. )=>rewrite_chain(self, context, width, offset)
};
let f: fn ( & _ , _ ) -> _ = unimplemented ! () ;
let f = unimplemented ! {} ;
{
foo ( ) ;
}
for & (sample, radiance) in samples.iter() {}
m... |
pub fn capacity( & self ) -> usize {
self . buf . cap ( )
}
pub fn reserve(& mut self, additional: usize) {
self. buf .reserve(self. len ,additional) ;
}
pub fn into_boxed_slice( mut self ) -> Box < [ T ] > {
unsafe{
self . shrink_to_fit ( ... | {
Vec{
buf :RawVec::from_raw_parts(ptr, capacity) ,
len :length ,
}
} | identifier_body |
spacing.rs | Field ( .. ) |
ast::ExprKind::MethodCall(.. )=>rewrite_chain(self, context, width, offset)
};
let f: fn ( & _ , _ ) -> _ = unimplemented ! () ;
let f = unimplemented ! {} ;
{
foo ( ) ;
}
for & (sample, radiance) in samples.iter() {}
m... | <R>(&mut self,range:R)->Drain<T>where R:RangeArgument <usize>{
let len = self.len();
let start = * range.start() .unwrap_or( & 0 ) ;
let end = * range. end().unwrap_or( & len ) ;
assert!(start <= end);
assert!(end <= len);
}
}
impl<T:Clone>Vec<T>{
pub ... | drain | identifier_name |
spacing.rs | :: Field ( .. ) |
ast::ExprKind::MethodCall(.. )=>rewrite_chain(self, context, width, offset)
};
let f: fn ( & _ , _ ) -> _ = unimplemented ! () ;
let f = unimplemented ! {} ;
{
foo ( ) ;
}
for & (sample, radiance) in samples.iter() {}
... | }
}
pub fn capacity( & self ) -> usize {
self . buf . cap ( )
}
pub fn reserve(& mut self, additional: usize) {
self. buf .reserve(self. len ,additional) ;
}
pub fn into_boxed_slice( mut self ) -> Box < [ T ] > {
unsafe{
self . s... | random_line_split | |
spacing.rs | :: Field ( .. ) |
ast::ExprKind::MethodCall(.. )=>rewrite_chain(self, context, width, offset)
};
let f: fn ( & _ , _ ) -> _ = unimplemented ! () ;
let f = unimplemented ! {} ;
{
foo ( ) ;
}
for & (sample, radiance) in samples.iter() {}
... |
r+=1 ;
}
self.truncate(w);
}
}
}
pub fn from_elem < T : Clone > ( elem :T ,n:usize) -> Vec <T>{
}
impl < T :Clone >Clone for Vec <T>{
fn clone(&self) -> Vec<T> {
< [ T ] > :: to_vec ( & * * self )
}
... | {
if r!=w{
let p_w = p_wm1.offset(1);
mem::swap( & mut * p_r , & mut * p_w );
}
w += 1;
} | conditional_block |
SFRF_backend.py | )
return True
except:
inter.pop_up("ERROR", "Consulta Inválida")
return False
def retorna_data_sem_hora(data_str):
split1 = data_str.split(" ")
return split1[0]
def retorna_dia(data_str):
split1 = data_str.split(" ")
split2 = split1[0]
data = split2.split("/")
return data[2]
def retorna_hora(data_str):
... |
cell_mes_str.font, cell_ano_str.font, cell_ano.font = font_normal, font_normal, font_normal
cell_mes_str.alignment, cell_ano_str.alignment = alignment_left, alignment_right | random_line_split | |
SFRF_backend.py | "Cadastro Inválido")
else:
inter.pop_up("ERROR", "Cadastro Inválido")
return False
def retorna_lista_colab(setor):
cursor = con.cursor
if setor == 'Não Ativos':
cursor.execute("SELECT Nome FROM Colaborador WHERE Status='Não Ativo'")
else:
cursor.execute("SELECT Nome FROM Colaborador WHERE Setor = '%s' and ... | ipo=='d':
dias = ["01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20"
,"21","22","23","24","25","26","27","28","29","30","31"]
for dia in dias:
data_com_dia = date+"/"+ dia
linha = dia+" de "+mes+" de "+ano
if setor != "Não Ativos":
c... | unter = timedelta()
cursor.execute("SELECT entrada, saida FROM Frequencia WHERE entrada LIKE ? and cpf = ? and saida IS NOT NULL",((date+'%', colab[0])))
for frequencia in cursor.fetchall():
entrada = retorna_objeto_date(frequencia[0])
saida = retorna_objeto_date(frequencia[1])
counter += (s... | conditional_block |
SFRF_backend.py | [0].split("/")
hora = data_hora[1].split(":")
date = datetime(int(data[0]),int(data[1]),int(data[2]), int(hora[0]),int(hora[1]),int(hora[2]))
return date
class ImageMethods():
# Abre uma caixa de diálogo para o usuário informar o caminho da imagem
@staticmethod
def get_path(line_path):
tk_dialog = Tk()
tk_di... | except:
inter.pop_up("ERROR", "Consulta Inválida")
return False
def retorna_data_sem_hora(data_str):
split1 = data_str.split | identifier_body | |
SFRF_backend.py | ogo):
cursor = con.cursor
conexao = con.conexao
if nome.get() != "" and sigla.get()!="":
try:
if logo.get() != "":
file_type = ImageMethods.get_file_type(logo.get())
file_binary = ImageMethods.get_binary(logo.get())
cursor.execute("INSERT INTO Setor VALUES (?, ?, ?, ?)", (nome.get(), sigla.get(), fi... | (nome, sigla, l | identifier_name | |
xcode.rs | fn from_project_info(pi: &XcodeProjectInfo) -> Result<Option<InfoPlist>> {
if_chain! {
if let Some(config) = pi.get_configuration("release")
.or_else(|| pi.get_configuration("debug"));
if let Some(target) = pi.get_first_target();
then {
let v... | {
show_notification("Sentry", &format!("{} finished", self.task_name))?;
} | conditional_block | |
xcode.rs | ),
})
}
/// Loads an info plist from provided environment variables list
pub fn from_env_vars(vars: &HashMap<String, String>) -> Result<InfoPlist> {
let name = vars
.get("PRODUCT_NAME")
.map(String::to_owned)
.ok_or_else(|| format_err!("PRODUCT_NAME is mi... | {
let mut vars = HashMap::new();
vars.insert("FOO_BAR".to_string(), "foo bar baz / blah".to_string());
assert_eq!(
expand_xcodevars("A$(FOO_BAR:rfc1034identifier)B", &vars),
"Afoo-bar-baz-blahB"
);
assert_eq!(
expand_xcodevars("A$(FOO_BAR:identifier)B", &vars),
"Afoo... | identifier_body | |
xcode.rs | => {
rv.project.path = path.as_ref().canonicalize()?;
Ok(rv.project)
}
Err(e) => {
warn!("Your .xcodeproj might be malformed. Command `xcodebuild -list -json -project {}` failed to produce a valid JSON output.", path.as_ref().display());
... | MayDetach | identifier_name | |
xcode.rs | : AsRef<Path>>(
path: P,
vars: &HashMap<String, String>,
) -> Result<InfoPlist> {
// do we want to preprocess the plist file?
let plist = if vars.get("INFOPLIST_PREPROCESS").map(String::as_str) == Some("YES") {
let mut c = process::Command::new("cc");
c.arg("-... | random_line_split | ||
elf.rs | , format_err, Error, Fail, ResultExt};
use goblin::elf::{
header::{EM_BPF, ET_REL},
section_header::{SectionHeader, SHT_PROGBITS, SHT_REL},
sym::{Sym, STB_GLOBAL},
};
use ebpf_core::{
ffi, prog, Attach, Insn, Map, Object, Opcode, Program, Type, BPF_LICENSE_SEC, BPF_MAPS_SEC,
BPF_VERSION_SEC, BTF_EL... | buf.get(sec.file_range()).ok_or_else(|| {
format_err!(
"`{}` section data {:?} out of bound",
name,
sec.file_range()
)
})
};
match name {
... | {
if self.obj.header.e_type != ET_REL || self.obj.header.e_machine != EM_BPF {
bail!("not an eBPF object file");
}
if self.obj.header.endianness()? != scroll::NATIVE {
bail!("endianness mismatch.")
}
let mut license = None;
let mut version = None... | identifier_body |
elf.rs | , format_err, Error, Fail, ResultExt};
use goblin::elf::{
header::{EM_BPF, ET_REL},
section_header::{SectionHeader, SHT_PROGBITS, SHT_REL},
sym::{Sym, STB_GLOBAL},
};
use ebpf_core::{
ffi, prog, Attach, Insn, Map, Object, Opcode, Program, Type, BPF_LICENSE_SEC, BPF_MAPS_SEC,
BPF_VERSION_SEC, BTF_EL... | (
&self,
programs: &mut [Program],
maps: &[Map],
maps_idx: Option<usize>,
text_idx: Option<usize>,
) -> Result<(), Error> {
for (idx, sec) in &self.obj.shdr_relocs {
if let Some(prog) = programs.iter_mut().find(|prog| prog.idx == *idx) {
tr... | relocate_programs | identifier_name |
elf.rs | , format_err, Error, Fail, ResultExt};
use goblin::elf::{
header::{EM_BPF, ET_REL},
section_header::{SectionHeader, SHT_PROGBITS, SHT_REL},
sym::{Sym, STB_GLOBAL},
};
use ebpf_core::{
ffi, prog, Attach, Insn, Map, Object, Opcode, Program, Type, BPF_LICENSE_SEC, BPF_MAPS_SEC,
BPF_VERSION_SEC, BTF_EL... | debug!(
"{:?} kernel program #{} @ section `{}` with {} insns",
ty,
idx,
name,
insns.len()
);
programs.push((name, ty, attach, idx, insns.t... | random_line_split | |
elf.rs | , format_err, Error, Fail, ResultExt};
use goblin::elf::{
header::{EM_BPF, ET_REL},
section_header::{SectionHeader, SHT_PROGBITS, SHT_REL},
sym::{Sym, STB_GLOBAL},
};
use ebpf_core::{
ffi, prog, Attach, Insn, Map, Object, Opcode, Program, Type, BPF_LICENSE_SEC, BPF_MAPS_SEC,
BPF_VERSION_SEC, BTF_EL... |
BPF_VERSION_SEC if sec.sh_type == SHT_PROGBITS => {
version = Some(u32::from_ne_bytes(section_data()?.try_into()?));
debug!("kernel version: {:x}", version.as_ref().unwrap());
}
BPF_MAPS_SEC => {
debug!("`{}` s... | {
license = Some(
CStr::from_bytes_with_nul(section_data()?)?
.to_str()?
.to_owned(),
);
debug!("kernel license: {}", license.as_ref().unwrap());
} | conditional_block |
disk.go | irGroup, ok := new(bbssig.Group).Unmarshal(cont.TheirGroup)
if !ok {
return errors.New("client: failed to unmarshal their group")
}
if contact.myGroupKey, ok = new(bbssig.MemberKey).Unmarshal(theirGroup, cont.MyGroupKey); !ok {
return errors.New("client: failed to unmarshal my group key")
}
if cont.The... | var drafts []*disk.Draft
for _, draft := range c.drafts { | random_line_split | |
disk.go | ig.PrivateKey).Unmarshal(group, state.GroupPrivate)
if !ok {
return errors.New("client: failed to unmarshal group private key")
}
if len(state.Private) != len(c.priv) {
return errors.New("client: failed to unmarshal private key")
}
copy(c.priv[:], state.Private)
if len(state.Public) != len(c.pub) {
return ... | () []byte {
var err error
var contacts []*disk.Contact
for _, contact := range c.contacts {
cont := &disk.Contact{
Id: proto.Uint64(contact.id),
Name: proto.String(contact.name),
GroupKey: contact.groupKey.Marshal(),
IsPending: proto.Bool(contact.isPending),
... | marshal | identifier_name |
disk.go | }
copy(c.priv[:], state.Private)
if len(state.Public) != len(c.pub) {
return errors.New("client: failed to unmarshal public key")
}
copy(c.pub[:], state.Public)
c.generation = *state.Generation
if state.LastErasureStorageTime != nil {
c.lastErasureStorageTime = time.Unix(*state.LastErasureStorageTime, 0)
}... | {
c.server = *state.Server
if len(state.Identity) != len(c.identity) {
return errors.New("client: identity is wrong length in State")
}
copy(c.identity[:], state.Identity)
curve25519.ScalarBaseMult(&c.identityPublic, &c.identity)
group, ok := new(bbssig.Group).Unmarshal(state.Group)
if !ok {
return errors.... | identifier_body | |
disk.go | ix(*prevGroupPriv.Expired, 0),
})
}
for _, cont := range state.Contacts {
contact := &Contact{
id: *cont.Id,
name: *cont.Name,
kxsBytes: cont.KeyExchangeBytes,
pandaKeyExchange: cont.PandaKeyExchange,
pandaResult: cont.GetPandaError(),
revokedUs: co... | {
if m.Message, err = proto.Marshal(msg.message); err != nil {
panic(err)
}
} | conditional_block | |
appstate.go | big.NewInt(0)}
acc.Amount.SetString(amount, 0)
return &acc, nil
}
// UpdateAccountCache update account in memory
func (as *AccountState) UpdateAccountCache(acc *Account) {
as.RLock()
defer as.RUnlock()
as.accounts[acc.Address] = acc
as.isDirty = true
}
//SyncToDisk cache to disk
func (as *AccountState) SyncToD... | () error {
sqlStr := "select content from state where id=1"
var text string
err := hdSt.db.QueryRowx(sqlStr).Scan(&text)
if err == sql.ErrNoRows {
return nil
}
if err != nil {
return err
}
return json.Unmarshal([]byte(text), hdSt)
}
// SyncToDisk to db
func (hdSt *HeaderState) SyncToDisk() error {
dat, er... | LoadHeaderState | identifier_name |
appstate.go | big.NewInt(0)}
acc.Amount.SetString(amount, 0)
return &acc, nil
}
// UpdateAccountCache update account in memory
func (as *AccountState) UpdateAccountCache(acc *Account) {
as.RLock()
defer as.RUnlock()
as.accounts[acc.Address] = acc
as.isDirty = true
}
//SyncToDisk cache to disk
func (as *AccountState) SyncToD... |
sqlStr := "replace into funds(address, amount) values "
for _, val := range as.accounts {
sqlStr = sqlStr + fmt.Sprintf(" ('%s', '%s'),", val.Address, val.Amount.String())
}
sqlStr = sqlStr[0 : len(sqlStr)-1]
_, err := as.db.Exec(sqlStr)
as.accounts = make(map[string]*Account)
return err
}
//Account ...
typ... | {
return nil
} | conditional_block |
appstate.go | big.NewInt(0)}
acc.Amount.SetString(amount, 0)
return &acc, nil
}
// UpdateAccountCache update account in memory
func (as *AccountState) UpdateAccountCache(acc *Account) {
as.RLock()
defer as.RUnlock()
as.accounts[acc.Address] = acc
as.isDirty = true
}
//SyncToDisk cache to disk
func (as *AccountState) SyncToD... |
// UpdateTx append tx
func (txState *TxState) UpdateTx(tx *Transaction) {
txState.Lock()
defer txState.Unlock()
txState.log.Error("one tx has been executed.......")
txState.Txs = txState.Txs.AppendTx(tx)
}
// SyncToDisk write tx to db
func (txState *TxState) SyncToDisk(height int64) (hashRoot string, err error) ... | {
return &TxState{
Txs: Transactions{},
log: log,
db: db,
}
} | identifier_body |
appstate.go | // AccountState means current account's info
type AccountState struct {
sync.RWMutex
accounts map[string]*Account
log log.Logger
db *sqlx.DB
isDirty bool
}
// NewAccountState return AccountState inst
func NewAccountState(db *sqlx.DB, log log.Logger) *AccountState {
return &AccountState{
accounts: m... | random_line_split | ||
list.rs | `], [`BoxColumn`]) parameterise
/// `W = Box<dyn Widget>`, thus supporting individually boxed child widgets.
/// This allows use of multiple types of child widget at the cost of extra
/// allocation, and requires dynamic dispatch of methods.
///
/// Configuring and resizing elements is O(n) in the number of children.
/... |
Some(self.id())
}
fn draw(&self, draw_handle: &mut dyn DrawHandle, mgr: &event::ManagerState, disabled: bool) {
let disabled = disabled || self.is_disabled();
let solver = layout::RowPositionSolver::new(self.direction);
solver.for_children(&self.widgets, draw_handle.get_clip_r... | {
return child.find_id(coord);
} | conditional_block |
list.rs | Row`], [`BoxColumn`]) parameterise
/// `W = Box<dyn Widget>`, thus supporting individually boxed child widgets.
/// This allows use of multiple types of child widget at the cost of extra
/// allocation, and requires dynamic dispatch of methods.
///
/// Configuring and resizing elements is O(n) in the number of children... | (&mut self, index: usize) -> Option<&mut dyn WidgetConfig> {
self.widgets.get_mut(index).map(|w| w.as_widget_mut())
}
}
impl<D: Directional, W: Widget> Layout for List<D, W> {
fn size_rules(&mut self, size_handle: &mut dyn SizeHandle, axis: AxisInfo) -> SizeRules {
let dim = (self.direction, se... | get_child_mut | identifier_name |
list.rs | } else {
match reverse {
false => Some(0),
true => Some(last),
}
}
}
fn find_id(&self, coord: Coord) -> Option<WidgetId> {
if !self.rect().contains(coord) {
return None;
}
let solver = layout::RowPositionSolve... | impl<'a, W: Widget> Iterator for ListIter<'a, W> {
type Item = &'a W;
fn next(&mut self) -> Option<Self::Item> {
if !self.list.is_empty() {
let item = &self.list[0]; | random_line_split | |
list.rs | `], [`BoxColumn`]) parameterise
/// `W = Box<dyn Widget>`, thus supporting individually boxed child widgets.
/// This allows use of multiple types of child widget at the cost of extra
/// allocation, and requires dynamic dispatch of methods.
///
/// Configuring and resizing elements is O(n) in the number of children.
/... |
/// Reserves capacity for at least `additional` more elements to be inserted
/// into the list. See documentation of [`Vec::reserve`].
pub fn reserve(&mut self, additional: usize) {
self.widgets.reserve(additional);
}
/// Remove all child widgets
///
/// Triggers a [reconfigure ac... | {
self.widgets.capacity()
} | identifier_body |
config_global.go | ClientName string `yaml:"well_known_client_name"`
// The server name to delegate sliding sync communications to, with optional port.
// Requires `well_known_client_name` to also be configured.
WellKnownSlidingSyncProxy string `yaml:"well_known_sliding_sync_proxy"`
// Disables federation. Dendrite will not be able... | (configErrs *ConfigErrors) {
}
// ServerNotices defines the configuration used for sending server notices
type ServerNotices struct {
Enabled bool `yaml:"enabled"`
// The localpart to be used when sending notices
LocalPart string `yaml:"local_part"`
// The displayname to be used when sending notices
DisplayName s... | Verify | identifier_name |
config_global.go | s()
c.Cache.Defaults()
}
func (c *Global) Verify(configErrs *ConfigErrors) {
checkNotEmpty(configErrs, "global.server_name", string(c.ServerName))
checkNotEmpty(configErrs, "global.private_key", string(c.PrivateKeyPath))
for _, v := range c.VirtualHosts {
v.Verify(configErrs)
}
c.JetStream.Verify(configErrs)... | func (c *DatabaseOptions) Verify(configErrs *ConfigErrors) {}
| random_line_split | |
config_global.go | server will trust as identity servers to
// verify third-party identifiers.
// Defaults to an empty array.
TrustedIDServers []string `yaml:"trusted_third_party_id_servers"`
// JetStream configuration
JetStream JetStream `yaml:"jetstream"`
// Metrics configuration
Metrics Metrics `yaml:"metrics"`
// Sentry c... | {
c.Endpoint = "https://panopticon.matrix.org/push"
} | conditional_block | |
config_global.go | ClientName string `yaml:"well_known_client_name"`
// The server name to delegate sliding sync communications to, with optional port.
// Requires `well_known_client_name` to also be configured.
WellKnownSlidingSyncProxy string `yaml:"well_known_sliding_sync_proxy"`
// Disables federation. Dendrite will not be able... |
func (c *Global) SplitLocalID(sigil byte, id string) (string, spec.ServerName, error) {
u, s, err := gomatrixserverlib.SplitID(sigil, id)
if err != nil {
return u, s, err
}
if !c.IsLocalServerName(s) {
return u, s, fmt.Errorf("server name %q not known", s)
}
return u, s, nil
}
func (c *Global) VirtualHost(... | {
if c.ServerName == serverName {
return true
}
for _, v := range c.VirtualHosts {
if v.ServerName == serverName {
return true
}
}
return false
} | identifier_body |
lib.rs | /// `1.0` is mapped to `100%`. Must be at most [`crate::RESOURCE_HARD_LIMIT`]. Setting this to
/// over `1.0` could stall the chain.
#[pallet::storage]
pub(crate) type Compute<T: Config> = StorageValue<_, FixedU64, ValueQuery>;
/// The proportion of the remaining `proof_size` to consume during `on_idle`.
///
//... | {
Err(())
} | conditional_block | |
lib.rs | pub const RESOURCE_HARD_LIMIT: FixedU64 = FixedU64::from_u32(10);
#[frame_support::pallet]
pub mod pallet {
use super::*;
#[pallet::config]
pub trait Config: frame_system::Config {
/// The overarching event type.
type RuntimeEvent: From<Event> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// The ... |
/// Set how much of the remaining `proof_size` weight should be consumed by `on_idle`.
///
/// `1.0` means that all remaining `proof_size` will be consumed. The PoV benchmarking
/// results that are used here are likely an over-estimation. 100% intended consumption will
/// therefore translate to less than ... | {
T::AdminOrigin::ensure_origin_or_root(origin)?;
ensure!(compute <= RESOURCE_HARD_LIMIT, Error::<T>::InsaneLimit);
Compute::<T>::set(compute);
Self::deposit_event(Event::ComputationLimitSet { compute });
Ok(())
} | identifier_body |
lib.rs | pub const RESOURCE_HARD_LIMIT: FixedU64 = FixedU64::from_u32(10);
#[frame_support::pallet]
pub mod pallet {
use super::*;
#[pallet::config]
pub trait Config: frame_system::Config {
/// The overarching event type.
type RuntimeEvent: From<Event> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// The ... | }
Self::deposit_event(Event::PalletInitialized { reinit: witness_count.is_some() });
TrashDataCount::<T>::set(new_count);
Ok(())
}
/// Set how much of the remaining `ref_time` weight should be consumed by `on_idle`.
///
/// Only callable by Root or `AdminOrigin`.
#[pallet::call_index(1)]
pub f... | (new_count..current_count).for_each(TrashData::<T>::remove); | random_line_split |
lib.rs | pub const RESOURCE_HARD_LIMIT: FixedU64 = FixedU64::from_u32(10);
#[frame_support::pallet]
pub mod pallet {
use super::*;
#[pallet::config]
pub trait Config: frame_system::Config {
/// The overarching event type.
type RuntimeEvent: From<Event> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// The ... | (origin: OriginFor<T>, storage: FixedU64) -> DispatchResult {
T::AdminOrigin::ensure_origin | set_storage | identifier_name |
house.go |
resp["errmsg"]=models.RecodeText(models.RECODE_OK)
defer this.RetData(resp)
//1.从用户请求中获取到图片数据
fileData,hd,err:=this.GetFile("house_image")
defer fileData.Close() //获取完后等程序执行完后关掉连接
//beego.Info("========",fileData,hd,err)
//没拿到图片
if fileData==nil{
resp["errno"]=models.RECODE_REQERR
resp["errmsg"]=models.Re... | resp["errno"]=models.RECODE_REQERR
resp["errmsg"]=models.RecodeText(models.RECODE_REQERR)
return
} | random_line_split | |
house.go | \n",reqData)
if &reqData==nil{
resp["errno"]=models.RECODE_REQERR
resp["errmsg"]=models.RecodeText(models.RECODE_REQERR)
return
}
//3.把房源数据插入到house结构体中
house:=models.House | le=reqData.Title
house.Price,_=strconv.Atoi(reqData.Price)
house.Price=house.Price*100
house.Address=reqData.Address
house.Room_count,_=strconv.Atoi(reqData.Room_count)
house.Acreage,_=strconv.Atoi(reqData.Acreage)
house.Unit=reqData.Unit
house.Beds=reqData.Beds
house.Capacity,_=strconv.Atoi(reqData.Capacity)
... | {}
house.Tit | identifier_name |
house.go | ecodeText(models.RECODE_OK)
defer this.RetData(resp)
//1.从session获取用户的user_id
user_id:=this.GetSession("user_id")
if user_id==nil{
resp["errno"]=models.RECODE_SESSIONERR
resp["errmsg"]=models.RecodeText(models.RECODE_SESSIONERR)
return
}
//2.从数据库中拿到user_id对应的house数据
//这里先拿到house结构体对象
/*
这里需要注意,因为我们需要查询的... | rno"]=models.RECODE_OK
resp["errmsg"]=models.R | identifier_body | |
house.go | �数组
}
//注意,只要house里有house_id后才能用QueryM2M,第一个参数是需要修改的哪个表,我这次要改house表,首先house表里一定要有一个house.Id,然后house.Id没有关联的设施信息,第二个参数为要修改的数据。
//这句的意思其实就是将房屋设施数据插放到house结构体中的Facilities字段所关联的表的字段中
//看下面Facility关联着House,rel(m2m)多对多关系。自然而然的就会将数据插入到关联表中。而这个关联表就是facility_houses
/*
type Facility struct {
Id int `json:"fid"` /... | ls.RecodeText(models.RECODE_DBERR)
return
}
//6.拼接完整域名url_fileid
respData:=make(map[string]string)
re | conditional_block | |
SearchEngine.py |
elif i%2 == 0:
if i > 2:
os.remove("temp2.json")
f = open("temp2.json", 'w')
f1 = open(files[i])
f2 = open(files[i+1])
line1 = f1.readline()
line2 = f2.readline()
while(line1 != "" or line2 != ""):
jsonObj1 = {"~~~": ""... | if i > 2:
os.remove("temp1.json")
f = open("temp1.json", 'w') | conditional_block | |
SearchEngine.py | line2 = f2.readline()
while(line1 != "" or line2 != ""):
jsonObj1 = {"~~~": ""} if line1 == "" else json.loads(line1) # highest ASCII val
jsonObj2 = {"~~~": ""} if line2 == "" else json.loads(line2) # highest ASCII val
key1, key2 = list(jsonObj1.keys())[0], list(jsonObj2.key... | for line in f:
fp_dict.update(json.loads(line)) # dict of the file pointers
with open("simhash_scores.json") as f:
for line in f:
simhash_scores.update(json.loads(line))
print(f"{len(fp_dict)} words in index")
f = open("tf_idf.json") # open our index
print | ps = PorterStemmer()
tokenizer = RegexpTokenizer(r"[a-zA-Z0-9']+")
# start prompt
start = input("Enter 'start'(s) to get started or 'quit'(q) to quit: \n")
start = start.lower()
while(start != "start" and start != "s"):
if start == 'q' or start == 'quit':
exit()
start = ... | identifier_body |
SearchEngine.py | ():
for file in os.listdir(os.getcwd()):
if re.match(r'^P\d\.json$', file):
os.remove(file)
try:
os.remove("temp1.json")
except:
pass
try:
os.remove("temp2.json")
except:
pass
def merge_partitions():
files = []
for file in os.listdir(os.ge... | delete_partitions | identifier_name | |
SearchEngine.py | line2 = f2.readline()
while(line1 != "" or line2 != ""):
jsonObj1 = {"~~~": ""} if line1 == "" else json.loads(line1) # highest ASCII val
jsonObj2 = {"~~~": ""} if line2 == "" else json.loads(line2) # highest ASCII val
key1, key2 = list(jsonObj1.keys())[0], list(jsonObj2.key... | json.dump({word:f2.tell()}, f3)
f3.write('\n')
json.dump(tf_idf, f2)
f2.write('\n')
f1.close()
f2.close()
f3.close()
# calculate simhash
f = open("simhash_scores.json", 'w')
for ID, hashed_words in simhash_dict.items():
simhash_score = ''
... | except KeyError:
simhash_dict[docID] = {sim_hashfn(word): score}
| random_line_split |
kelliptic.go | // fields.
//
// This package operates, internally, on Jacobian coordinates. For a given
// (x, y) position on the curve, the Jacobian coordinates are (x1, y1, z1)
// where x = x1/z1² and y = y1/z1³. The greatest speedups come when the whole
// calculation can be performed within the transform (as in ScalarMult and
// ... | // license that can be found in the LICENSE file.
// Package bitelliptic implements several Koblitz elliptic curves over prime | random_line_split | |
kelliptic.go | the first true bit in |k|. If we don't find any true bits in
// |k|, then we return nil, nil, because we cannot return the identity
// element.
Bz := new(big.Int).SetInt64(1)
x := Bx
y := By
z := Bz
seenFirstTrue := false
for _, byte := range k {
for bitNum := 0; bitNum < 8; bitNum++ {
if seenFirstTrue... | nito | identifier_name | |
kelliptic.go | cobian takes two points in Jacobian coordinates, (x1, y1, z1) and
// (x2, y2, z2) and returns their sum, also in Jacobian form.
func (curve *Curve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) {
// See http://hyperellipticurve.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
... | w(big.Int).SetInt64(1)
return curve.affineFromJacobian(curve.addJacobian(x1, y1, z, x2, y2, z))
}
// addJa | identifier_body | |
kelliptic.go | 26F2FC170F69466A74DEFD8D", 16)
secp192k1.B, _ = new(big.Int).SetString("000000000000000000000000000000000000000000000003", 16)
secp192k1.Gx, _ = new(big.Int).SetString("DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D", 16)
secp192k1.Gy, _ = new(big.Int).SetString("9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D", ... | c.Div(c, FOUR)
c.Exp(a, c, p)
return c
}
// Partition p-1 | conditional_block | |
xmlpipe2.py | .server, slave_okay=True)
try:
# busca la entidad principal
main_ntt_id = int(afile["se"]["_id"])
ntt = gconn.ontology.ontology.find_one({"_id":main_ntt_id})
ntts1_info = set()
ntts2_info = set()
... | if headers: self.generate_header() | random_line_split | |
xmlpipe2.py | iene entidades de primer nivel
ntts1_ids = [ntt_id for ntt_id, relation in ntts1_info]
ntts1 = list(gconn.ontology.ontology.find({"_id":{"$in":ntts1_ids}}))
# genera la lista de entidades y tipos de relacion de segundo nive... | FilesFetcher(server, entities_server, afilter, batch_size, stop_set, stop_set_len, last_count, self.processes)
ff.start()
if headers: self.generate_header()
count = error_count = 0
logging.warn("Comienza indexado en servidor %s."%server)
if self.pool:
for doc, extra ... | identifier_body | |
xmlpipe2.py | (self):
gconn = None
not_found_count = 0
with open("nf_ntts.csv", "w") as not_found_ntts:
while True:
# obtiene peticiones de buscar entidades
afile = self.requests.get(True)
if afile is None:
self.requests.task_done... | run | identifier_name | |
xmlpipe2.py | .requests.get(True)
if afile is None:
self.requests.task_done()
break
if not gconn:
gconn = pymongo.Connection(self.server, slave_okay=True)
try:
# busca la entidad principal
... | if "se" in f and f["se"]:
self.entities.requests.put(f)
else:
self.results.put(f)
self.entities.requests.put(None)
self.entities.requests.join()
# actualiza el nuevo stop set
if self.stop_set_len:
self.stop_set = new_sto... | dd_to_stop_set and self.stop_set:
new_stop_set.update(self.stop_set)
break
| conditional_block |
script.js | let next_b2 = {x: balls[b2].x + balls[b2].vx * time_delta_s,
y: balls[b2].y + balls[b2].vy * time_delta_s,
r: balls[b2].r};
if (overlap(next_b1, next_b2)){
//asignning deltaX and deltaY for the positions of the balls
... | fill_polygon | identifier_name | |
script.js | 2','#45fe3a','#4efd31','#58fc2a','#61f923','#6bf61c','#75f216'];
function fit_to_screen(){
cnvs.height = cnvs.width = innerHeight; //update to change dynamically
}
//initialising arrays
let balls = [];
let bollards = [];
//variables to be initialised by url params
let gravity;
let cor;
let collision... | balls[b].vy += gravity * time_delta_s;
}
}
function wall_collisions(){
for (let i = 0; i < balls.length; i++){
let ball = balls[i];
let nx = ball.x + ball.vx * time_delta_s;
let ny = ball.y + ball.vy * time_delta_s;
//set ball's position to over the wall so come... | function apply_gravity(){
for (let b = 0; b < balls.length; b++){
| random_line_split |
script.js | deltaX and deltaY for the positions of the balls
let deltaX = balls[b2].x - balls[b1].x;
let deltaY = balls[b2].y - balls[b1].y;
//initialising the current normal and tangental velocities to the collision for each ball
let normVel1 = normal_vel(del... | {
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++){
ctx.lineTo(points[i].x, points[i].y);
}
ctx.stroke();
ctx.fillStyle = color;
ctx.fill();
} | identifier_body | |
freelist.rs | 0 is returned.
pub fn allocate(&mut self, n: usize) -> pgid_t {
if self.ids.len() == 0 {
return 0;
}
let mut initial: pgid_t = 0;
let mut previd: pgid_t = 0;
let mut found_index: Option<usize> = None;
for i in 0..self.ids.len() {
let id = self... | else {
let pgid_ptr = &p.ptr as *const usize as *const pgid_t;
self.ids.reserve(count - idx);
let mut pgids_slice = unsafe {
slice::from_raw_parts(pgid_ptr.offset(idx as isize), count)
};
self.ids.append(&mut pgids_slice.to_vec());
... | {
self.ids.clear();
} | conditional_block |
freelist.rs | 0 is returned.
pub fn allocate(&mut self, n: usize) -> pgid_t {
if self.ids.len() == 0 {
return 0;
}
let mut initial: pgid_t = 0;
let mut previd: pgid_t = 0;
let mut found_index: Option<usize> = None;
for i in 0..self.ids.len() {
let id = self... | } else {
p.count = 0xFFFF;
let mut pgid_ptr = &mut p.ptr as *mut usize as *mut pgid_t;
unsafe {*pgid_ptr = lenids as u64;}
/*
let mut dst = unsafe {
Vec::from_raw_parts(pgid_ptr.offset(1), 0, lenids)
};
*/
... | {
// Combine the old free pgids and pgids waiting on an open transaction.
// Update the header flag.
p.flags |= FREELIST_PAGE_FLAG;
// The page.count can only hold up to 64k elementes so if we overflow that
// number then we handle it by putting the size in the first element.
... | identifier_body |
freelist.rs | let ids_option = self.pending.get_mut(&txid);
match ids_option {
None => panic!("pending should not be None"),
Some(ids) => {
for id in pgid..pgid + 1 + p.borrow().overflow as pgid_t {
// Verify that page is not already free.
if se... | freelist_read | identifier_name | |
freelist.rs | 0 is returned.
pub fn allocate(&mut self, n: usize) -> pgid_t {
if self.ids.len() == 0 {
return 0;
}
let mut initial: pgid_t = 0;
let mut previd: pgid_t = 0;
let mut found_index: Option<usize> = None;
for i in 0..self.ids.len() {
let id = self... | // writes the page ids onto a freelist page. All free and pending ids are
// saved to disk since in the event of a program crash, all pending ids will
// become free.
pub fn write(&self, p: &mut Page) {
// Combine the old free pgids and pgids waiting on an open transaction.
// Update th... | }
| random_line_split |
basic_agent.py | a copy, see <https://opensource.org/licenses/MIT>.
""" This module implements an agent that roams around a track following random
waypoints and avoiding other vehicles.
The agent also responds to traffic lights. """
import math
from typing import List
import carla
from carla.libcarla import ActorList, Actor
from ag... | self._target_speed = target_speed
self._grp = None
self.drawn_lights = False
self.is_affected_by_traffic_light = False
def set_destination(self, location):
"""
This method creates a list of waypoints from agent's position to destination location
based on the... | """
:param vehicle: actor to apply to local planner logic onto
"""
super(BasicAgent, self).__init__(vehicle)
self.stopping_for_traffic_light = False
self._proximity_threshold = 10.0 # meters
self._state = AgentState.NAVIGATING
args_lateral_dict = {
... | identifier_body |
basic_agent.py | a copy, see <https://opensource.org/licenses/MIT>.
""" This module implements an agent that roams around a track following random
waypoints and avoiding other vehicles.
The agent also responds to traffic lights. """
import math
from typing import List
import carla
from carla.libcarla import ActorList, Actor
from ag... |
self._state = AgentState.NAVIGATING
self.braking_intial_speed = None
# standard local planner behavior
control = self._local_planner.run_step(debug=debug)
if self.stopping_for_traffic_light:
control.steer = 0.0
# Prevent from steering randomly when stopped
... | random_line_split | |
basic_agent.py | a copy, see <https://opensource.org/licenses/MIT>.
""" This module implements an agent that roams around a track following random
waypoints and avoiding other vehicles.
The agent also responds to traffic lights. """
import math
from typing import List
import carla
from carla.libcarla import ActorList, Actor
from ag... |
if nearest_traffic_light is not None:
print("nearest_traffic_light: ", nearest_traffic_light.get_location() if nearest_traffic_light is not None else "None", " ", nearest_traffic_light.state if nearest_traffic_light is not None else "None")
"""
ego_vehicle_loca... | TRAFFIC_LIGHT_SECONDS_AWAY = 3
METERS_TO_STOP_BEFORE_TRAFFIC_LIGHT = 8
get_traffic_light = self._vehicle.get_traffic_light() # type: carla.TrafficLight
nearest_traffic_light, distance = get_nearest_traffic_light(self._vehicle) # type: carla.TrafficLight, float
distance_... | conditional_block |
basic_agent.py | copy, see <https://opensource.org/licenses/MIT>.
""" This module implements an agent that roams around a track following random
waypoints and avoiding other vehicles.
The agent also responds to traffic lights. """
import math
from typing import List
import carla
from carla.libcarla import ActorList, Actor
from agen... | (Agent):
"""
BasicAgent implements a basic agent that navigates scenes to reach a given
target destination. This agent respects traffic lights and other vehicles.
"""
def __init__(self, vehicle, target_speed=20):
"""
:param vehicle: actor to apply to local planner logic onto
... | BasicAgent | identifier_name |
APISchedFetch.js | /postgame) data
loading:true,
records:[],
mobileActive:'list' // keeps track of view state for mobile (list => display the list; gameView => display the game data)
};
this.sideBarClick = this.sideBarClick.bind(this);
this.refreshData = this.refreshData.bind(this);
this.handleDateChange... | } else {
this.setState({
loading:false,
liveGames: allGames[0],
scheduledGames:allGames[1],
finalGames:allGames[2],
gamesData:allGamesJSON,
gamesContentData:gamesContentData,
records:records
});
}
})
.catch(err =>... | gamesData:allGamesJSON,
gamesContentData:gamesContentData,
records:records
}); | random_line_split |
APISchedFetch.js | game) data
loading:true,
records:[],
mobileActive:'list' // keeps track of view state for mobile (list => display the list; gameView => display the game data)
};
this.sideBarClick = this.sideBarClick.bind(this);
this.refreshData = this.refreshData.bind(this);
this.handleDateChange = th... | () {
this.refreshData();
this._interval = window.setInterval(this.refreshData,10000); // set refresh interval to 5s
}
componentWillUnMount() {
this._interval && window.clearInterval(this._interval); // remove refresh interval when unmounted
}
sideBarClick(gameFID) {
this.setState({mainGamePk: ... | componentDidMount | identifier_name |
APISchedFetch.js | game) data
loading:true,
records:[],
mobileActive:'list' // keeps track of view state for mobile (list => display the list; gameView => display the game data)
};
this.sideBarClick = this.sideBarClick.bind(this);
this.refreshData = this.refreshData.bind(this);
this.handleDateChange = th... |
allGames = [liveGames,scheduledGames,finalGames,data];
allGamesJSON = allGamesJSON.concat(gameData);
})
);
// content data is available at a different endpoint and needs its own fetch
fetches.push(
fetch(apiContentString)
.then(contentRaw => {
ret... | {
finalGames = finalGames.concat(gameData);
} | conditional_block |
APISchedFetch.js | game) data
loading:true,
records:[],
mobileActive:'list' // keeps track of view state for mobile (list => display the list; gameView => display the game data)
};
this.sideBarClick = this.sideBarClick.bind(this);
this.refreshData = this.refreshData.bind(this);
this.handleDateChange = th... |
backButtonClick() {
this.setState({mobileActive:'list'}); // used for mobile to provide back button functionality
}
handleDateChange(date) {
this.setState({
date:date,
liveGames: [], // array of game data for live games
scheduledGames: [], // array of game data for scheduled gam... | {
this.setState({mainGamePk: gameFID, mobileActive:'gameView'}); // handles sidebar game click
} | identifier_body |
13.1.rs | [ ] ... [ ]
// [S] [S] [S] [S]
// [ ] [ ] [ ]
// [ ] [ ]
// Picosecond 2:
// 0 1 2 3 4 5 6
// [ ] [S] ... ... [ ] ... [ ]
// [ ] [ ] [ ] [ ]
// [S] [S] [S]
// [ ] [ ]
// Picosecond 3:
// 0 1 ... | get_scanners | identifier_name | |
13.1.rs | 3 4 5 6
// [ ] [ ] ... ... [ ] ... [ ]
// [S] [S] [S] [S]
// [ ] [ ] [ ]
// [ ] [ ]
// Picosecond 2:
// 0 1 2 3 4 5 6
// [ ] [S] ... ... [ ] ... [ ]
// [ ] [ ] [ ] [ ]
// [S] [S] [S]
// [ ] ... | // 0 1 2 3 4 5 6
// [ ] ( ) ... ... [ ] ... [ ]
// [S] [S] [S] [S]
// [ ] [ ] [ ]
// [ ] [ ]
// 0 1 2 3 4 5 6
// [ ] (S) ... ... [ ] ... [ ]
// [ ] [ ] [ ] [ ]
// [S] [S] [S]
// [ ] [ ]
... | // [ ] [ ]
// Picosecond 1:
| random_line_split |
13.1.rs | 3 4 5 6
// [ ] [ ] ... ... [ ] ... [ ]
// [S] [S] [S] [S]
// [ ] [ ] [ ]
// [ ] [ ]
// Picosecond 2:
// 0 1 2 3 4 5 6
// [ ] [S] ... ... [ ] ... [ ]
// [ ] [ ] [ ] [ ]
// [S] [S] [S]
// [ ] ... |
let mi = r - 1; /* max index of the scanner range */
let unique_positions = r * 2 - 2; /* how many different states the scanner can be in. Whenever the scanner is at an end, it can only be turning around. Whenever a scanner is in a middle position, it could be going back or forward*/
... | {
return Some(0);
} | conditional_block |
13.1.rs | [S] ... ... [S] ... [S]
// [ ] [ ] [ ] [ ]
// [ ] [ ] [ ]
// [ ] [ ]
// 0 1 2 3 4 5 6
// ( ) [ ] ... ... [ ] ... [ ]
// [S] [S] [S] [S]
// [ ] [ ] [ ]
// [ ] [ ]
// Picosecond 1:
// 0 1 2 3... | {
let mut d: i32 = 0;
while d <= scanners.max_depth {
let scanner_time = d + offset;
if scanners.collides(&d, &scanner_time) {
return true;
}
d += 1;
}
false
} | identifier_body | |
config.js | zoom: 4.5,
pitch: 60,
bearing: 0
},
onChapterEnter: [
{
layer: 'anchor port',
opacity: 1
}
],
onChapterExit: [
{
layer: ... |
location: {
center: [151.235148, -33.851759],
zoom: 4.5,
pitch: 60,
| random_line_split | |
cache.go | Err func(err error) bool
group singleflight.Group
hits uint64
misses uint64
localHits uint64
localMisses uint64
}
// UseLocalCache causes Codec to cache items in local LRU cache.
func (cd *Codec) UseLocalCache(maxLen int, expiration time.Duration) {
cd.localCache = lrucache.New(maxLen, expiration... | }
obj = d
}
if !item.doNotReturn {
m.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(obj))
}
items[i] = item
i++
}
return cd.Set(items...)
}
return nil
}
func (cd *Codec) mSetItems(items []*Item) error {
var pipeline redis.Pipeliner
if cd.Redis != nil {
pipeline = cd.Redis.Pipeli... | item = &Item{
Key: key,
Object: d,
Expiration: mItem.Expiration, | random_line_split |
cache.go | func(err error) bool
group singleflight.Group
hits uint64
misses uint64
localHits uint64
localMisses uint64
}
// UseLocalCache causes Codec to cache items in local LRU cache.
func (cd *Codec) UseLocalCache(maxLen int, expiration time.Duration) {
cd.localCache = lrucache.New(maxLen, expiration)
}... |
func (cd *Codec) setItem(item *Item) ([]byte, error) {
object, err := item.object()
if err != nil {
return nil, err
}
b, err := cd.Marshal(object)
if err != nil {
log.Printf("cache: Marshal key=%q failed: %s", item.Key, err)
return nil, err
}
if cd.localCache != nil {
cd.localCache.Set(item.Key, b)
... | {
if len(items) == 1 {
_, err := cd.setItem(items[0])
return err
} else if len(items) > 1 {
return cd.mSetItems(items)
}
return nil
} | identifier_body |
cache.go | func(err error) bool
group singleflight.Group
hits uint64
misses uint64
localHits uint64
localMisses uint64
}
// UseLocalCache causes Codec to cache items in local LRU cache.
func (cd *Codec) UseLocalCache(maxLen int, expiration time.Duration) {
cd.localCache = lrucache.New(maxLen, expiration)
}... |
elementType := mapType.Elem()
// non-pointer values not supported yet
if elementType.Kind() != reflect.Ptr {
return fmt.Errorf("dst value type must be a pointer, %v given", elementType.Kind())
}
// get the value that the pointer elementType points to.
elementType = elementType.Elem()
// allocate a new map, ... | {
return fmt.Errorf("dst key type must be a string, %v given", keyType.Kind())
} | conditional_block |
cache.go |
}
default:
return nil, fmt.Errorf("slice expected from the loader function, %s received", li.Kind())
}
if len(keysToLoad) != len(result) && batchArgs.CreateObjectForMissedKey != nil {
for _, k := range keysToLoad {
if _, exists := result[k]; !exists {
objToCache, returnInResult := batch... | ensureDefaultExp | identifier_name | |
lib.rs | pub struct XRefInfo {
//! #[pdf(key = "Filter")]
//! filter: Vec<StreamFilter>,
//! #[pdf(key = "Size")]
//! pub size: i32,
//! #[pdf(key = "Index", default = "vec![0, size]")]
//! pub index: Vec<i32>,
//! // [...]
//! }
//! ```
//!
//!
//! ## 2. Struct from PDF Stream
//! PDF Streams consi... | else {
match *value {
Lit::Str(ref value, _) => attrs.checks.push((String::from(ident.as_ref()), value.clone())),
_ => panic!("Other checks must have RHS String."),
}
... | {
match *value {
Lit::Str(ref value, _) => {
if value.ends_with("?") {
attrs.type_name = Some(value[.. value.len()-1].to_string());
... | conditional_block |
lib.rs | pub struct XRefInfo {
//! #[pdf(key = "Filter")]
//! filter: Vec<StreamFilter>,
//! #[pdf(key = "Size")]
//! pub size: i32,
//! #[pdf(key = "Index", default = "vec![0, size]")]
//! pub index: Vec<i32>,
//! // [...]
//! }
//! ```
//!
//!
//! ## 2. Struct from PDF Stream
//! PDF Streams consi... |
/// Accepts Name to construct enum
fn impl_object_for_enum(ast: &DeriveInput, variants: &Vec<Variant>) -> quote::Tokens {
let id = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let ser_code: Vec<_> = variants.iter().map(|var| {
quote! {
#id... | {
let attrs = GlobalAttrs::from_ast(&ast);
if attrs.is_stream {
match ast.body {
Body::Struct(ref data) => impl_object_for_stream(ast, data.fields()),
Body::Enum(_) => panic!("Enum can't be a PDF stream"),
}
} else {
match ast.body {
Body::Struct(r... | identifier_body |
lib.rs | pub struct XRefInfo {
//! #[pdf(key = "Filter")]
//! filter: Vec<StreamFilter>,
//! #[pdf(key = "Size")]
//! pub size: i32,
//! #[pdf(key = "Index", default = "vec![0, size]")]
//! pub index: Vec<i32>,
//! // [...]
//! }
//! ```
//!
//!
//! ## 2. Struct from PDF Stream
//! PDF Streams consi... | match ast.body {
Body::Struct(ref data) => impl_object_for_stream(ast, data.fields()),
Body::Enum(_) => panic!("Enum can't be a PDF stream"),
}
} else {
match ast.body {
Body::Struct(ref data) => impl_object_for_struct(ast, data.fields()),
Body... | random_line_split | |
lib.rs | pub struct XRefInfo {
//! #[pdf(key = "Filter")]
//! filter: Vec<StreamFilter>,
//! #[pdf(key = "Size")]
//! pub size: i32,
//! #[pdf(key = "Index", default = "vec![0, size]")]
//! pub index: Vec<i32>,
//! // [...]
//! }
//! ```
//!
//!
//! ## 2. Struct from PDF Stream
//! PDF Streams consi... | (ast: &DeriveInput, fields: &[Field]) -> quote::Tokens {
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let attrs = GlobalAttrs::from_ast(&ast);
let parts: Vec<_> = fields.iter()
.map(|field| {
let (key, default, skip) = field_attrs(fi... | impl_object_for_struct | identifier_name |
swarm_test.go | .ConnMultiaddrs) bool { return false }
return c
},
p1ConnectednessToP2: network.NotConnected,
p2ConnectednessToP1: network.NotConnected,
isP1OutboundErr: true,
// QUIC gates the connection after completion of the handshake
disableOnQUIC: true,
},
"p2 gates inbound peer dial before multiple... | {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
rcmgr1 := mocknetwork.NewMockResourceManager(ctrl)
s1 := GenSwarm(t, WithSwarmOpts(swarm.WithResourceManager(rcmgr1)))
defer s1.Close()
s2 := GenSwarm(t)
defer s2.Close()
connectSwarms(t, context.Background(), []*swarm.Swarm{s1, s2})
rerr := errors.New(... | identifier_body | |
swarm_test.go | Reuseport)
// connect everyone
connectSwarms(t, context.Background(), swarms)
// ping/pong
for _, s1 := range swarms {
log.Debugf("-------------------------------------------------------")
log.Debugf("%s ping pong round", s1.LocalPeer())
log.Debugf("-------------------------------------------------------")
... | if s2.LocalPeer() == s1.LocalPeer() {
continue // dont send to self...
}
wg.Add(1)
go send(s2.LocalPeer())
}
wg.Wait()
}()
// receive "pong" x MsgNum from every peer
go func() {
defer close(errChan)
count := 0
countShouldBe := MsgNum * (len(swarms) - 1)
for stream := range... | // read it later
streamChan <- stream
}
for _, s2 := range swarms { | random_line_split |
swarm_test.go | Reuseport)
// connect everyone
connectSwarms(t, context.Background(), swarms)
// ping/pong
for _, s1 := range swarms {
log.Debugf("-------------------------------------------------------")
log.Debugf("%s ping pong round", s1.LocalPeer())
log.Debugf("-------------------------------------------------------")
... |
wg.Add(1)
go send(s2.LocalPeer())
}
wg.Wait()
}()
// receive "pong" x MsgNum from every peer
go func() {
defer close(errChan)
count := 0
countShouldBe := MsgNum * (len(swarms) - 1)
for stream := range streamChan { // one per peer
// get peer on the other side
p := stream.Conn(... | {
continue // dont send to self...
} | conditional_block |
swarm_test.go | boundErr: true,
},
"p2 accepts inbound peer dial if outgoing dial is gated": {
p2Gater: func(c *MockConnectionGater) *MockConnectionGater {
c.Dial = func(peer.ID, ma.Multiaddr) bool { return false }
return c
},
p1ConnectednessToP2: network.Connected,
p2ConnectednessToP1: network.Connected,
... | TestResourceManagerNewStream | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.