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 |
|---|---|---|---|---|
tax_task.py | _true', help='use position embed or not')
parser.add_argument('--position_embed_size', type=int, default=100, help='position embed size')
parser.add_argument('--position_embed_mode', type=str, default='sum', choices=['sum','concat'], help='position embed mode[sum,concat]')
parser.add_argument('--self_attention_units',... | if prob >= 0.5:
train_pred_output.append(1)
else:
train_pred_output.append(0)
end_time = time.time()
elapsed_time = (end_time - start_time) / 60
train_acc, train_prec, train_recall, train_f1 = metrics_non_multi(train_real_output, train_pre... | 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 | _true', help='use position embed or not')
parser.add_argument('--position_embed_size', type=int, default=100, help='position embed size')
parser.add_argument('--position_embed_mode', type=str, default='sum', choices=['sum','concat'], help='position embed mode[sum,concat]')
parser.add_argument('--self_attention_units',... |
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 | -label classification or not')
parser.add_argument('--epochs', type=int, default=10, help='epochs')
parser.add_argument('--focal_loss', action='store_false', help='use focal loss')
parser.add_argument('--focal_loss_alpha', type=float, default=0.6, help='focal loss alpha')
parser.add_argument('--focal_loss_gamma', type... | 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 |
/// 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 | 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_targets = vec!();
for (order... |
}
}
/// 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 | 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_targets = vec!();
for (order... | 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 | (&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 | Self {
Self {
config: Some(Box::new(config)),
functions,
}
}
/// Constructs a built-in program
pub fn new_builtin(functions: FunctionRegistry<BuiltinFunction<C>>) -> Self {
Self {
config: None,
functions,
}
}
/// Cons... | {
/// 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 | TestContextObject {
/// 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]) {
... | {
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 | _elf_parser: bool,
/// Use aligned memory mapping
pub aligned_memory_mapping: bool,
/// Allow ExecutableCapability::V1
pub enable_sbpf_v1: bool,
/// Allow ExecutableCapability::V2
pub enable_sbpf_v2: bool,
}
impl Config {
/// Returns the size of the stack memory region
pub fn stack_size... | pub debug_port: Option<u16>,
} | random_line_split | |
vm.rs | .as_slice();
if jit.len() > interpreter.len() {
jit = &jit[0..interpreter.len()];
}
interpreter == jit
}
}
/// Statistic of taken branches (from a recorded trace)
pub struct DynamicAnalysis {
/// Maximal edge counter value
pub edge_counter_max: usize,
/// src_node, d... | {
#[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 | 32];
h.input(secret_key.as_bytes());
hash.copy_from_slice(h.fixed_result().as_slice());
digest = array_mut_ref!(&mut hash, 0, 32);
digest[0] &= 248;
digest[31] &= 127;
digest[31] |= 64;
pk = (&Scalar(*digest) * &constants::ED25519_BASEPOINT_TABLE).compress().... | ify() { // | identifier_name | |
ed25519.rs | _bytes(bytes: &[u8]) -> SecretKey {
SecretKey(*array_ref!(bytes, 0, SECRET_KEY_LENGTH))
}
/// Generate a `SecretKey` from a `csprng`.
///
/// # Example
///
/// ```
/// extern crate rand;
/// extern crate sha2;
/// extern crate ed25519_dalek;
///
/// # fn main() {
... | 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 | _bytes(bytes: &[u8]) -> SecretKey {
SecretKey(*array_ref!(bytes, 0, SECRET_KEY_LENGTH))
}
/// Generate a `SecretKey` from a `csprng`.
///
/// # Example
///
/// ```
/// extern crate rand;
/// extern crate sha2;
/// extern crate ed25519_dalek;
///
/// # fn main() {
... | /// 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 | 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 | (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 |
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 | dir = "/"
}
names := make([]string, 0, len(afs.Files))
dirRaw := dir
dir = path.Clean(dir)
if dir != "/" && strings.HasSuffix(dirRaw, "/") {
dir += string(filepath.Separator)
}
dir = filepath.ToSlash(dir)
for name := range afs.Files {
if strings.HasPrefix(name, dir) {
names = append(names, name)
}... | 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 |
// 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 | "related" objects to be augmented
index (str): token index of related word
connector (str): if related word is cousin of unit (not sibling) then connecter is word between
Returns:
list: all related words for a given measurement (augmented with new 'related' passed in)
"""
doc = {}
... | (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 |
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 | simplified["related"] = {}
if "quantified" in match:
if simplified["unit"] == "":
simplified["unit"] = match["quantified"]["normalizedName"]
simplified["quantified"][match["quantified"]["normalizedName"]] = []
if "descriptors" in match["quantified"]:
match["quant... | random_line_split | ||
Measurements.py | ():
connector = None
if isinstance(dep_obj[pos_logic], dict):
for pos in dep_obj[pos_logic].keys():
# Check for allowed part of speech tags in matched dependency patterns
if (pos_logic == "pos_in" and pos in G.nodes[sibling_idx]["pos"]) o... | 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 | (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 | 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 | ER_GUID
};
let offline_installer_path = tauri_tools_path
.join("Webview2OfflineInstaller")
.join(guid)
.join(arch);
create_dir_all(&offline_installer_path)?;
let webview2_installer_path =
offline_installer_path.join("MicrosoftEdgeWebView2RuntimeInstaller.exe");
... | {
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 | mu".
toBeScheduledClusterOperations chan ClusterOperationInstance
// Guarded by "mu".
state schedulerState
// Guarded by "taskCreatorMu". May be overridden by testing code.
taskCreator taskCreator
taskCreatorMu sync.Mutex
pendingOpsWg *sync.WaitGroup
muOpList sync.Mutex
// Guarded by "muOpList".
// The k... |
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 | mu".
toBeScheduledClusterOperations chan ClusterOperationInstance
// Guarded by "mu".
state schedulerState
// Guarded by "taskCreatorMu". May be overridden by testing code.
taskCreator taskCreator
taskCreatorMu sync.Mutex
pendingOpsWg *sync.WaitGroup
muOpList sync.Mutex
// Guarded by "muOpList".
// The k... |
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 | mu".
toBeScheduledClusterOperations chan ClusterOperationInstance
// Guarded by "mu".
state schedulerState
// Guarded by "taskCreatorMu". May be overridden by testing code.
taskCreator taskCreator
taskCreatorMu sync.Mutex
pendingOpsWg *sync.WaitGroup
muOpList sync.Mutex
// Guarded by "muOpList". | // 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 | } else {
MarkTaskSucceeded(taskProto, output)
}
if newTaskContainers != nil {
// Make sure all new tasks do not miss any required parameters.
err := s.validateTaskContainers(newTaskContainers)
if err != nil {
err = vterrors.Wrapf(err, "task: %v (%v/%v) emitted a new task which is not vali... | ShutdownAndWait | identifier_name | |
index.js | onParentPriorityChange(priority, _parent) {
// Assume we only have one parent.
this.priority = priority + 1;
}
_attach() {}
_detach() {}
/** Notify observers of a change to our value */
_onChange(value, idle) {
if (idle === void 0) {
idle = false;
}
// Clone "_... | if (context) {
Animated.context = context;
}
| random_line_split | |
index.js | ._priority != priority) {
this._priority = priority;
this._onPriorityChange(priority);
}
}
/** Get the current value */
get() {
// The node doesn't exist until the first update, which normally isn't an
// issue but it can be for tests.
return this.node && this.node.getVa... | () {
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 | ._priority != priority) {
this._priority = priority;
this._onPriorityChange(priority);
}
}
/** Get the current value */
get() {
// The node doesn't exist until the first update, which normally isn't an
// issue but it can be for tests.
return this.node && this.node.getVa... |
});
}
/** 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 |
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 | # 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),
transforms.Rando... |
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 | # 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),
transforms.Rando... | 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 | (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 | mailchimp for list id " + list_id)
else:
logger.info(
"cleared " + str(delete_count) + " out of " + str(
active_subscribed.count()) + " for list id " + list_id)
if active_subscribed.count() == add_count:
logger.info("successfully synced all subscriptions for ... |
@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 | mailchimp for list id " + list_id)
else:
logger.info(
"cleared " + str(delete_count) + " out of " + str(
active_subscribed.count()) + " for list id " + list_id)
if active_subscribed.count() == add_count:
logger.info("successfully synced all subscriptions for ... | uq.save()
if u.first_name and u.last_name:
sal_name = '{} {}'.format(u.first_name, u.last_name)
elif u.first_name:
sal_name = u.first_name
elif u.last_name:
sal_name = u.last_name
... | 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 | mailchimp for list id " + list_id)
else:
logger.info(
"cleared " + str(delete_count) + " out of " + str(
active_subscribed.count()) + " for list id " + list_id)
if active_subscribed.count() == add_count:
logger.info("successfully synced all subscriptions for ... | (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 | mailchimp for list id " + list_id)
else:
logger.info(
"cleared " + str(delete_count) + " out of " + str(
active_subscribed.count()) + " for list id " + list_id)
if active_subscribed.count() == add_count:
logger.info("successfully synced all subscriptions for ... | 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 | effects', 30],
],
name: ' ',
//data:[50,40],
dataLabels: {
rotation: 270,
enabled: false,
format: '{series.name}: <b>{series.percentage:.1f}%</b>',
}
}],
title: {
text: 'Medicine Details'
},
tooltip: {
... | $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 | $scope.phLogin = function() {
var huser=$scope.phform.username;
var phpass=$scope.phform.password;
var phuser=huser.toLowerCase();
if(phuser.substr(0,8)=="pharmacy" && phpass=="pharmacy123")
$state.go("pharmacy.dash");
else
document.getElementById("phErr").innerHTML="Invalid Credentials"... | {
return contacts[i];
} | conditional_block | |
mamikon.js | />>>>>>>>>>>>>>>>>>>>>>*/
/* filter >>>>>>>>>>>>>>>>>>>>>>*/
var closestsElementClass = function (elem, className) {
var node = elem;
while (node) {
if (node.classList.contains(className)) {
return node; //класс есть — значит его и возвращаем, прекращая функцию
}
node = node.parentElement;
}
r... | up = clos | identifier_name | |
mamikon.js | Arrow.addEventListener('click', function () {
changeSlideLeft()
})
/* Slider />>>>>>>>>>>>>>>>>>>*/
/* carousel >>>>>>>>>>>>>>>>>>>*/
var root = document.documentElement;
var carouselElementsDisplayed = getComputedStyle(root).getPropertyValue("--carousel-elements-displayed");
var carouselContent = document.qu... | //Поиск названия data-popup, который задан у кнопки бургера
//var popupClass = target.getAttribute('data-popup');
var popupClass | var target = e.target; | random_line_split |
mamikon.js | -displayed");
var carouselContent = document.querySelector("ul.carousel-content");
root.style.setProperty("--carousel-elements", carouselContent.children.length);
for (var i = 0; i < carouselElementsDisplayed; i++) {
carouselContent.appendChild(carouselContent.children[i].cloneNode(true));
}
/* carousel />>>>... | data-popup');
//если элемент, на котором кликнули, не имеет аттрибут data-popup, то выходим
if (popupClass === null) {
r | conditional_block | |
mamikon.js | 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 | .removeChild(this.m_BeanView);
gameLayer.removeChild(this.m_FlyBeanContainer);
gameLayer.removeChild(this.m_SlitherContainer);
this.allNames = {};
this.m_TileBackground = null;
this.m_BeanView = null;
this.m_FlyBeanContainer = null;
this.m_SlitherContainer = null;
}
public StopTweenCamera()
... | date(deltaTime);
this.LateUpdate(deltaTime);
| conditional_block | |
GameScene.ts | Size:number;
private m_LastOrthoSizeTarget:number;
private m_CurrOrthoSizeTarget:number;
private m_CameraViewAnimDuration:number = 1.0;
private m_CameraViewFactor:number = 1.0;
protected m_Time:number;
protected m_Radius:number;
protected allNames:Object = new Object();
protected m_PlayerNameInfo:NameIn... | 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 | Size:number;
private m_LastOrthoSizeTarget:number;
private m_CurrOrthoSizeTarget:number;
private m_CameraViewAnimDuration:number = 1.0;
private m_CameraViewFactor:number = 1.0;
protected m_Time:number;
protected m_Radius:number;
protected allNames:Object = new Object();
protected m_PlayerNameInfo:NameIn... | sg:RpcSlitherBirthDeathSync)
{
let foundPlayer = false;
let count = msg.slithers.length;
for (let i | SlitherBirthDeathSync(m | identifier_name |
GameScene.ts | Size:number;
private m_LastOrthoSizeTarget:number;
private m_CurrOrthoSizeTarget:number;
private m_CameraViewAnimDuration:number = 1.0;
private m_CameraViewFactor:number = 1.0;
protected m_Time:number;
protected m_Radius:number;
protected allNames:Object = new Object();
protected m_PlayerNameInfo:NameIn... |
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 | , a warning to indicate as such
//! pub const WARNING: Option<Warning> = ...;
//!
//! // Given a file that we know starts with the correct version prefix, parse it
//! //
//! // If any errors are encountered, print them and exit.
//! pub fn parse(file_content: String) -> FileContent { ... }
//! ```
//! Those are used b... | /// 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 | ) -> Result<Box<CurrentFileContent>, DecryptError>;
/// Provides the string that the file content should be written as
///
/// This method is provided -- instead of directly writing to the file -- so that no error
/// handling needs to be done within the implementation itself.
fn write(&self) -> St... | {
PlaintextContent {
last_update: SystemTime::now(),
entries: Vec::new(),
}
} | identifier_body | |
mod.rs | , a warning to indicate as such
//! pub const WARNING: Option<Warning> = ...;
//!
//! // Given a file that we know starts with the correct version prefix, parse it
//! //
//! // If any errors are encountered, print them and exit.
//! pub fn parse(file_content: String) -> FileContent { ... }
//! ```
//! Those are used b... |
};
macro_rules! prefix_match {
($val:expr => { $($str:literal => $arm:expr,)* _ => $else_arm:expr, | {
eprintln!("failed to read file {:?}: {}", file.to_string_lossy(), e);
exit(1);
} | conditional_block |
mod.rs | , a warning to indicate as such
//! pub const WARNING: Option<Warning> = ...;
//!
//! // Given a file that we know starts with the correct version prefix, parse it
//! //
//! // If any errors are encountered, print them and exit.
//! pub fn parse(file_content: String) -> FileContent { ... }
//! ```
//! Those are used b... | {
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 | }
}
//we're going to split up the month by weeks! See what happens
let monthData = function(year, month) {
let censusArray = sealCensus[year][month];
let censuses = {
week1: [],
week2: [],
week3: [],
week4: []
};
//assign censuses to weeks
... | .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 | dataLocation = generalLocation(census.location);
data = census.sealCensusLong;
}
else {
data = census;
}
data = fixData(data, dataLocation);
console.log("Extracted data for the force simulation: ");
console.log(data);
let xPadding = width/10;
let yPa... | fixData | identifier_name | |
draw.js | ensuses;
});
}
//Add circles where the seals are!
// Create SVG element
let width = 1000;
let height = 500;
var addSVG = function() {
debug("in addSVG()");
let row = -1;
//create svg element
var svg = d3.select("#chart")
.append("svg")
.attr("width", width)
.a... | {
circles
.attr("cx", d => d.x)
.attr("cy", d => d.y)
} | identifier_body | |
draw.js | %12 < 0 ? sliderValue%12 : 12;
var dataLocation;
var data;
var noCensus = false;
//var data = sealCensus[dataYear][dataMonth];
let censusArray = sealCensus[dataYear][dataMonth];
let census;
if(censusArray != undefined && censusArray != "undefined") {
census = censusArray[... | {
return height/4;
} | conditional_block | |
main.rs | ::with_name("find")
.short("f")
.long("find")
.value_name("METHOD")
.default_value("any")
.possible_values(&["any", "all"])
.help("Whether to find *all* paths for each graph or *any* path for each graph"))
.get_matches();
let start_tim... | (
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 | ::with_name("find")
.short("f")
.long("find")
.value_name("METHOD")
.default_value("any")
.possible_values(&["any", "all"])
.help("Whether to find *all* paths for each graph or *any* path for each graph"))
.get_matches();
let start_tim... |
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 | ::with_name("find")
.short("f")
.long("find")
.value_name("METHOD")
.default_value("any")
.possible_values(&["any", "all"])
.help("Whether to find *all* paths for each graph or *any* path for each graph"))
.get_matches();
let start_tim... | 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 | 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 |
# 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 | for i in range(nb_layers):
angle = alpha0 - (res_alpha * i)
angle_rad = ((90-angle) * np.pi) / 180.0
radius = int(np.round(abs(h_scanner * np.tan(angle_rad) * res_x)))
if radius > (im.getWidth() + im.getHeight()):
radius_index[i] = max(im.getWidth(), im.getHeight())
... | """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 | (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 | .angle = 0
self.torque = 0
def set_vel(self, vel):
self.state[2] = vel
return self
def update(self, dt):
self.t += dt
def draw(self, surface):
self.angle += self.state[2]
for i in range(0,316, 45):
x = self.center[0] + math.cos(ma... | while True:
# 30 fps
if not pause:
clock.tick(30)
| random_line_split | |
particle.py | ,y), 5))
else:
self.lines[i/45] = pygame.draw.line(surface, BLACK, self.center, (x,y), 5)
self.circle = pygame.draw.circle(surface, BLACK, self.center, (int)(self.radius*.7), 10)
def pprint(self):
print 'Wheel', self.state
class World:
def __init__(sel... | 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 | = vel
return self
def update(self, dt):
self.t += dt
self.state[3] += dt * self.gravity
self.state[0] += self.state[2] * dt
self.state[1] += self.state[3] * dt
def move_by(self, delta):
self.state[0:2] = np.add(self.pos, delta)
return self
def ... |
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 | vel
return self
def update(self, dt):
self.t += dt
self.state[3] += dt * self.gravity
self.state[0] += self.state[2] * dt
self.state[1] += self.state[3] * dt
def move_by(self, delta):
self.state[0:2] = np.add(self.pos, delta)
return self
def dr... | (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 | "Busqueda rapida: ",
oPaginate: {
"sFirst": "Primero",
"sLast": "Último",
"sNext": "Siguiente",
"sPrevious": "Anterior"
}
},
lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "Todos"]],
function(start, end, label... | //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 | Names: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'
],
monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun',
'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'
],
d... | rBitacoras(idVe | identifier_name | |
peticiones_bitacora.js | dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mié', 'Juv', 'Vie', 'Sáb'],
dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'],
weekHeader: 'Sm',
dateForma... | motivo = "--";
} else {
motivo = data[i].motivo;
}
tabla.fnAddData([
data[i].vendedor,
data[i].descripcion,
clientRazonS,
visita,
motivo,
... | 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 | dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mié', 'Juv', 'Vie', 'Sáb'],
dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'],
weekHeader: 'Sm',
dateForma... |
},
{
"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 | .0, // Top right
-1.0, 1.0, 0.0, // Top left
];
fn window() -> web_sys::Window {
web_sys::window().expect("no global `window` exists")
}
fn request_animation_frame(f: &Closure<dyn FnMut()>) {
window()
.request_animation_frame(f.as_ref().unchecked_ref())
.expect("should register `requestAni... | {
Ok(shader)
} | conditional_block | |
lib.rs | 8] = [
-1.0, -1.0, 0.0, // Bottom left
1.0, -1.0, 0.0, // Bottem right
1.0, 1.0, 0.0, // Top right
-1.0, -1.0, 0.0, // Bottom left
1.0, 1.0, 0.0, // Top right
-1.0, 1.0, 0.0, // Top left
];
fn window() -> web_sys::Window {
web_sys::window().expect("no global `window` exists")
}
fn request_... | 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 | ] = [
-1.0, -1.0, 0.0, // Bottom left
1.0, -1.0, 0.0, // Bottem right
1.0, 1.0, 0.0, // Top right
-1.0, -1.0, 0.0, // Bottom left
1.0, 1.0, 0.0, // Top right
-1.0, 1.0, 0.0, // Top left
];
fn window() -> web_sys::Window {
web_sys::window().expect("no global `window` exists")
}
fn request_a... | (
context: &WebGlRenderingContext,
shader_type: u32,
source: & | compile_shader | identifier_name |
lib.rs | ] = [
-1.0, -1.0, 0.0, // Bottom left
1.0, -1.0, 0.0, // Bottem right
1.0, 1.0, 0.0, // Top right
-1.0, -1.0, 0.0, // Bottom left
1.0, 1.0, 0.0, // Top right
-1.0, 1.0, 0.0, // Top left
];
fn window() -> web_sys::Window {
web_sys::window().expect("no global `window` exists")
}
fn request_a... |
#[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 | )]
/// # use tokio_stream::StreamExt;
///
/// async fn run() {
/// let source = std::fs::read("test/fixtures/SekienAkashita.jpg").unwrap();
/// let mut chunker = AsyncStreamCDC::new(source.as_ref(), 4096, 16384, 65535);
/// let stream = chunker.as_stream();
///
/// let chunks = stream.collect::<Vec<_>>(... | () {
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 | )]
/// # use tokio_stream::StreamExt;
///
/// async fn run() {
/// let source = std::fs::read("test/fixtures/SekienAkashita.jpg").unwrap();
/// let mut chunker = AsyncStreamCDC::new(source.as_ref(), 4096, 16384, 65535);
/// let stream = chunker.as_stream();
///
/// let chunks = stream.collect::<Vec<_>>(... |
}
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 | )]
/// # use tokio_stream::StreamExt;
///
/// async fn run() {
/// let source = std::fs::read("test/fixtures/SekienAkashita.jpg").unwrap();
/// let mut chunker = AsyncStreamCDC::new(source.as_ref(), 4096, 16384, 65535);
/// let stream = chunker.as_stream();
///
/// let chunks = stream.collect::<Vec<_>>(... | 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 | ,
set_seed,
)
from transformers.trainer_utils import is_main_process
from mydatasets import BERTPretrainedPairWiseDataset, PairCollator
from mymodels import PairWiseBertForPreTraining
logger = logging.getLogger(__name__)
MODEL_CONFIG_CLASSES = list(MODEL_FOR_MASKED_LM_MAPPING.keys())
MODEL_TYPES = tuple(conf.model... | :
"""
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 | ,
set_seed,
)
from transformers.trainer_utils import is_main_process
from mydatasets import BERTPretrainedPairWiseDataset, PairCollator
from mymodels import PairWiseBertForPreTraining
logger = logging.getLogger(__name__)
MODEL_CONFIG_CLASSES = list(MODEL_FOR_MASKED_LM_MAPPING.keys())
MODEL_TYPES = tuple(conf.model... | 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 | ,
set_seed,
)
from transformers.trainer_utils import is_main_process
from mydatasets import BERTPretrainedPairWiseDataset, PairCollator
from mymodels import PairWiseBertForPreTraining
logger = logging.getLogger(__name__)
MODEL_CONFIG_CLASSES = list(MODEL_FOR_MASKED_LM_MAPPING.keys())
MODEL_TYPES = tuple(conf.model... |
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 | ,
set_seed,
)
from transformers.trainer_utils import is_main_process
from mydatasets import BERTPretrainedPairWiseDataset, PairCollator
from mymodels import PairWiseBertForPreTraining
logger = logging.getLogger(__name__)
MODEL_CONFIG_CLASSES = list(MODEL_FOR_MASKED_LM_MAPPING.keys())
MODEL_TYPES = tuple(conf.model... | )
cache_dir: Optional[str] = field(
default=None,
metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
)
use_fast_tokenizer: bool = field(
default=True,
metadata={"help": "Whether to use one of the fast tokenizer (backed by... | """
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 | except Exception as e:
raise e
# data exploration
print("shape: ", df.shape)
# statistical summary
description = df.describe()
print("description - no encoding:\n", description)
print()
plt.style.use('ggplot')
# input("Enter key to continue... \n")
# Feature-Featur... | print("'%s' is quicker than DummyClf." % best_model_name) | conditional_block | |
titanic_keras_exp.py |
else:
print("Invalid number. Try again...")
except ValueError as e:
print("'%s' is not a valid integer." % e.args[0].split(": ")[1])
return choice
# starting program
if __name__ == '__main__':
print("### Probability Calibration Experiment -- CalibratedClassif... | # 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 | ():
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 |
# 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 | 0]].append(d[1]+"("+d[2]+")")
dict_indication_mappings[d[0]].append(d[3])
#dictionary of source organism
dict_source_mappings = collections.defaultdict(list)
for s in rows2: dict_source_mappings[s[0].lower()+s[1]].append(s[3])
#dictionary of pdb-macromolecule mappings
dict_macromolecule_mappings = collections.de... | 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 | ','CA ','CB ','CG ','OD1','ND2'),"PRO":('N ','C ','O ','CA ','CB ','CG ','CD '),"GLN":('N ','C ','O ','CA ','CB ','CG ','CD ','OE1','NE2'),"ARG":('N ','C ','O ','CA ','CB ','CG ','CD ','NE ','CZ ','NH1','NH2'),
"SER":('N ','C ','O ','CA ','CB ','OG '),"THR":('N ','C ','O ','CA ','CB ','OG1',... |
else: het_res = ";".join(het_resx)
else: het_res = "None"
else: het_res = "None"
return het_res
#BINDING_INTERFACES_ASSAM
def | het_res = "None" | conditional_block |
AUTO_ASSAM_PART3.py | save_output_binding_interfaces():
csv_reader=csv.reader(open("pdbdescription.csv","r"),delimiter=",")
rows=[row for row in csv_reader][1:-2]
rows2=[row[:4]+[";".join(sorted(list(set([z+"("+y+")" for z,y in zip(list(set([n.split()[0] for n in row[4].split(", ")])),row[5].split(", "))])))) if row[4] != "" else "None"... | 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 | ]]
if type(weapon) == list:
if 'Archbishop' == player.cls:
weapon = weapon[0]
else:
weapon = weapon[1]
print("Give me a moment and I will make you an ultimate weapon...")
time.sleep(5)
print("I present to you, {}, the mighty {}!".fo... | print("Please enter a valid option.") | conditional_block | |
town.py | buy_list, shop_text)
def alchemist(player):
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)
def jeweler(player):
os.system('cls' if os.name == 'nt' else 'clear')
shop_tex... | player.status()
elif town_options[town_index][0] == 'Church':
locations[town_index](player, wmap) | random_line_split | |
town.py | Hammer': items.Skullcrusher,
'Ninja Blades': items.Ninjato}
make_list = []
i = 0
for typ, weapon in weapon_list.items():
if typ == 'Staff':
if 'Archbishop' == player.cls:
weapon = weapon[0]
else:
weapon = weapon[1]
if... |
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 | Hammer': items.Skullcrusher,
'Ninja Blades': items.Ninjato}
make_list = []
i = 0
for typ, weapon in weapon_list.items():
if typ == 'Staff':
if 'Archbishop' == player.cls:
weapon = weapon[0]
else:
weapon = weapon[1]
if... | (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 | Some("0C000000789CCB48CDC9C95728CF2F32303402001D8004202E"),
Some(12),
),
(Some("020000000000"), Some(2)),
(Some("0000000001"), Some(0)),
(
Some("02000000789CCB48CDC9C95728CF2FCA4901001A0B045D"),
Some(2),
),
... | KV", "*cca644408381f962dba8dfb9889db1371ee74208"),
("Pingcap", "*f33bc75eac70ac317621fbbfa560d6251c43cf8a"),
("rust", "*090c2b08e0c1776910e777b917c2185be6554c2e"),
("database", "*02e86b4af5219d0ba6c974908aea62d42eb7da24"),
("raft", "*b23a77787ed44e62ef2570f03ce8982d119fb6... | identifier_body | |
impl_encryption.rs | Result<Bytes> {
hash::hash(hashtype, input)
.map(|digest| hex::encode(digest).into_bytes())
.map_err(|e| box_err!("OpenSSL error: {:?}", e))
}
#[rpn_fn(nullable, capture = [ctx])]
#[inline]
pub fn uncompressed_length(ctx: &mut EvalContext, arg: Option<BytesRef>) -> Result<Option<Int>> {
use by... | (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 |
impl_encryption.rs | <Bytes> {
hash::hash(hashtype, input)
.map(|digest| hex::encode(digest).into_bytes())
.map_err(|e| box_err!("OpenSSL error: {:?}", e))
}
#[rpn_fn(nullable, capture = [ctx])]
#[inline]
pub fn uncompressed_length(ctx: &mut EvalContext, arg: Option<BytesRef>) -> Result<Option<Int>> {
use byteorder... | "pingcap", 0, "2871823be240f8ecd1d72f24c99eaa2e58af18b4b8ba99a4fc2823ba5c43930a"),
("pingcap", 224, "cd036dc9bec69e758401379c522454ea24a6327b48724b449b40c6b7"),
("pingcap", 256, "2871823be240f8ecd1d72f24c99eaa2e58af18b4b8ba99a4fc2823ba5c43930a"),
("pingcap", 384, "c50955b6b0c | ( | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.