file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
tax_task.py
#!/usr/bin/env python # encoding: utf-8 import os import time import argparse import sys sys.path.append('..') sys.path.append('.') import tensorflow as tf from sklearn.utils import shuffle from keras.callbacks import TensorBoard from keras.models import Model, load_model from keras.utils.vis_utils import plot_model...
(config): # model save path model_save_dir = os.path.join("../model/tax-task", model_name, time_str) if not os.path.exists(model_save_dir): os.makedirs(model_save_dir) # log save path log_save_dir = os.path.join("../logs/tax-task", model_name, time_str) if not os.path.exists(log_save_di...
train
identifier_name
tax_task.py
#!/usr/bin/env python # encoding: utf-8 import os import time import argparse import sys sys.path.append('..') sys.path.append('.') import tensorflow as tf from sklearn.utils import shuffle from keras.callbacks import TensorBoard from keras.models import Model, load_model from keras.utils.vis_utils import plot_model...
.replace(".h5", "_best.h5")) print("train done. best epoch: %d, best: f1: %f, model path: %s" % (best_epoch, best_f1, best_model)) file.write("train done. best epoch: %d, best: f1: %f, model path: %s\n" % (best_epoch, best_f1, best_model)) CallBack.on_train_end(None) file.close() # evaluate def model_...
ata_train) start_time = time.time() llprint("Epoch %d/%d\n" % (epoch + 1, config["epochs"])) losses = [] train_pred_output_prob = [] train_pred_output = [] train_real_output = [] file.write("Epoch: %d/%d\n" % ((epoch + 1), config["epochs"])) for patient_...
conditional_block
tax_task.py
#!/usr/bin/env python # encoding: utf-8 import os import time import argparse import sys sys.path.append('..') sys.path.append('.') import tensorflow as tf from sklearn.utils import shuffle from keras.callbacks import TensorBoard from keras.models import Model, load_model from keras.utils.vis_utils import plot_model...
CallBack = TensorBoard(log_dir=('../tb-logs/tax-task/%s/%s' %(model_name, time_str)), # log dir histogram_freq=0, write_graph=True, write_grads=True, write_images=True, embeddings_freq=0, ...
for name, value in zip(names, logs): summary = tf.Summary() summary_value = summary.value.add() summary_value.simple_value = value summary_value.tag = name callback.writer.add_summary(summary, epoch_no) callback.writer.flush()
identifier_body
tax_task.py
#!/usr/bin/env python # encoding: utf-8 import os import time import argparse import sys sys.path.append('..') sys.path.append('.') import tensorflow as tf from sklearn.utils import shuffle from keras.callbacks import TensorBoard from keras.models import Model, load_model from keras.utils.vis_utils import plot_model...
if __name__ == "__main__": print("#####################args#####################") print(args) config = { "datapath": args.datapath, "run_mode": args.run_mode, "debug": args.debug, "use_tensorboard": not args.no_tensorboard, "has_position_embed": not args.no_positio...
roc_auc = roc_auc_non_multi(eval_real_output, eval_pred_output_prob) prauc = prc_auc_non_multi(eval_real_output, eval_pred_output_prob) return acc, prec, recall, f1, prauc, roc_auc
random_line_split
nn.rs
//! Neural networks use crate::matrix::*; /// a network #[derive(Debug)] pub struct Network { // activation functions activations: Vec<Box<dyn Activation>>, // topology topology: Vec<usize>, // weights weights: Vec<Matrix> } impl Network { /// create a new random network with the given top...
/// back propagation pub fn backward(&mut self, inputs :&[f64], outputs :Vec<Vec<f64>>, target :&[f64], learning_rate: f64 ) { debug!("Error: {}", error(target, outputs.last().expect("outputs"))); let l = outputs.len(); let mut new_weights = self.weights.clone(); let mut new_ta...
{ assert_eq!(self.topology[0],inputs.len()); let mut m = Matrix::new(1,inputs.len(),inputs); let mut all_results = Vec::with_capacity(self.topology.len() - 1); self.weights.iter().enumerate().for_each(| (ix,wm) | { add_column(&mut m,vec!(1.0)); m = mul(&m,wm); ...
identifier_body
nn.rs
//! Neural networks use crate::matrix::*; /// a network #[derive(Debug)] pub struct Network { // activation functions activations: Vec<Box<dyn Activation>>, // topology topology: Vec<usize>, // weights weights: Vec<Matrix> } impl Network { /// create a new random network with the given top...
} } /// Softmax activation function #[derive(Debug)] pub struct Softmax{} impl Activation for Softmax { fn activate(&self, inputs: &[f64]) -> Vec<f64> { softmax(inputs) } fn derive(&self, outputs: &[f64], index: usize) -> f64 { let s: f64 = outputs.iter().sum(); let el = out...
{0.0}
conditional_block
nn.rs
//! Neural networks use crate::matrix::*; /// a network #[derive(Debug)] pub struct Network { // activation functions activations: Vec<Box<dyn Activation>>, // topology topology: Vec<usize>, // weights weights: Vec<Matrix> } impl Network { /// create a new random network with the given top...
inputs }; let previous_size = size(&weights).0; debug!("previous size: {}",previous_size); debug!("weights to update: {:?}",size(&weights)); new_targets.push(vec!(0.0; previous_size)); for (i,o) in outputs[rev_order]...
} else {
random_line_split
nn.rs
//! Neural networks use crate::matrix::*; /// a network #[derive(Debug)] pub struct Network { // activation functions activations: Vec<Box<dyn Activation>>, // topology topology: Vec<usize>, // weights weights: Vec<Matrix> } impl Network { /// create a new random network with the given top...
(&self, inputs :&[f64]) -> Vec<Vec<f64>> { assert_eq!(self.topology[0],inputs.len()); let mut m = Matrix::new(1,inputs.len(),inputs); let mut all_results = Vec::with_capacity(self.topology.len() - 1); self.weights.iter().enumerate().for_each(| (ix,wm) | { add_column(&mut m,ve...
forward
identifier_name
vm.rs
#![allow(clippy::arithmetic_side_effects)] // Derived from uBPF <https://github.com/iovisor/ubpf> // Copyright 2015 Big Switch Networks, Inc // (uBPF: VM architecture, parts of the interpreter, originally in C) // Copyright 2016 6WIND S.A. <quentin.monnet@6wind.com> // (Translation to Rust, MetaBuff/multiple ...
{ /// Contains the register state at every instruction in order of execution pub trace_log: Vec<TraceLogEntry>, /// Maximal amount of instructions which still can be executed pub remaining: u64, } impl ContextObject for TestContextObject { fn trace(&mut self, state: [u64; 12]) { self.trace...
TestContextObject
identifier_name
vm.rs
#![allow(clippy::arithmetic_side_effects)] // Derived from uBPF <https://github.com/iovisor/ubpf> // Copyright 2015 Big Switch Networks, Inc // (uBPF: VM architecture, parts of the interpreter, originally in C) // Copyright 2016 6WIND S.A. <quentin.monnet@6wind.com> // (Translation to Rust, MetaBuff/multiple ...
} #[cfg(test)] mod tests { use super::*; use crate::syscalls; #[test] fn test_program_result_is_stable() { let ok = ProgramResult::Ok(42); assert_eq!(unsafe { *(&ok as *const _ as *const u64) }, 0); let err = ProgramResult::Err(Box::new(EbpfError::JitNotCompiled)); ass...
{ let mut registers = [0u64; 12]; // R1 points to beginning of input memory, R10 to the stack of the first frame, R11 is the pc (hidden) registers[1] = ebpf::MM_INPUT_START; registers[ebpf::FRAME_PTR_REG] = self.stack_pointer; registers[11] = executable.get_entrypoint_instruction...
identifier_body
vm.rs
#![allow(clippy::arithmetic_side_effects)] // Derived from uBPF <https://github.com/iovisor/ubpf> // Copyright 2015 Big Switch Networks, Inc // (uBPF: VM architecture, parts of the interpreter, originally in C) // Copyright 2016 6WIND S.A. <quentin.monnet@6wind.com> // (Translation to Rust, MetaBuff/multiple ...
impl<'a, C: ContextObject> EbpfVm<'a, C> { /// Creates a new virtual machine instance. pub fn new( config: &Config, sbpf_version: &SBPFVersion, context_object: &'a mut C, mut memory_mapping: MemoryMapping<'a>, stack_len: usize, ) -> Self { let stack_pointer =...
pub debug_port: Option<u16>, }
random_line_split
vm.rs
#![allow(clippy::arithmetic_side_effects)] // Derived from uBPF <https://github.com/iovisor/ubpf> // Copyright 2015 Big Switch Networks, Inc // (uBPF: VM architecture, parts of the interpreter, originally in C) // Copyright 2016 6WIND S.A. <quentin.monnet@6wind.com> // (Translation to Rust, MetaBuff/multiple ...
; let instruction_count = if config.enable_instruction_meter { self.context_object_pointer.consume(due_insn_count); initial_insn_count.saturating_sub(self.context_object_pointer.get_remaining()) } else { 0 }; let mut result = ProgramResult::Ok(0); ...
{ #[cfg(all(feature = "jit", not(target_os = "windows"), target_arch = "x86_64"))] { let compiled_program = match executable .get_compiled_program() .ok_or_else(|| Box::new(EbpfError::JitNotCompiled)) { O...
conditional_block
ed25519.rs
// -*- mode: rust; -*- // // This file is part of ed25519-dalek. // Copyright (c) 2017 Isis Lovecruft // See LICENSE for licensing information. // // Authors: // - Isis Agora Lovecruft <isis@patternsinthevoid.net> //! A Rust implementation of ed25519 EdDSA key generation, signing, and //! verification. use core::fmt:...
TestSignVerify let mut cspring: OsRng; let keypair: Keypair; let good_sig: Signature; let bad_sig: Signature; let good: &[u8] = "test message".as_bytes(); let bad: &[u8] = "wrong message".as_bytes(); cspring = OsRng::new().unwrap(); keypair = Keypai...
ify() { //
identifier_name
ed25519.rs
// -*- mode: rust; -*- // // This file is part of ed25519-dalek. // Copyright (c) 2017 Isis Lovecruft // See LICENSE for licensing information. // // Authors: // - Isis Agora Lovecruft <isis@patternsinthevoid.net> //! A Rust implementation of ed25519 EdDSA key generation, signing, and //! verification. use core::fmt:...
if ao.is_some() { a = ao.unwrap(); } else { return false; } a = -(&a); let top_half: &[u8; 32] = array_ref!(&signature.0, 32, 32); let bottom_half: &[u8; 32] = array_ref!(&signature.0, 0, 32); h.input(&bottom_half[..]); h.inpu...
return false; } ao = self.decompress();
random_line_split
ed25519.rs
// -*- mode: rust; -*- // // This file is part of ed25519-dalek. // Copyright (c) 2017 Isis Lovecruft // See LICENSE for licensing information. // // Authors: // - Isis Agora Lovecruft <isis@patternsinthevoid.net> //! A Rust implementation of ed25519 EdDSA key generation, signing, and //! verification. use core::fmt:...
/// View this public key as a byte array. #[inline] pub fn as_bytes<'a>(&'a self) -> &'a [u8; PUBLIC_KEY_LENGTH] { &(self.0).0 } /// Construct a `PublicKey` from a slice of bytes. /// /// # Warning /// /// The caller is responsible for ensuring that the bytes passed into this ...
self.0.to_bytes() }
identifier_body
ed25519.rs
// -*- mode: rust; -*- // // This file is part of ed25519-dalek. // Copyright (c) 2017 Isis Lovecruft // See LICENSE for licensing information. // // Authors: // - Isis Agora Lovecruft <isis@patternsinthevoid.net> //! A Rust implementation of ed25519 EdDSA key generation, signing, and //! verification. use core::fmt:...
lse { return false; } } } impl Signature { /// View this `Signature` as a byte array. #[inline] pub fn to_bytes(&self) -> [u8; SIGNATURE_LENGTH] { self.0 } /// View this `Signature` as a byte array. #[inline] pub fn as_bytes<'a>(&'a self) -> &'a [u8; SIGNATU...
return true; } e
conditional_block
asset.go
// Generated by goasset(1.0 20200404) or "go generate" . DO NOT EDIT. // https://github.com/hidu/goasset/ package res import ( "bytes" "compress/gzip" "encoding/base64" "flag" "fmt" "io/ioutil" "log" "mime" "net/http" "os" "path" "path/filepath" "regexp" "runtime" "strings" "time" ) // AssetFile one ...
(name string) []byte { s, err := afs.GetAssetFile(name) if err != nil { return []byte("") } return s.Content() } // GetFileNames get all file names func (afs *assetFiles) GetFileNames(dir string) []string { if dir == "" { dir = "/" } names := make([]string, 0, len(afs.Files)) dirRaw := dir dir = path.Clea...
GetContent
identifier_name
asset.go
// Generated by goasset(1.0 20200404) or "go generate" . DO NOT EDIT. // https://github.com/hidu/goasset/ package res import ( "bytes" "compress/gzip" "encoding/base64" "flag" "fmt" "io/ioutil" "log" "mime" "net/http" "os" "path" "path/filepath" "regexp" "runtime" "strings" "time" ) // AssetFile one ...
helper := newAssetHelper() contentNew, errHelper := helper.Execute(assetFilePath, content, "") if errHelper != nil { return nil, errHelper } return &assetFile{ content: contentNew, name: name, mtime: info.ModTime(), }, nil } return nil, fmt.Errorf("not file") } if sf, has ...
{ return nil, err }
conditional_block
asset.go
// Generated by goasset(1.0 20200404) or "go generate" . DO NOT EDIT. // https://github.com/hidu/goasset/ package res import ( "bytes" "compress/gzip" "encoding/base64" "flag" "fmt" "io/ioutil" "log" "mime" "net/http" "os" "path" "path/filepath" "regexp" "runtime" "strings" "time" ) // AssetFile one ...
r _ = flag.String var _ = runtime.Version() // ---------------------------helper.go--------begin--------------------------// func newAssetHelper() *assetHelper { helper := &assetHelper{} helper.Regs = make(map[string]*regexp.Regexp) helper.Regs["remove_above"] = regexp.MustCompile(`[\S\s]*?//\s*asset_remove_above...
oin(f.pdir, r.URL.Path)) f.sf.FileHandlerFunc(name).ServeHTTP(w, r) } var _ AssetFiles = &assetFiles{} va
identifier_body
asset.go
// Generated by goasset(1.0 20200404) or "go generate" . DO NOT EDIT. // https://github.com/hidu/goasset/ package res import ( "bytes" "compress/gzip" "encoding/base64" "flag" "fmt" "io/ioutil" "log" "mime" "net/http" "os" "path" "path/filepath" "regexp" "runtime" "strings" "time" ) // AssetFile one ...
// assetFiles asset files type assetFiles struct { Files map[string]*assetFile } var _assetDirect bool var _assetCwd, _ = os.Getwd() // GetAssetFile get file by name func (afs *assetFiles) GetAssetFile(name string) (AssetFile, error) { name = filepath.ToSlash(name) if name != "" && name[0] != '/' { name = "/" ...
random_line_split
Measurements.py
#!/usr/bin/env python # encoding: utf-8 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version...
(related): """For related words found for a measurement (usually nouns), add any connected adjectives, compounds, or modifiers. Args: related (list): objects containing related words and their metadata Returns: list: original list of related objects augmented with additional descriptor wor...
_add_descriptors
identifier_name
Measurements.py
#!/usr/bin/env python # encoding: utf-8 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version...
def _get_cousin(sibling_idx, dep_type_list, visited_nodes={}): """Find a second degree relation within the dependency graph. Used to find subject in a sentence when the measurement unit is a direct object, for example. Args: sibling_idx (str): Token index of the sibling node through which to fin...
"""If an edge connects to a node (word), return the index of the node Args: edge (tuple): Contains token indices of two connect words and the dependency type between them - e.g. ('11', '14', {'dep': 'nmod:at'}) idx (int): Token index of word Returns: str or None: str if connected word ...
identifier_body
Measurements.py
#!/usr/bin/env python # encoding: utf-8 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version...
"Not finding token index for Grobid Quantity value in CoreNLP output. Sentence: %s" % sentence) return {} if "rawUnit" in q[key]: q[key]["rawUnit"]["after"] = a.lookup[q[key]["tokenIndex"]]["after"] q[key]["rawUnit"]["t...
random_line_split
Measurements.py
#!/usr/bin/env python # encoding: utf-8 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version...
return simplified def _reconstruct_sent(parsed_sentence): """Reconstruct sentence from CoreNLP tokens - raw sentence text isn't retained by CoreNLP after sentence splitting and processing Args: parsed_sentence (dict): Object containing CoreNLP output Returns: str: original sentence...
r["descriptors"].sort(key=lambda x: int(x["tokenIndex"]), reverse=False) for z in r["descriptors"]: simplified["related"][r["rawName"]].append(z["rawName"])
conditional_block
nsis.rs
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #[cfg(target_os = "windows")] use crate::bundle::windows::util::try_sign; use crate::{ bundle::{ common::CommandExt, windows::util::{ download, download_and_verif...
(settings: &Settings, updater: bool) -> crate::Result<Vec<PathBuf>> { let tauri_tools_path = dirs_next::cache_dir().unwrap().join("tauri"); let nsis_toolset_path = tauri_tools_path.join("NSIS"); if !nsis_toolset_path.exists() { get_and_extract_nsis(&nsis_toolset_path, &tauri_tools_path)?; } else if NSIS_RE...
bundle_project
identifier_name
nsis.rs
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #[cfg(target_os = "windows")] use crate::bundle::windows::util::try_sign; use crate::{ bundle::{ common::CommandExt, windows::util::{ download, download_and_verif...
rename(_tauri_tools_path.join("nsis-3.08"), nsis_toolset_path)?; } let nsis_plugins = nsis_toolset_path.join("Plugins"); let data = download(NSIS_APPLICATIONID_URL)?; info!("extracting NSIS ApplicationID plugin"); extract_zip(&data, &nsis_plugins)?; create_dir_all(nsis_plugins.join("x86-unicode"))?; ...
info!("extracting NSIS"); extract_zip(&data, _tauri_tools_path)?;
random_line_split
nsis.rs
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #[cfg(target_os = "windows")] use crate::bundle::windows::util::try_sign; use crate::{ bundle::{ common::CommandExt, windows::util::{ download, download_and_verif...
fn write_ut16_le_with_bom<P: AsRef<Path>>(path: P, content: &str) -> crate::Result<()> { use std::fs::File; use std::io::{BufWriter, Write}; let file = File::create(path)?; let mut output = BufWriter::new(file); output.write_all(&[0xFF, 0xFE])?; // the BOM part for utf16 in content.encode_utf16() { o...
{ if let Some(path) = custom_lang_files.and_then(|h| h.get(lang)) { return Ok(Some((dunce::canonicalize(path)?, None))); } let lang_path = PathBuf::from(format!("{lang}.nsh")); let lang_content = match lang.to_lowercase().as_str() { "arabic" => Some(include_str!("./templates/nsis-languages/Arabic.nsh")...
identifier_body
scheduler.go
/* Copyright 2019 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
delete(s.activeClusterOperations, clusterOp.Id) s.finishedClusterOperations[clusterOp.Id] = clusterOp } func (s *Scheduler) runTask(taskProto *automationpb.Task, clusterOpID string) ([]*automationpb.TaskContainer, string, error) { if taskProto.State == automationpb.TaskState_DONE { // Task is already done (e.g. ...
{ panic("Pending ClusterOperation was not recorded as active, but should have.") }
conditional_block
scheduler.go
/* Copyright 2019 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
func (s *Scheduler) createTaskInstance(taskName string) (Task, error) { s.taskCreatorMu.Lock() taskCreator := s.taskCreator s.taskCreatorMu.Unlock() task := taskCreator(taskName) if task == nil { return nil, fmt.Errorf("no implementation found for: %v", taskName) } return task, nil } // validateParameters ...
{ taskInstanceForParametersCheck, err := s.createTaskInstance(taskName) if err != nil { return err } errParameters := validateParameters(taskInstanceForParametersCheck, parameters) if errParameters != nil { return errParameters } return nil }
identifier_body
scheduler.go
/* Copyright 2019 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
// The scheduler may update the copy with the latest status. activeClusterOperations map[string]ClusterOperationInstance // Guarded by "muOpList". // The key of the map is ClusterOperationInstance.ID. finishedClusterOperations map[string]ClusterOperationInstance } // NewScheduler creates a new instance. func NewS...
// The key of the map is ClusterOperationInstance.ID. // This map contains a copy of the ClusterOperationInstance which is currently processed.
random_line_split
scheduler.go
/* Copyright 2019 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
() { s.mu.Lock() if s.state != stateShuttingDown { s.state = stateShuttingDown close(s.toBeScheduledClusterOperations) } s.mu.Unlock() log.Infof("Scheduler was shut down. Waiting for pending ClusterOperations to finish.") s.pendingOpsWg.Wait() s.mu.Lock() s.state = stateShutdown s.mu.Unlock() log.Infof(...
ShutdownAndWait
identifier_name
index.js
import { defineHidden, FluidType, is, each, isFluidValue, createInterpolator, toArray, isEqual, Globals, needsInterpolation, useForceUpdate, useIsomorphicLayoutEffect } from '@react-spring/shared'; import _extends from '@babel/runtime/helpers/esm/extends'; import { deprecateInterpolate } from '@react-spring/shared/de...
super.setValue(props.style && createAnimatedStyle ? _extends({}, props, { style: createAnimatedStyle(props.style) }) : props); Animated.context = null; } /** @internal */ onParentChange() { if (!this.dirty) { this.dirty = true; frameLoop.onFrame(() => { th...
if (context) { Animated.context = context; }
random_line_split
index.js
import { defineHidden, FluidType, is, each, isFluidValue, createInterpolator, toArray, isEqual, Globals, needsInterpolation, useForceUpdate, useIsomorphicLayoutEffect } from '@react-spring/shared'; import _extends from '@babel/runtime/helpers/esm/extends'; import { deprecateInterpolate } from '@react-spring/shared/de...
() { let value = this._string; return value == null ? this._string = this._toString(this._value) : value; } setValue(value) { if (!is$1.num(value)) { this._string = value; this._value = 1; } else if (super.setValue(value)) { this._string = null; } else { retu...
getValue
identifier_name
index.js
import { defineHidden, FluidType, is, each, isFluidValue, createInterpolator, toArray, isEqual, Globals, needsInterpolation, useForceUpdate, useIsomorphicLayoutEffect } from '@react-spring/shared'; import _extends from '@babel/runtime/helpers/esm/extends'; import { deprecateInterpolate } from '@react-spring/shared/de...
}); } /** Reset our node and the nodes of every descendant */ _reset(goal) { this.node.reset(!this.idle, goal); each(this._children, observer => { if (isAnimationValue(observer)) { observer._reset(goal); } }); } } /** An object containing `Animated` node...
{ observer.onParentPriorityChange(priority, this); }
conditional_block
train.py
import argparse import torch import torch.nn as nn import re import numpy as np import os import pickle from data_loader import get_loader from data_loader import get_images from build_vocab import Vocabulary from model import EncoderCNN, DecoderRNN from torch.autograd import Variable from torch.nn.utils.rnn import ...
def main(args): # Create model directory if not os.path.exists(args.model_path): os.makedirs(args.model_path) # Image preprocessing # For normalization, see https://github.com/pytorch/vision#models transform = transforms.Compose([ transforms.RandomCrop(args.crop_size), ...
if torch.cuda.is_available(): x = x.cuda() return Variable(x, volatile=volatile)
identifier_body
train.py
import argparse import torch import torch.nn as nn import re import numpy as np import os import pickle from data_loader import get_loader from data_loader import get_images from build_vocab import Vocabulary from model import EncoderCNN, DecoderRNN from torch.autograd import Variable from torch.nn.utils.rnn import ...
for index,word in enumerate(words): words[index] = vocab.word2idx[word] rationalizations.append(words) # max_length = max(rationalizations,key=len rationalizations=[np.array(xi) for xi in rationalizations] # for index,r in enumerate(rationalizations): # # pr...
max_length = length
conditional_block
train.py
import argparse import torch import torch.nn as nn import re import numpy as np import os import pickle from data_loader import get_loader from data_loader import get_images from build_vocab import Vocabulary from model import EncoderCNN, DecoderRNN from torch.autograd import Variable from torch.nn.utils.rnn import ...
new_lengths.reverse() captions = captions # print(captions) # print(new_lengths) targets = pack_padded_sequence(captions, new_lengths, batch_first=True)[0] decoder.zero_grad() encoder.zero_grad() # print(images) ...
random_line_split
train.py
import argparse import torch import torch.nn as nn import re import numpy as np import os import pickle from data_loader import get_loader from data_loader import get_images from build_vocab import Vocabulary from model import EncoderCNN, DecoderRNN from torch.autograd import Variable from torch.nn.utils.rnn import ...
(x, volatile=False): if torch.cuda.is_available(): x = x.cuda() return Variable(x, volatile=volatile) def main(args): # Create model directory if not os.path.exists(args.model_path): os.makedirs(args.model_path) # Image preprocessing # For normalization, see https://git...
to_var
identifier_name
tasks.py
"""Define celery tasks for hs_core app.""" from __future__ import absolute_import import os import sys import traceback import zipfile import logging import json from datetime import datetime, timedelta, date from xml.etree import ElementTree import requests from celery import shared_task from celer...
@periodic_task(ignore_result=True, run_every=crontab(minute=0, hour=0)) def manage_task_nightly(): # The nightly running task do DOI activation check # Check DOI activation on failed and pending resources and send email. msg_lst = [] # retrieve all published resources with failed metadata d...
logger.info("added " + str(add_count) + " out of " + str( active_subscribed.count()) + " for list id " + list_id)
conditional_block
tasks.py
"""Define celery tasks for hs_core app.""" from __future__ import absolute_import import os import sys import traceback import zipfile import logging import json from datetime import datetime, timedelta, date from xml.etree import ElementTree import requests from celery import shared_task from celer...
@shared_task def add_zip_file_contents_to_resource(pk, zip_file_path): """Add zip file to existing resource and remove tmp zip file.""" zfile = None resource = None try: resource = utils.get_resource_by_shortkey(pk, or_404=False) zfile = zipfile.ZipFile(zip_file_path) ...
hs_internal_zone = "hydroshare" if not QuotaMessage.objects.exists(): QuotaMessage.objects.create() qmsg = QuotaMessage.objects.first() users = User.objects.filter(is_active=True).filter(is_superuser=False).all() for u in users: uq = UserQuota.objects.filter(user__username=u.userna...
identifier_body
tasks.py
"""Define celery tasks for hs_core app.""" from __future__ import absolute_import import os import sys import traceback import zipfile import logging import json from datetime import datetime, timedelta, date from xml.etree import ElementTree import requests from celery import shared_task from celer...
(pk, zip_file_path): """Add zip file to existing resource and remove tmp zip file.""" zfile = None resource = None try: resource = utils.get_resource_by_shortkey(pk, or_404=False) zfile = zipfile.ZipFile(zip_file_path) num_files = len(zfile.infolist()) zcontents =...
add_zip_file_contents_to_resource
identifier_name
tasks.py
"""Define celery tasks for hs_core app.""" from __future__ import absolute_import import os import sys import traceback import zipfile import logging import json from datetime import datetime, timedelta, date from xml.etree import ElementTree import requests from celery import shared_task from celer...
DOI_BATCH_ID=res.short_id, TYPE='result')) root = ElementTree.fromstring(response.content) rec_cnt_elem = root.find('.//record_count') failure_cnt_elem = root.find('.//failure_co...
USERNAME=settings.CROSSREF_LOGIN_ID, PASSWORD=settings.CROSSREF_LOGIN_PWD,
random_line_split
controllers.js
angular.module('starter.controllers', []) .controller('HomeCtrl', function($scope) {}) .controller('ChatsCtrl', function($scope, Chats) { $scope.chats = Chats.all(); $scope.remove = function(chat) { Chats.remove(chat); }; }) .controller('PieChartCtrl', function($scope,$stateParams,$timeout,$rootScope,$ionic...
$scope.add={}; alert($scope.add.fname); var id1=$scope.p[$scope.p.length-1].id+1; var savep={ id: id1, face: 'img/mike.png', name: $scope.add.fname, PatientID: '12556'+id1, Age : $scope.add.fname, message : 'Hi doctor', date:'26/3/2017 3.20PM', gender:'Male' }; // Patients.s...
$scope.done=function(){ $scope.p=Patients.all();
random_line_split
controllers.js
angular.module('starter.controllers', []) .controller('HomeCtrl', function($scope) {}) .controller('ChatsCtrl', function($scope, Chats) { $scope.chats = Chats.all(); $scope.remove = function(chat) { Chats.remove(chat); }; }) .controller('PieChartCtrl', function($scope,$stateParams,$timeout,$rootScope,$ionic...
} } //iterate through contacts list and delete //contact if found this.delete = function (id) { for (i in contacts) { if (contacts[i].id == id) { contacts.splice(i, 1); } } } //simply returns the contacts list this.list...
{ return contacts[i]; }
conditional_block
mamikon.js
(function () { var body = document.querySelector('body'); //прелоадер >>>>>>>>>>>>>>>>>>>>>>*/ var preloader = document.querySelector('.loader'); //body.classList.add('overflow'); window.onload = function () { window.setTimeout(function () { preloader.classList.add('disable'); //document.body.classList.r...
estsElementClass(target, 'popup'); closePopup(popup); bodyOverflow(); } }); //Закрытие попапа при клике на escape (Esc) body.addEventListener('keydown', function (e) { if (e.keyCode !== 27) return; else { var popup = document.querySelector('.popup.is-active'); closePopup(popup); bodyOverflo...
up = clos
identifier_name
mamikon.js
(function () { var body = document.querySelector('body'); //прелоадер >>>>>>>>>>>>>>>>>>>>>>*/ var preloader = document.querySelector('.loader'); //body.classList.add('overflow'); window.onload = function () { window.setTimeout(function () { preloader.classList.add('disable'); //document.body.classList.r...
//Поиск названия data-popup, который задан у кнопки бургера //var popupClass = target.getAttribute('data-popup'); var popupClass = closestsElementAttr(target, 'data-popup'); //если элемент, на котором кликнули, не имеет аттрибут data-popup, то выходим if (popupClass === null) { return; } e.preventDefa...
var target = e.target;
random_line_split
mamikon.js
(function () { var body = document.querySelector('body'); //прелоадер >>>>>>>>>>>>>>>>>>>>>>*/ var preloader = document.querySelector('.loader'); //body.classList.add('overflow'); window.onload = function () { window.setTimeout(function () { preloader.classList.add('disable'); //document.body.classList.r...
eturn; } e.preventDefault(); var popup = document.querySelector('.' + popupClass); if (popup) { showPopup(popup); bodyOverflow(); } }) //Закрытие попапа при клике X или на область вне попапа body.addEventListener('click', function (e) { var target = e.target; //Если клик был на кнопку Х или фон ...
data-popup'); //если элемент, на котором кликнули, не имеет аттрибут data-popup, то выходим if (popupClass === null) { r
conditional_block
mamikon.js
(function () { var body = document.querySelector('body'); //прелоадер >>>>>>>>>>>>>>>>>>>>>>*/ var preloader = document.querySelector('.loader'); //body.classList.add('overflow'); window.onload = function () { window.setTimeout(function () { preloader.classList.add('disable'); //document.body.classList.r...
on changeSlideLeft() { //activeSlide.classList.remove('active'); for (var i = slides.length - 1; i >= 0; i--) { if (slides[i].classList.contains('active')) { slides[i].classList.remove('active'); if (i > 0) slides[--i].classList.add('active'); else slides[slides.length - 1].classList.add('a...
iveSlide.classList.remove('active'); for (var i = 0; i < slides.length; i++) { if (slides[i].classList.contains('active')) { slides[i].classList.remove('active'); if (i < slides.length - 1) slides[++i].classList.add('active'); else slides[0].classList.add('active'); return; } } } ...
identifier_body
GameScene.ts
module wqq { import Vector2D = snake.Vector2; export enum InGameEvent { kInGamePlayerRespawn = 30000, kInGamePlayerPlayerDead = 30001, kInGameEndlessRankPlayer = 30002 }; export class AnimationCurve { private m_keys:Array<number> = []; private m_Values:Array<number> = []; public constructor(){ }...
} public GetTimeLeft():number { return 0; } public GetNameInfo(id:number):NameInfo { return this.allNames[id]; } public Enter() { //SceneManager.GetInstance().ShowApp(AppModuleType.kAppInGameMainUI, false, false, false); //SoundManager.GetInstance().PlayBackgroundMusic("sound/music/GameS...
date(deltaTime); this.LateUpdate(deltaTime);
conditional_block
GameScene.ts
module wqq { import Vector2D = snake.Vector2; export enum InGameEvent { kInGamePlayerRespawn = 30000, kInGamePlayerPlayerDead = 30001, kInGameEndlessRankPlayer = 30002 }; export class AnimationCurve { private m_keys:Array<number> = []; private m_Values:Array<number> = []; public constructor(){ }...
public AddNameInfo(name:NameInfo) { this.allNames[name.id] = name; } public SendSlitherCmd(targetDirection:Vector2D, accelarating:boolean) { } public SetSlitherNameInfo(slither:Slither, id:number) { let info = this.allNames[id]; if (!info) { return; } slither.SetName(info.name);...
let attr = (typeof name == "number")?"GetID":"GetName"; let size = this.m_AllSlithers.length; for (let i = 0; i < size; ++i) { let slither = this.m_AllSlithers[i]; if (slither[attr]() == name) { return slither; } } return null; }
identifier_body
GameScene.ts
module wqq { import Vector2D = snake.Vector2; export enum InGameEvent { kInGamePlayerRespawn = 30000, kInGamePlayerPlayerDead = 30001, kInGameEndlessRankPlayer = 30002 }; export class AnimationCurve { private m_keys:Array<number> = []; private m_Values:Array<number> = []; public constructor(){ }...
sg:RpcSlitherBirthDeathSync) { let foundPlayer = false; let count = msg.slithers.length; for (let i = 0; i < count; i++) { let info = msg.slithers[i]; let slither = this.FindSlither(info.id); let isPlayer = info.id == this.m_PlayerID; if (isPlayer) { foundPlayer = true; } if ...
SlitherBirthDeathSync(m
identifier_name
GameScene.ts
module wqq { import Vector2D = snake.Vector2; export enum InGameEvent { kInGamePlayerRespawn = 30000, kInGamePlayerPlayerDead = 30001, kInGameEndlessRankPlayer = 30002 }; export class AnimationCurve { private m_keys:Array<number> = []; private m_Values:Array<number> = []; public constructor(){ }...
this.DestroyAllSlithers(); let gameLayer = this; gameLayer.removeChild(this.m_TileBackground); gameLayer.removeChild(this.m_BeanView); gameLayer.removeChild(this.m_FlyBeanContainer); gameLayer.removeChild(this.m_SlitherContainer); this.allNames = {}; this.m_TileBackground = null; this.m_Be...
random_line_split
mod.rs
//! Abstraction over multiple versions of the file format allowed //! //! Because we want to continue to properly handle old config file formats - even when they'll no //! longer be generated by default. In the future, we might provide some kind of feature-gating for //! older versions, so that the dependencies associa...
/// An immutable handle on an entry in the file pub trait EntryRef { /// Returns the title of the entry fn name(&self) -> &str; /// Returns all the tags associated with the entry fn tags(&self) -> Vec<&str>; /// Returns the date + time at which the fn first_added(&self) -> SystemTime; ///...
fn remove_entry(&mut self, idx: usize); }
random_line_split
mod.rs
//! Abstraction over multiple versions of the file format allowed //! //! Because we want to continue to properly handle old config file formats - even when they'll no //! longer be generated by default. In the future, we might provide some kind of feature-gating for //! older versions, so that the dependencies associa...
}
{ PlaintextContent { last_update: SystemTime::now(), entries: Vec::new(), } }
identifier_body
mod.rs
//! Abstraction over multiple versions of the file format allowed //! //! Because we want to continue to properly handle old config file formats - even when they'll no //! longer be generated by default. In the future, we might provide some kind of feature-gating for //! older versions, so that the dependencies associa...
}; macro_rules! prefix_match { ($val:expr => { $($str:literal => $arm:expr,)* _ => $else_arm:expr, }) => {{ let v = $val; $(if v.starts_with($str) { $arm } else)* { $else_arm } }}; } prefix_match!(content....
{ eprintln!("failed to read file {:?}: {}", file.to_string_lossy(), e); exit(1); }
conditional_block
mod.rs
//! Abstraction over multiple versions of the file format allowed //! //! Because we want to continue to properly handle old config file formats - even when they'll no //! longer be generated by default. In the future, we might provide some kind of feature-gating for //! older versions, so that the dependencies associa...
{ Basic, Protected, Totp, } impl Display for ValueKind { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { ValueKind::Basic => f.write_str("Basic"), ValueKind::Protected => f.write_str("Protected"), ValueKind::Totp => f.write_str("TOTP"), ...
ValueKind
identifier_name
draw.js
var pickColor = (category) => { if(category == "pup" || category == "weanling" || category == "yearling") { return "#220C08"; //chocolate black } else if (category == "adult_female") { return "#9B8576"; //tan } else if (category == "adult_male") { return "#BC8D7D"; /...
.style("text-anchor", "middle") .attr("transform", "translate(" + width/3 + ", " + height/2 + ")") .text("Mid Bight Beach"); //bottom right text svg.append("text") .style("text-anchor", "middle") .attr("transform", "translate(" + width*2/3 + ", " + height/2 + ")")...
.attr("transform", "translate(" + width*2/3 + ", " + height/12 + ")") .text("Bight Beach North"); //bottom left text svg.append("text")
random_line_split
draw.js
var pickColor = (category) => { if(category == "pup" || category == "weanling" || category == "yearling") { return "#220C08"; //chocolate black } else if (category == "adult_female") { return "#9B8576"; //tan } else if (category == "adult_male") { return "#BC8D7D"; /...
(old, location) { let newData; console.log("Fixing this data: "); console.log(old); //create new array where each element is an object with the seal type and where it is newData = old.map( seal => { return {type: seal, location: location}; }); return newData; }
fixData
identifier_name
draw.js
var pickColor = (category) => { if(category == "pup" || category == "weanling" || category == "yearling") { return "#220C08"; //chocolate black } else if (category == "adult_female") { return "#9B8576"; //tan } else if (category == "adult_male") { return "#BC8D7D"; /...
} // bubble cluster physics // help from https://youtu.be/NTS7uXOxQeM var forceX = d3.forceX( d => { if(d.location == "North Point") { //North Point return width*1/3; } else if(d.location == "Bight Beach North") { //Bight Beach North return width*2/3; ...
{ circles .attr("cx", d => d.x) .attr("cy", d => d.y) }
identifier_body
draw.js
var pickColor = (category) => { if(category == "pup" || category == "weanling" || category == "yearling") { return "#220C08"; //chocolate black } else if (category == "adult_female") { return "#9B8576"; //tan } else if (category == "adult_male") { return "#BC8D7D"; /...
else {//d.data[0].long > medianLong return height*3/4; } }) .strength(0.1); var simulation = d3.forceSimulation() .force("x", forceX) .force("y", forceY) .force("collide", d3.forceCollide( d => pickSize(d.type) )); //this function specifically exists to ...
{ return height/4; }
conditional_block
main.rs
extern crate petgraph; extern crate rand; extern crate time; extern crate clap; use std::cmp::{max, min}; use std::collections::HashSet; use rand::Rng; use time::PreciseTime; enum Method { Any, All, } fn main() { let matches = clap::App::new("square-sum") .about("Calculates solutions to the squa...
( g: &mut petgraph::Graph<(), (), petgraph::Undirected, usize>, square_numbers: &[usize], ) { let i = g.node_count() + 1; g.add_node(()); for sq in square_numbers .iter() .skip_while(|&sq| sq <= &i) .take_while(|&sq| sq <= &((i * 2) - 1)) { let i_index = petgraph:...
add_square_sum_node
identifier_name
main.rs
extern crate petgraph; extern crate rand; extern crate time; extern crate clap; use std::cmp::{max, min}; use std::collections::HashSet; use rand::Rng; use time::PreciseTime; enum Method { Any, All, } fn main() { let matches = clap::App::new("square-sum") .about("Calculates solutions to the squa...
fn push(&mut self, node_index: usize) { self.path.push(node_index); self.member[node_index] = true; } fn len(&self) -> usize { self.path.len() } fn contains(&self, node_index: usize) -> bool { self.member[node_index] } fn backtrack(&mut self, amount: usiz...
{ // TODO check that size >= seed.len() let mut path = Vec::with_capacity(size); let mut member = vec![false; size]; for i in seed.iter() { path.push(i - 1); member[*i - 1] = true; } Path { path, member } }
identifier_body
main.rs
extern crate petgraph; extern crate rand; extern crate time; extern crate clap; use std::cmp::{max, min}; use std::collections::HashSet; use rand::Rng; use time::PreciseTime; enum Method { Any, All, } fn main() { let matches = clap::App::new("square-sum") .about("Calculates solutions to the squa...
fn reverse(&mut self) { self.path.reverse(); } fn iter(&self) -> std::slice::Iter<usize> { self.path.iter() } } fn setup_path<N, E, Ty>(g: &petgraph::Graph<N, E, Ty, usize>) -> Result<Path, &'static str> where Ty: petgraph::EdgeType, { let mut rng = rand::thread_rng(); let...
self.path.truncate(new_size); }
random_line_split
_bev_qfz.py
import os import smilPython as sm import numpy as np from pyntcloud import PyntCloud from smutsia.point_cloud.projection import Projection, project_img, back_projection_ground from smutsia.utils.image import np_2_smil, smil_2_np, label_with_measure
self.delta_ground = delta_ground self.delta_h_circle = delta_h_circle self.nl = nl def find_min_z(zL, step): # TODO: Ask Bea the reason why this function. Apparently minPercent is not used # histogram of zL, step = 0.2. minZ is set to the value over 0 # with at maximum 5% of points...
class LambdaGDParameters: def __init__(self, my_lambda=2, delta_ground=0.2, delta_h_circle=0.5, nl=sm.HexSE()): self.my_lambda = my_lambda
random_line_split
_bev_qfz.py
import os import smilPython as sm import numpy as np from pyntcloud import PyntCloud from smutsia.point_cloud.projection import Projection, project_img, back_projection_ground from smutsia.utils.image import np_2_smil, smil_2_np, label_with_measure class LambdaGDParameters: def __init__(self, my_lambda=2, delta_g...
# for each distance to scanner, get the layer index inverse_radius_index = {} index = 0 # get the maximum index falling into the image imsize = max(im.getHeight(), im.getWidth()) while imsize <= radius_index[index]: index = index + 1 # for this index, get the corresponding radius...
radius_index[i] = radius
conditional_block
_bev_qfz.py
import os import smilPython as sm import numpy as np from pyntcloud import PyntCloud from smutsia.point_cloud.projection import Projection, project_img, back_projection_ground from smutsia.utils.image import np_2_smil, smil_2_np, label_with_measure class LambdaGDParameters: def __init__(self, my_lambda=2, delta_g...
def get_scanner_xy(points, proj): """ get x0,y0 coordinates of the scanner location """ # Find the pixel corresponding to (x=0,y=0) res_x = proj.projector.res_x # 5 pixels / m, 1 px = 20 cm res_y = proj.projector.res_y # 5 pixels / m , 1 px = 20 cm min_x, min_y, min_z = points.min(0) # t...
"""im: as an input image just the size is important. As an output image it contains the dart board x0,y0,hScanner: scanner position alpha0: first angle res_x,res_y : spatial resolution of input image nb_layers The output draws a chess board according to the size of the each """ ...
identifier_body
_bev_qfz.py
import os import smilPython as sm import numpy as np from pyntcloud import PyntCloud from smutsia.point_cloud.projection import Projection, project_img, back_projection_ground from smutsia.utils.image import np_2_smil, smil_2_np, label_with_measure class LambdaGDParameters: def __init__(self, my_lambda=2, delta_g...
(zL, step): # TODO: Ask Bea the reason why this function. Apparently minPercent is not used # histogram of zL, step = 0.2. minZ is set to the value over 0 # with at maximum 5% of points under it. mybins = np.arange(np.amin(zL), np.amax(zL), step) myhisto = np.histogram(zL, mybins) mycount = myh...
find_min_z
identifier_name
particle.py
''' Water Wheel of Fortune By Nathaniel Yearwood Cody Macedo ''' import pygame, sys import matplotlib.pyplot as plt import numpy as np from scipy.integrate import ode import random as rand import math import threading win_width = 800 # 500 cm = 5 m win_height = 600 # set up the colors BLACK = (0, 0, 0) GREY...
event = pygame.event.poll() if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN and event.key == pygame.K_q: pygame.quit() sys.exit(0) elif event.type == pygame.KEYDOWN and event.key == pygame.K_p: pause = not pause ...
while True: # 30 fps if not pause: clock.tick(30)
random_line_split
particle.py
''' Water Wheel of Fortune By Nathaniel Yearwood Cody Macedo ''' import pygame, sys import matplotlib.pyplot as plt import numpy as np from scipy.integrate import ode import random as rand import math import threading win_width = 800 # 500 cm = 5 m win_height = 600 # set up the colors BLACK = (0, 0, 0) GREY...
if __name__ == '__main__': main()
if not pause: clock.tick(30) event = pygame.event.poll() if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN and event.key == pygame.K_q: pygame.quit() sys.exit(0) elif event.type == pygame.KEYDOWN and event...
conditional_block
particle.py
''' Water Wheel of Fortune By Nathaniel Yearwood Cody Macedo ''' import pygame, sys import matplotlib.pyplot as plt import numpy as np from scipy.integrate import ode import random as rand import math import threading win_width = 800 # 500 cm = 5 m win_height = 600 # set up the colors BLACK = (0, 0, 0) GREY...
def outside_screen(self, particle): if (particle.state[0] < -particle.radius): return False elif (particle.state[0] > win_width + particle.radius): return False elif (particle.state[1] < -particle.radius): return False else: return T...
self.particles = [x for x in self.particles if self.outside_screen(x)]
identifier_body
particle.py
''' Water Wheel of Fortune By Nathaniel Yearwood Cody Macedo ''' import pygame, sys import matplotlib.pyplot as plt import numpy as np from scipy.integrate import ode import random as rand import math import threading win_width = 800 # 500 cm = 5 m win_height = 600 # set up the colors BLACK = (0, 0, 0) GREY...
(self, imgfile, radius, mass=1.0): particle = Particle(imgfile, radius, mass) self.particles.append(particle) return particle def addWheel(self, centre, radius): wheel = Wheel(centre, radius) self.wheels.append(wheel) return wheel def pprint(self): pri...
add
identifier_name
peticiones_bitacora.js
$(document).ready(function () { var vendedores = $("#vendedores"); //window.moment = require('moment'); var rangoFecha = $("#rangoFecha"); var MmensajeOrdenFecha = $('#MmensajeOrdenFecha'); var map; //Para enviar la fecha Actual var fechaActual = new Date(); var MesActual = fechaActual...
SeleccionarVendedor(); //GOOGLE MAPS });
//DESCRICION : Funcion que me obtiene la lista de rutas asignadas segun el vendedor seleccionado. vendedores.change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); ListarBitacoras(valueSelected,...
identifier_body
peticiones_bitacora.js
$(document).ready(function () { var vendedores = $("#vendedores"); //window.moment = require('moment'); var rangoFecha = $("#rangoFecha"); var MmensajeOrdenFecha = $('#MmensajeOrdenFecha'); var map; //Para enviar la fecha Actual var fechaActual = new Date(); var MesActual = fechaActual...
ndedor, Mes, flagFiltro,fechaIncio,fechaFin) { //DESCRICION : Funcion que me obtiene la lista de bitacoras var json = JSON.stringify({ codVendedor: idVendedor, fechaActual: Mes, flagFiltro: flagFiltro, fechaIncio: fechaIncio, fe...
rBitacoras(idVe
identifier_name
peticiones_bitacora.js
$(document).ready(function () { var vendedores = $("#vendedores"); //window.moment = require('moment'); var rangoFecha = $("#rangoFecha"); var MmensajeOrdenFecha = $('#MmensajeOrdenFecha'); var map; //Para enviar la fecha Actual var fechaActual = new Date(); var MesActual = fechaActual...
$.fn.dataTableExt.afnFiltering.push( function(settings, data, dataIndex) { var min = $('#min-date').val(); var minr = min.split('/').join('-'); var max = $('#max-date').val() var maxr = max.split('/')...
replaceCli = data[i].cliente; clientRuc = replaceCli.replace(/ /g, ""); if (clientRuc == "") { clientRazonS = data[i].razonsocial; } else { clientRazonS = data[i].cliente; } i...
conditional_block
peticiones_bitacora.js
$(document).ready(function () { var vendedores = $("#vendedores"); //window.moment = require('moment'); var rangoFecha = $("#rangoFecha"); var MmensajeOrdenFecha = $('#MmensajeOrdenFecha'); var map; //Para enviar la fecha Actual var fechaActual = new Date(); var MesActual = fechaActual...
}, { "width": "10%", targets: [3], }, { "width": "2%", targets: [5], render: function (data) { return moment(data).format('DD/MM/YYYY'); } }], ...
"width": "5%", targets: [3],
random_line_split
lib.rs
mod utils; use std::cell::RefCell; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{ImageData, WebGlProgram, WebGlRenderingContext, WebGlShader}; const WIDTH: i32 = 128; const HEIGHT: i32 = 128; const CHANNELS: i32 = 4; const BUFFER_SIZE: usize = ((WIDTH * HEIGHT) * CHANNELS) as ...
else { Err(context .get_shader_info_log(&shader) .unwrap_or_else(|| String::from("Unknown error creating shader"))) } } pub fn link_program( context: &WebGlRenderingContext, vert_shader: &WebGlShader, frag_shader: &WebGlShader, ) -> Result<WebGlProgram, String> { le...
{ Ok(shader) }
conditional_block
lib.rs
mod utils; use std::cell::RefCell; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{ImageData, WebGlProgram, WebGlRenderingContext, WebGlShader}; const WIDTH: i32 = 128; const HEIGHT: i32 = 128; const CHANNELS: i32 = 4; const BUFFER_SIZE: usize = ((WIDTH * HEIGHT) * CHANNELS) as ...
pub fn start() { utils::set_panic_hook(); log!("Hello there! Compositor canvas starting/loading"); } #[wasm_bindgen] pub fn initialise(element_id: String) -> Result<(), JsValue> { log!( "Compositor canvas (element_id: String = `{}`) initialisation", &element_id ); let document = we...
.expect("should register `requestAnimationFrame` OK"); } #[wasm_bindgen(start)]
random_line_split
lib.rs
mod utils; use std::cell::RefCell; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{ImageData, WebGlProgram, WebGlRenderingContext, WebGlShader}; const WIDTH: i32 = 128; const HEIGHT: i32 = 128; const CHANNELS: i32 = 4; const BUFFER_SIZE: usize = ((WIDTH * HEIGHT) * CHANNELS) as ...
( context: &WebGlRenderingContext, shader_type: u32, source: &str, ) -> Result<WebGlShader, String> { let shader = context .create_shader(shader_type) .ok_or_else(|| String::from("Unable to create shader object"))?; context.shader_source(&shader, source); context.compile_shader(&...
compile_shader
identifier_name
lib.rs
mod utils; use std::cell::RefCell; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{ImageData, WebGlProgram, WebGlRenderingContext, WebGlShader}; const WIDTH: i32 = 128; const HEIGHT: i32 = 128; const CHANNELS: i32 = 4; const BUFFER_SIZE: usize = ((WIDTH * HEIGHT) * CHANNELS) as ...
#[wasm_bindgen(start)] pub fn start() { utils::set_panic_hook(); log!("Hello there! Compositor canvas starting/loading"); } #[wasm_bindgen] pub fn initialise(element_id: String) -> Result<(), JsValue> { log!( "Compositor canvas (element_id: String = `{}`) initialisation", &element_id ...
{ window() .request_animation_frame(f.as_ref().unchecked_ref()) .expect("should register `requestAnimationFrame` OK"); }
identifier_body
async_stream_cdc.rs
// // Copyright (c) 2023 Nathan Fiedler // use super::*; #[cfg(all(feature = "futures", not(feature = "tokio")))] use futures::{ io::{AsyncRead, AsyncReadExt}, stream::Stream, }; #[cfg(all(feature = "tokio", not(feature = "futures")))] use tokio_stream::Stream; #[cfg(all(feature = "tokio", not(feature = "fu...
() { let array = [0u8; 1024]; AsyncStreamCDC::new(array.as_slice(), 64, 255, 1024); } #[test] #[should_panic] fn test_average_too_high() { let array = [0u8; 1024]; AsyncStreamCDC::new(array.as_slice(), 64, 268_435_457, 1024); } #[test] #[should_panic] fn...
test_average_too_low
identifier_name
async_stream_cdc.rs
// // Copyright (c) 2023 Nathan Fiedler // use super::*; #[cfg(all(feature = "futures", not(feature = "tokio")))] use futures::{ io::{AsyncRead, AsyncReadExt}, stream::Stream, }; #[cfg(all(feature = "tokio", not(feature = "futures")))] use tokio_stream::Stream; #[cfg(all(feature = "tokio", not(feature = "fu...
} Ok(all_bytes_read) } } /// Drains a specified number of bytes from the buffer, then resizes the /// buffer back to `capacity` size in preparation for further reads. fn drain_bytes(&mut self, count: usize) -> Result<Vec<u8>, Error> { // this code originally cop...
{ self.length += bytes_read; all_bytes_read += bytes_read; }
conditional_block
async_stream_cdc.rs
// // Copyright (c) 2023 Nathan Fiedler // use super::*; #[cfg(all(feature = "futures", not(feature = "tokio")))] use futures::{ io::{AsyncRead, AsyncReadExt}, stream::Stream, }; #[cfg(all(feature = "tokio", not(feature = "futures")))] use tokio_stream::Stream; #[cfg(all(feature = "tokio", not(feature = "fu...
max_size: usize, mask_s: u64, mask_l: u64, mask_s_ls: u64, mask_l_ls: u64, } impl<R: AsyncRead + Unpin> AsyncStreamCDC<R> { /// /// Construct a `StreamCDC` that will process bytes from the given source. /// /// Uses chunk size normalization level 1 by default. /// pub fn new...
/// True when the source produces no more data. eof: bool, min_size: usize, avg_size: usize,
random_line_split
run_mlm_my.py
import logging import os from dataclasses import dataclass, field from typing import Optional import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers...
: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch. """ model_name_or_path: Optional[str] = field( default=None, metadata={ "help": "The model checkpoint for weights initialization." "Don't set if you want ...
ModelArguments
identifier_name
run_mlm_my.py
import logging import os from dataclasses import dataclass, field from typing import Optional import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers...
revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, ) else: logger.info("Training new model from scratch") model = PairWiseBertForPreTraining.from_config(config) model.resize_token_embeddings(len(tokenizer)) # Get ...
model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path), config=config, cache_dir=model_args.cache_dir,
random_line_split
run_mlm_my.py
import logging import os from dataclasses import dataclass, field from typing import Optional import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers...
if model_args.model_name_or_path: model = PairWiseBertForPreTraining.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path), config=config, cache_dir=model_args.cache_dir, revision=model_args.model_r...
raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_name." )
conditional_block
run_mlm_my.py
import logging import os from dataclasses import dataclass, field from typing import Optional import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers...
@dataclass class DataTrainingArguments: """ Arguments pertaining to what data we are going to input our model for training and eval. """ dataset_name: Optional[str] = field( default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} ) dataset_config...
""" Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch. """ model_name_or_path: Optional[str] = field( default=None, metadata={ "help": "The model checkpoint for weights initialization." "Don't set if you want to tra...
identifier_body
titanic_keras_exp.py
"""Evaluate Keras Classifiers and learn from the Titanic data set.""" from sklearn.model_selection import StratifiedKFold from sklearn.pipeline import Pipeline from sklearn.dummy import DummyClassifier from pandas import read_csv # from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt import nump...
print() print() input("Press key to continue...") preprocessing = (encoding, scaler_tuple, featselector) if labels is not None: print("You have labels:", labels) all_models_and_parameters['labels'] = labels print("Defined dictionary with models...
print("'%s' is quicker than DummyClf." % best_model_name)
conditional_block
titanic_keras_exp.py
"""Evaluate Keras Classifiers and learn from the Titanic data set.""" from sklearn.model_selection import StratifiedKFold from sklearn.pipeline import Pipeline from sklearn.dummy import DummyClassifier from pandas import read_csv # from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt import nump...
# Feature-Feature Relationships # scatter_matrix(df) print() # too many missing values in 'Cabin' columns: about 3/4 print("Dropping 'Cabin' column -- too many missing values") # df.Cabin.replace(to_replace=np.nan, value='Unknown', inplace=True) df.drop(['Cabin'], axis=1, inplace=True) ...
plt.style.use('ggplot') # input("Enter key to continue... \n")
random_line_split
titanic_keras_exp.py
"""Evaluate Keras Classifiers and learn from the Titanic data set.""" from sklearn.model_selection import StratifiedKFold from sklearn.pipeline import Pipeline from sklearn.dummy import DummyClassifier from pandas import read_csv # from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt import nump...
(): is_valid = 0 choice = 0 while not is_valid: try: choice = int(input("Select cv method: [1] Classical CV, [2] Nested-CV?\n")) if choice in (1, 2): is_valid = 1 else: print("Invalid number. Try again...") except ValueErr...
select_cv_method
identifier_name
titanic_keras_exp.py
"""Evaluate Keras Classifiers and learn from the Titanic data set.""" from sklearn.model_selection import StratifiedKFold from sklearn.pipeline import Pipeline from sklearn.dummy import DummyClassifier from pandas import read_csv # from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt import nump...
# starting program if __name__ == '__main__': print("### Probability Calibration Experiment -- CalibratedClassifierCV " "with cv=cv (no prefit) ###") print() d_name = ga.get_name() if d_name is None: d_name = "titanic" # fix random seed for reproducibility seed = 7 n...
is_valid = 0 choice = 0 while not is_valid: try: choice = int(input("Select cv method: [1] Classical CV, [2] Nested-CV?\n")) if choice in (1, 2): is_valid = 1 else: print("Invalid number. Try again...") except ValueError as e: ...
identifier_body
AUTO_ASSAM_PART3.py
#!/usr/bin/env python # -*- coding: utf-8 -*- #A program to parse user.LP import itertools, sys, os, subprocess, shutil, glob, numpy as np, re, collections, operator, datetime, optparse, csv #import Bio trans = {'ALA':'A','CYS':'C','CYH':'C','CSS':'C','ASP':'D','GLU':'E','PHE':'F','GLY':'G','HIS':'H','ILE':'I','LYS':'K...
(): pdbs_to_edit = [i for i in glob.glob("BINDING_SITES_CLUSTERS/*.pdb")] pdbs_to_edit2 = [[i]+[i.split("/")[-1].split("_")[0].lower()] for i in pdbs_to_edit] d_dct = collections.defaultdict(list) for n in pdbs_to_edit2: d_dct[n[1]].append(n[0]) keys = sorted([key for key in d_dct.keys()]) for key in keys: for ...
rename_pdb_dbs
identifier_name
AUTO_ASSAM_PART3.py
#A program to parse user.LP import itertools, sys, os, subprocess, shutil, glob, numpy as np, re, collections, operator, datetime, optparse, csv #import Bio trans = {'ALA':'A','CYS':'C','CYH':'C','CSS':'C','ASP':'D','GLU':'E','PHE':'F','GLY':'G','HIS':'H','ILE':'I','LYS':'K','LEU':'L','MET':'M','ASN':'N','PRO':'P','GLN...
#!/usr/bin/env python # -*- coding: utf-8 -*-
random_line_split
AUTO_ASSAM_PART3.py
#!/usr/bin/env python # -*- coding: utf-8 -*- #A program to parse user.LP import itertools, sys, os, subprocess, shutil, glob, numpy as np, re, collections, operator, datetime, optparse, csv #import Bio trans = {'ALA':'A','CYS':'C','CYH':'C','CSS':'C','ASP':'D','GLU':'E','PHE':'F','GLY':'G','HIS':'H','ILE':'I','LYS':'K...
else: het_res = ";".join(het_resx) else: het_res = "None" else: het_res = "None" return het_res #BINDING_INTERFACES_ASSAM def save_output_binding_interfaces_assam(): pdb_dict=collections.defaultdict(list) pdb_new_dict=collections.defaultdict(list) pdbs_all=[["_".join(i.split("/")[-1].split("_")[:3]).upper()...
het_res = "None"
conditional_block
AUTO_ASSAM_PART3.py
#!/usr/bin/env python # -*- coding: utf-8 -*- #A program to parse user.LP import itertools, sys, os, subprocess, shutil, glob, numpy as np, re, collections, operator, datetime, optparse, csv #import Bio trans = {'ALA':'A','CYS':'C','CYH':'C','CSS':'C','ASP':'D','GLU':'E','PHE':'F','GLY':'G','HIS':'H','ILE':'I','LYS':'K...
#BINDING_INTERFACES_EXACT def binding_interfaces_exact(): csv_readerx=csv.reader(open("BINDING_INTERFACES_CLUSTERS.csv","r"),delimiter=",") rowsx=[[row[0]]+[row[8]] for row in csv_readerx] dreposer_id_dict=collections.defaultdict(list) for r in rowsx: dreposer_id_dict[r[0]].append(len(r[1].split(";"))) csv_re...
pdb_dict=collections.defaultdict(list) pdb_new_dict=collections.defaultdict(list) pdbs_all=[["_".join(i.split("/")[-1].split("_")[:3]).upper()]+[i.split("/")[-1].replace(".pdb","")] for i in glob.glob("renew_bs_finalized/*.pdb")] for pdb in pdbs_all: pdb_dict[pdb[0]].append(pdb[1]) for k in pdb_dict.keys(): for i...
identifier_body
town.py
########################################### """ Town manager """ # Imports import os import time import items import storyline import classes # Functions def shop_inventory(): pass def ultimate(player): texts = [ "Oh my...can it possibly be?...the legendary ore...Unobtainium?\n", "I can\'t...
time.sleep(1) os.system('cls' if os.name == 'nt' else 'clear') def town(player, wmap): os.system('cls' if os.name == 'nt' else 'clear') locations = [blacksmith, armory, alchemist, jeweler, church, tavern] town_options = [('Blacksmith', 0), ('Armory', 1), ('Alchemist', 2), ('Jeweler', 3), ...
print("Please enter a valid option.")
conditional_block
town.py
########################################### """ Town manager """ # Imports import os import time import items import storyline import classes # Functions def shop_inventory(): pass def ultimate(player): texts = [ "Oh my...can it possibly be?...the legendary ore...Unobtainium?\n", "I can\'t...
else: locations[town_index](player) os.system('cls' if os.name == 'nt' else 'clear')
player.status() elif town_options[town_index][0] == 'Church': locations[town_index](player, wmap)
random_line_split
town.py
########################################### """ Town manager """ # Imports import os import time import items import storyline import classes # Functions def shop_inventory(): pass def ultimate(player): texts = [ "Oh my...can it possibly be?...the legendary ore...Unobtainium?\n", "I can\'t...
def jeweler(player): os.system('cls' if os.name == 'nt' else 'clear') shop_text = "Come glimpse the finest jewelry in the land." buy_list = [('Accessory', 0)] shop(player, buy_list, shop_text) def tavern(player): """ Quests """ print("Sorry but we are closed for construction. Come b...
os.system('cls' if os.name == 'nt' else 'clear') shop_text = "Welcome to Ye Olde Item Shoppe." buy_list = [('Potion', 0), ('Misc', 1)] shop(player, buy_list, shop_text)
identifier_body
town.py
########################################### """ Town manager """ # Imports import os import time import items import storyline import classes # Functions def shop_inventory(): pass def ultimate(player): texts = [ "Oh my...can it possibly be?...the legendary ore...Unobtainium?\n", "I can\'t...
(player): os.system('cls' if os.name == 'nt' else 'clear') shop_text = "I have the finest armors for sale. Come in and look around." buy_list = [('Armor', 0)] shop(player, buy_list, shop_text) def alchemist(player): os.system('cls' if os.name == 'nt' else 'clear') shop_text = "Welcome to Ye Ol...
armory
identifier_name
impl_encryption.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use openssl::hash::{self, MessageDigest}; use tidb_query_codegen::rpn_fn; use tidb_query_datatype::expr::{Error, EvalContext}; use tidb_query_common::Result; use tidb_query_datatype::codec::data_type::*; use tidb_query_shared_expr::rand::{gen_random_...
KV", "*cca644408381f962dba8dfb9889db1371ee74208"), ("Pingcap", "*f33bc75eac70ac317621fbbfa560d6251c43cf8a"), ("rust", "*090c2b08e0c1776910e777b917c2185be6554c2e"), ("database", "*02e86b4af5219d0ba6c974908aea62d42eb7da24"), ("raft", "*b23a77787ed44e62ef2570f03ce8982d119fb6...
identifier_body
impl_encryption.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use openssl::hash::{self, MessageDigest}; use tidb_query_codegen::rpn_fn; use tidb_query_datatype::expr::{Error, EvalContext}; use tidb_query_common::Result; use tidb_query_datatype::codec::data_type::*; use tidb_query_shared_expr::rand::{gen_random_...
(b"abc".to_vec(), "900150983cd24fb0d6963f7d28e17f72"), (b"123".to_vec(), "202cb962ac59075b964b07152d234b70"), ( "你好".as_bytes().to_vec(), "7eca689f0d3389d9dea66ae112e5cfd7", ), ( "分布式データベース".as_bytes().to_vec(), ...
(vec![], "d41d8cd98f00b204e9800998ecf8427e"), (b"a".to_vec(), "0cc175b9c0f1b6a831c399e269772661"), (b"ab".to_vec(), "187ef4436122d1cc2f40dc2b92f0eba0"),
random_line_split