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
planner.go
// Copyright 2016 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree" "github.com/cockroachdb/cockroach/pkg/sql/sessiondata" "github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb" "github.com/cockroachdb/cockroach/pkg/sql/types" "github.com/cockroachdb/cockroach/pkg/util/cancelchecker" "github.com/cockroachdb/cockroach/pkg/util/...
"github.com/cockroachdb/cockroach/pkg/sql/opt/exec" "github.com/cockroachdb/cockroach/pkg/sql/parser" "github.com/cockroachdb/cockroach/pkg/sql/querycache" "github.com/cockroachdb/cockroach/pkg/sql/rowenc" "github.com/cockroachdb/cockroach/pkg/sql/sem/transform"
random_line_split
planner.go
// Copyright 2016 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
// TypeAsStringArray enforces (not hints) that the given expressions all typecheck as // strings and returns a function that can be called to get the string values // during (planNode).Start. func (p *planner) TypeAsStringArray( ctx context.Context, exprs tree.Exprs, op string, ) (func() ([]string, error), error) { ...
{ typed := make(map[string]tree.TypedExpr, len(opts)) for _, opt := range opts { k := string(opt.Key) validate, ok := optValidate[k] if !ok { return nil, errors.Errorf("invalid option %q", k) } if opt.Value == nil { if validate == KVStringOptRequireValue { return nil, errors.Errorf("option %q req...
identifier_body
planner.go
// Copyright 2016 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
fn := func() ([]string, error) { strs := make([]string, len(exprs)) for i := range exprs { d, err := typedExprs[i].Eval(p.EvalContext()) if err != nil { return nil, err } str, ok := d.(*tree.DString) if !ok { return strs, errors.Errorf("failed to cast %T to string", d) } strs[i] = str...
{ typedE, err := tree.TypeCheckAndRequire(ctx, exprs[i], &p.semaCtx, types.String, op) if err != nil { return nil, err } typedExprs[i] = typedE }
conditional_block
builder.go
package account import ( "github.com/pkg/errors" "golang.org/x/text/currency" "gopkg.in/go-playground/validator.v9" ) type ( // Builder provides methods to create and validate account objects. /////// // I was after creating a Builder which would have compile time validation, // but as there was vast amount of...
// SetBaseCurrency - ISO 4217 code used to identify the base currency of the account, e.g. 'GBP', 'EUR' // Provide currency unit object from golang text library. func (opt *optionalAttributes) SetBaseCurrency(unit currency.Unit) *Builder { opt.Builder.optional.BaseCurrency = unit.String() return opt.Builder } // S...
{ opt.Builder.optional.VersionIndex = version return opt.Builder }
identifier_body
builder.go
package account import ( "github.com/pkg/errors" "golang.org/x/text/currency" "gopkg.in/go-playground/validator.v9" ) type ( // Builder provides methods to create and validate account objects. /////// // I was after creating a Builder which would have compile time validation, // but as there was vast amount of...
// SetSecondaryIdentification - Secondary identification, e.g. building society roll number. // Used for Confirmation of Payee. // Valid up to string[140] func (opt *optionalAttributes) SetSecondaryIdentification(secondaryID string) *Builder { opt.Builder.optional.SecondaryIdentification = secondaryID return opt.Bui...
}
random_line_split
builder.go
package account import ( "github.com/pkg/errors" "golang.org/x/text/currency" "gopkg.in/go-playground/validator.v9" ) type ( // Builder provides methods to create and validate account objects. /////// // I was after creating a Builder which would have compile time validation, // but as there was vast amount of...
return &Account{ id: b.essential.ID, organizationID: b.essential.OrganizationID, versionIndex: b.optional.VersionIndex, country: b.essential.Country, bankIDCode: b.essential.BankIDCode, bankID: b.essential.BankID, bic...
{ return nil, err }
conditional_block
builder.go
package account import ( "github.com/pkg/errors" "golang.org/x/text/currency" "gopkg.in/go-playground/validator.v9" ) type ( // Builder provides methods to create and validate account objects. /////// // I was after creating a Builder which would have compile time validation, // but as there was vast amount of...
(accountNumber string) *Builder { opt.Builder.optional.AccountNumber = accountNumber return opt.Builder } // SetVersion - version number of account object. Needs to be incremented when Patching an existing account. func (opt *optionalAttributes) SetVersion(version int) *Builder { opt.Builder.optional.VersionIndex =...
SetAccountNumber
identifier_name
mod.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
}
{ assert_eq!(Version::parse("1"), Err("1")); assert_eq!(Version::parse("1."), Err("1.")); assert_eq!(Version::parse("1 h3l1o. W0rld"), Err("1 h3l1o. W0rld")); assert_eq!(Version::parse("1. h3l1o. W0rld"), Err("1. h3l1o. W0rld")); assert_eq!(Version::parse("1.2.3"), Ok(Version(1, ...
identifier_body
mod.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
error!("Ignored unsupported GL Request: {}", request) } }, super::BindAttribute(slot, buffer, count, el_type, stride, offset) => { let gl_type = match el_type { a::Int(_, a::U8, a::Unsigned) => gl::UNSIGNED_BYTE, ...
} else {
random_line_split
mod.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
(src: &'static str) -> Result<Version, &'static str> { let (version, vendor_info) = match src.find(' ') { Some(i) => (src.slice_to(i), src.slice_from(i + 1)), None => (src, ""), }; // TODO: make this even more lenient so that we can also accept // `<major> "." <m...
parse
identifier_name
xform_anno.py
#! /usr/bin/python3 # # xform_anno.py - Utility to transform p4info annotations into first-class Message elements # # Copyright 2018-present Keysight Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtai...
(): parser = argparse.ArgumentParser(description='P4info transform utility', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=textwrap.dedent('''\ Either or both of infile, outfile can be omitted; a hyphen signifies stdin and stdout, respectively. Using -i none o...
get_arg_parser
identifier_name
xform_anno.py
#! /usr/bin/python3 # # xform_anno.py - Utility to transform p4info annotations into first-class Message elements # # Copyright 2018-present Keysight Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtai...
outfile.close()
random_line_split
xform_anno.py
#! /usr/bin/python3 # # xform_anno.py - Utility to transform p4info annotations into first-class Message elements # # Copyright 2018-present Keysight Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtai...
# Set document.description def set_doc_description(doc, value): doc.description = value; # Extract the string value embedded in an annotation # Asssumes just one string, surrounded by escaped quotes e.g. "\"string\"" def get_anno_value(anno): return anno.split('(\"')[1].split('\")')[0] # Detect @brief() and...
doc.brief = value;
identifier_body
xform_anno.py
#! /usr/bin/python3 # # xform_anno.py - Utility to transform p4info annotations into first-class Message elements # # Copyright 2018-present Keysight Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtai...
for counter in p4info.direct_counters: log_verbose("=== process direct_counter %s" % counter.preamble.name) xform_preamble_doc_annotations(counter) for meter in p4info.meters: log_verbose("=== process indirect meter %s" % meter.preamble.name) xform_preamble_doc_annotations(meter) for meter in p4info...
log_verbose("=== process indirect counter %s" % counter.preamble.name) xform_preamble_doc_annotations(counter)
conditional_block
admin.py
import asyncio import discord import importlib import os import re import subprocess import sys import time from discord.ext import commands from discord.utils import get from dotenv import load_dotenv import src.utils.cogfile_manage as cogManage import src.utils.help_function as helpFunction # Loads the ADMIN_LIST a...
print("[AdminCog.findPermission] Forbidden: authorID (" + str(authorID) + ") not found in adminList\n") for admin in ADMIN_LIST: print(admin) return False # Commands Methods ########################################################################################################...
print("[AdminCog.findPermission] Accepted") return True
conditional_block
admin.py
import asyncio import discord import importlib import os import re import subprocess import sys import time from discord.ext import commands from discord.utils import get from dotenv import load_dotenv import src.utils.cogfile_manage as cogManage import src.utils.help_function as helpFunction # Loads the ADMIN_LIST a...
ction for the cog def setup(bot): bot.add_cog(AdminCog(bot)) # Unload function for the cog def teardown(bot): bot.remove_cog(AdminCog(bot))
def __init__(self, bot): self.bot = bot self.adminList = ADMIN_LIST # Functions ########################################################################################################################################################### # runProcess: Used to run a terminal command async def ...
identifier_body
admin.py
import asyncio import discord import importlib import os import re import subprocess import sys import time from discord.ext import commands from discord.utils import get from dotenv import load_dotenv import src.utils.cogfile_manage as cogManage import src.utils.help_function as helpFunction # Loads the ADMIN_LIST a...
(self, ctx): print("[AdminCog.adminHelpCommand] Generating embed") # If it is, we use the generic help function to generate a embed # First we generate all needed fields cogName = "admin" cogDescription = "Admin tools to control bot cogs and updates" cogEmbed = 0xeb4034 ...
adminHelpCommand
identifier_name
admin.py
import asyncio import discord import importlib import os import re import subprocess import sys import time from discord.ext import commands from discord.utils import get from dotenv import load_dotenv import src.utils.cogfile_manage as cogManage import src.utils.help_function as helpFunction # Loads the ADMIN_LIST a...
# Setup function for the cog def setup(bot): bot.add_cog(AdminCog(bot)) # Unload function for the cog def teardown(bot): bot.remove_cog(AdminCog(bot))
] print("[AdminCog.adminHelpCommand] Sending embed\n") await helpFunction.generateHelpEmbed(ctx, cogName, cogDescription, helpList, cogEmbed) return
random_line_split
edit_ops.rs
// Copyright 2020 The xi-editor 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 ag...
<BT, AT>( base: &Rope, regions: &[SelRegion], before_text: BT, after_text: AT, ) -> RopeDelta where BT: Into<Rope>, AT: Into<Rope>, { let mut builder = DeltaBuilder::new(base.len()); let before_rope = before_text.into(); let after_rope = after_text.into(); for region in regions {...
surround
identifier_name
edit_ops.rs
// Copyright 2020 The xi-editor 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 ag...
else { None }; (delete_sel_regions(base, &deletions), kill_ring) } /// Deletes the given regions. pub(crate) fn delete_sel_regions(base: &Rope, sel_regions: &[SelRegion]) -> RopeDelta { let mut builder = DeltaBuilder::new(base.len()); for region in sel_regions { let iv = Interval::new...
{ let saved = extract_sel_regions(base, &deletions).unwrap_or_default(); Some(Rope::from(saved)) }
conditional_block
edit_ops.rs
// Copyright 2020 The xi-editor 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 ag...
/// Deletes the given regions. pub(crate) fn delete_sel_regions(base: &Rope, sel_regions: &[SelRegion]) -> RopeDelta { let mut builder = DeltaBuilder::new(base.len()); for region in sel_regions { let iv = Interval::new(region.min(), region.max()); if !iv.is_empty() { builder.delete...
{ // We compute deletions as a selection because the merge logic // is convenient. Another possibility would be to make the delta // builder able to handle overlapping deletions (with union semantics). let mut deletions = Selection::new(); for &r in regions { if r.is_caret() { le...
identifier_body
edit_ops.rs
// Copyright 2020 The xi-editor 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 ag...
fn outdent(base: &Rope, lines: BTreeSet<usize>, tab_text: &str) -> RopeDelta { let mut builder = DeltaBuilder::new(base.len()); for line in lines { let offset = LogicalLines.line_col_to_offset(base, line, 0); let tab_offset = LogicalLines.line_col_to_offset(base, line, tab_text.len()); ...
random_line_split
utils.py
import numpy as np from torch import nn import torch import os import sys from six.moves.urllib import request import shutil import contextlib import cv2 import matplotlib.pyplot as plt from PIL import Image import imageio med_frq = [0.382900, 0.452448, 0.637584, 0.377464, 0.585595, 0.479574, 0.781544, 0.9...
def depthImage2ptcloud(self, depth_img): [ifocal_length_x, ifocal_length_y, center_x, center_y, Rtilt] = self.getCameraInfo() ptCloud = np.zeros(shape=(int(depth_img.shape[0]), int(depth_img.shape[1]), 3), dtype=np.float32) for y in xrange(0, depth_img.shape[0]): for x ...
depthVisData = np.asarray(depthImage, np.uint16) depthInpaint = np.bitwise_or(np.right_shift(depthVisData, 3), np.left_shift(depthVisData, 16 - 3)) depthInpaint = depthInpaint.astype(np.single) / 1000 depthInpaint[depthInpaint > 8] = 8 return depthInpaint
identifier_body
utils.py
import numpy as np from torch import nn import torch import os import sys from six.moves.urllib import request import shutil import contextlib import cv2 import matplotlib.pyplot as plt from PIL import Image import imageio med_frq = [0.382900, 0.452448, 0.637584, 0.377464, 0.585595, 0.479574, 0.781544, 0.9...
return planes_img def fitPlaneImplicitLeastSquares(self, points): from numpy import linalg as LA plane3 = np.empty(shape=(4), dtype=np.float32) centroid = np.mean(points, 0) demeaned_pts3D = points - centroid _MtM = np.matmul(demeaned_pts3D.transpose(), demeaned_pts...
for x in range(0, depth_img.shape[1]-winsize, winsize): windowDepths = depth_img[y:(y + winsize + 1), x:(x + winsize + 1)] # print(windowDepths) numValidPoints = np.count_nonzero(~np.isnan(windowDepths)) # print(numValidPoints) if (numValid...
conditional_block
utils.py
import numpy as np from torch import nn import torch import os import sys from six.moves.urllib import request import shutil import contextlib import cv2 import matplotlib.pyplot as plt from PIL import Image import imageio med_frq = [0.382900, 0.452448, 0.637584, 0.377464, 0.585595, 0.479574, 0.781544, 0.9...
targets_m[mask] -= 1 # map the label from [1, 37] to [0, 36] loss_all = self.ce_loss(inputs, targets_m.long()) losses.append(torch.sum(torch.masked_select(loss_all, mask)) / torch.sum(mask.float())) total_loss = sum(losses) return total_loss def color_label(label):...
def forward(self, inputs_scales, targets_scales): losses = [] for inputs, targets in zip(inputs_scales, targets_scales): mask = targets > 1e-3 # should be larger than 0 but tensor seems to treat 0 as a very small number like 2e-9 then targets_m = targets.clone() # when we s...
random_line_split
utils.py
import numpy as np from torch import nn import torch import os import sys from six.moves.urllib import request import shutil import contextlib import cv2 import matplotlib.pyplot as plt from PIL import Image import imageio med_frq = [0.382900, 0.452448, 0.637584, 0.377464, 0.585595, 0.479574, 0.781544, 0.9...
(self, weight=med_frq): super(CrossEntropyLoss2d, self).__init__() self.ce_loss = nn.CrossEntropyLoss(torch.from_numpy(np.array(weight)).float(), reduction='none') def forward(self, inputs_scales, targets_scales): losses = [] for inputs, ta...
__init__
identifier_name
app.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; import { Subscription } from 'rxjs/Subscription'; import 'rxjs/add/operator/filter'; import { UserModel } from 'app/user/user.model'; import { AuthService } from 'app/core/auth.service'; import { Mess...
} } // app-routing.module { path: 'foo', loadChildren: 'app/foo/foo.module#FooModule', data: { preload: true } } */
return Observable.of(null);
random_line_split
app.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; import { Subscription } from 'rxjs/Subscription'; import 'rxjs/add/operator/filter'; import { UserModel } from 'app/user/user.model'; import { AuthService } from 'app/core/auth.service'; import { Mess...
() { // Can we get to the data property from this not routable component? No! // console.log(this.activatedRoute.snapshot.data['pageTitle']); // Can we subscribe to a resolve from this not routable component? No! // this.activatedRouteSubscription = this.activatedRoute.data.subscribe((data) => { //...
ngOnInit
identifier_name
app.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; import { Subscription } from 'rxjs/Subscription'; import 'rxjs/add/operator/filter'; import { UserModel } from 'app/user/user.model'; import { AuthService } from 'app/core/auth.service'; import { Mess...
ngOnDestroy() { this.userSubscription.unsubscribe(); } logOut() { this.authService.logout(); } displayMessages() { this.router.navigate([{ outlets: { popup: ['messages'] } }]); this.messageService.isDisplayed = true; } hideMessages() { this.router.navigate([{ outlets: { popup: nul...
{ // Can we get to the data property from this not routable component? No! // console.log(this.activatedRoute.snapshot.data['pageTitle']); // Can we subscribe to a resolve from this not routable component? No! // this.activatedRouteSubscription = this.activatedRoute.data.subscribe((data) => { // ...
identifier_body
generate.rs
/*fn search(width: usize, height: usize, words: &[Word], tries: &[&Trie], acrosses: &mut Vec<Word>) { if height == acrosses.len() { let downs: Vec<Word> = (0..width).map(|x| (0..height).map(|y| acrosses[y][x]).collect()).collect(); if !iproduct!(acrosses.iter(), downs.iter()).any(|(a, b)| a == b) { ...
clues.insert("CHEAP", "Overpowered, in the 90's"); clues.insert("RAG", "with \"on\", tease"); clues.insert("OVA", "Largest human cells"); clues.insert("RALLY", "Make a comeback, as a military force"); clues.insert("ANTS", "Pants' contents?"); clues.insert("EDIT", "Amend"); clues.insert("AGAR...
clues.insert("ICETEA", "???"); clues.insert("DOB", "Important date: abbr");
random_line_split
generate.rs
/*fn search(width: usize, height: usize, words: &[Word], tries: &[&Trie], acrosses: &mut Vec<Word>) { if height == acrosses.len() { let downs: Vec<Word> = (0..width).map(|x| (0..height).map(|y| acrosses[y][x]).collect()).collect(); if !iproduct!(acrosses.iter(), downs.iter()).any(|(a, b)| a == b) { ...
]; for c in line.chars() { if c == '█' { row.push(Cell::Black); } else { row.push(Cell::White(Letter::from_unicode(c))); } } rows.push(row); } let grid = Grid::new((rows[0].len(), rows.len()), |x, y| rows[y][x]); pri...
ow = vec![
identifier_name
generate.rs
/*fn search(width: usize, height: usize, words: &[Word], tries: &[&Trie], acrosses: &mut Vec<Word>) { if height == acrosses.len() { let downs: Vec<Word> = (0..width).map(|x| (0..height).map(|y| acrosses[y][x]).collect()).collect(); if !iproduct!(acrosses.iter(), downs.iter()).any(|(a, b)| a == b) { ...
RT); let mut rows = vec![]; for line in reader.records() { let mut row = vec![]; for cell in line?.iter() { row.push(match cell { "!" => Cell::Black, "" => Cell::White(None), letter => Cell::White(Some(Letter::from_unicode(letter.chars(...
identifier_body
Translatable.js
import Editor from './Editor'; import Helpers from './Helpers'; import Pencils from './Pencils'; var Translatable = { allTranslates : null, rawTranslates : null, translatedTree : [], duplicates : [], maxTranslateLength : 0, boot(TAObject, onAjax){ //Turn on translatable if translate ob...
} }, /* * Change translates and HTML dom into same format * ig. we need sort all attributes by name order, because VueJS sorts attributes... then translates are not same with innerHTML */ domPreparer: { prepared : {}, prepareTranslateHTML(html, e){ //We ne...
this.maxTranslateLength = translate.length; }
conditional_block
Translatable.js
import Editor from './Editor'; import Helpers from './Helpers'; import Pencils from './Pencils'; var Translatable = { allTranslates : null, rawTranslates : null, translatedTree : [], duplicates : [], maxTranslateLength : 0, boot(TAObject, onAjax){ //Turn on translatable if translate ob...
element, pencil){ var actualValue = this.nodeValue(element); //We cant allow update duplicate translates. Because change may be updated on right source translate. if ( this.duplicates.indexOf(actualValue) > -1 ) { alert(CATranslates.texts.cannotUpdate); ...
nPointerClick(
identifier_name
Translatable.js
import Editor from './Editor'; import Helpers from './Helpers'; import Pencils from './Pencils'; var Translatable = { allTranslates : null, rawTranslates : null, translatedTree : [], duplicates : [], maxTranslateLength : 0, boot(TAObject, onAjax){ //Turn on translatable if translate ob...
} var actualValue = this.nodeValue(element); Editor.turnOffEditor(element); //When element is hidden and is being editing state. We want open alert editor this.openAlertModal(element, actualValue); } } } export default Translatable;
//Because propably this elements has been hidden if ( element.isContentEditable !== true ){ return;
random_line_split
Translatable.js
import Editor from './Editor'; import Helpers from './Helpers'; import Pencils from './Pencils'; var Translatable = { allTranslates : null, rawTranslates : null, translatedTree : [], duplicates : [], maxTranslateLength : 0, boot(TAObject, onAjax){ //Turn on translatable if translate ob...
updateAttribute(item){ //We want update style to format same as from vuejs render if ( item.name == 'style' ){ let newValue = item.value.replace(/\:/g, ': ').replace(/\s\s/g, ' '); if ( newValue && newValue.substr(-1) != ';' ){ newVal...
let defaultAttributes = []; //If childnode has attributes, we need sort them if ( e.attributes && e.attributes.length > 0 ){ //Build attributes tree for ( let i = 0; i < e.attributes.length; i++ ){ defaultAttributes.push({ ...
identifier_body
index.b4f5078c.js
// modules are defined as an array // [ module function, map of requires ] // // map of requires is short require name -> numeric require // // anything defined in a previous bundle is accessed via the // orig method which is the require for previous bundles (function(modules, entry, mainEntry, parcelRequireName, glob...
console.log('[parcel] ✨ Error resolved'); } } function createErrorOverlay(diagnostics) { var overlay = document.createElement('div'); overlay.id = OVERLAY_ID; let errorHTML = '<div style="background: black; opacity: 0.85; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; l...
if (overlay) { overlay.remove();
random_line_split
index.b4f5078c.js
// modules are defined as an array // [ module function, map of requires ] // // map of requires is short require name -> numeric require // // anything defined in a previous bundle is accessed via the // orig method which is the require for previous bundles (function(modules, entry, mainEntry, parcelRequireName, glob...
(name, jumped) { if (!cache[name]) { if (!modules[name]) { // if we cannot find the module within our internal map or // cache jump to the current global require ie. the last bundle // that was added to the page. var currentRequire = typeof globalObject[parcelRequireN...
newRequire
identifier_name
index.b4f5078c.js
// modules are defined as an array // [ module function, map of requires ] // // map of requires is short require name -> numeric require // // anything defined in a previous bundle is accessed via the // orig method which is the require for previous bundles (function(modules, entry, mainEntry, parcelRequireName, glob...
n createErrorOverlay(diagnostics) { var overlay = document.createElement('div'); overlay.id = OVERLAY_ID; let errorHTML = '<div style="background: black; opacity: 0.85; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; left: 0px; padding: 30px; font-family: Menlo, Consolas, mono...
r overlay = document.getElementById(OVERLAY_ID); if (overlay) { overlay.remove(); console.log('[parcel] ✨ Error resolved'); } } functio
identifier_body
index.b4f5078c.js
// modules are defined as an array // [ module function, map of requires ] // // map of requires is short require name -> numeric require // // anything defined in a previous bundle is accessed via the // orig method which is the require for previous bundles (function(modules, entry, mainEntry, parcelRequireName, glob...
undle.cache[id]; bundle(id); cached = bundle.cache[id]; if (cached && cached.hot && cached.hot._acceptCallbacks.length) { cached.hot._acceptCallbacks.forEach(function (cb) { var assetsToAlsoAccept = cb(function () { return getParents(module.bundle.root, id); }); if (assetsToAlsoAccep...
d.hot._disposeCallbacks.forEach(function (cb) { cb(bundle.hotData); }); } delete b
conditional_block
Simple-Linear-Regression.py
# coding: utf-8 # # Simple Linear Regression # # In this notebook, we'll build a linear regression model to predict `Sales` using an appropriate predictor variable. # ## Step 1: Reading and Understanding the Data # # Let's start with the following steps: # # 1. Importing data using the pandas library # 2. Understa...
corrs = np.corrcoef(X_train, y_train) print(corrs) # In[46]: corrs[0,1] ** 2 # Correlation (Pearson) is also called **"r"** or **"Pearson's R"** # # # # # # # # # ### Q: What is a good RMSE? Is there some RMSE that I should aim for? # <br> # # <br> # # You should be able to answer this by ...
# # # # In[45]:
random_line_split
ctl.rs
use std::{path::PathBuf, process::ExitCode}; use crate::daemon::{config::CliArg, tracing::LogLevel, Config, ObservableState}; use tracing_subscriber::util::SubscriberInitExt; const USAGE_MSG: &str = "\ usage: ntp-ctl validate [-c PATH] ntp-ctl status [-f FORMAT] [-c PATH] [-o PATH] ntp-ctl -h | ntp-ctl ...
() -> std::io::Result<ExitCode> { let options = match NtpDaemonOptions::try_parse_from(std::env::args()) { Ok(options) => options, Err(msg) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, msg)), }; match options.action { NtpCtlAction::Help => { printl...
main
identifier_name
ctl.rs
use std::{path::PathBuf, process::ExitCode}; use crate::daemon::{config::CliArg, tracing::LogLevel, Config, ObservableState}; use tracing_subscriber::util::SubscriberInitExt; const USAGE_MSG: &str = "\ usage: ntp-ctl validate [-c PATH] ntp-ctl status [-f FORMAT] [-c PATH] [-o PATH] ntp-ctl -h | ntp-ctl ...
let observation = config .observability .observe .observation_path .unwrap_or_else(|| PathBuf::from("/run/ntpd-rs/observe")); match options.format { Format::Plain => print_state(Format::Plain, observation).await, ...
let config = config.unwrap_or_default();
random_line_split
ctl.rs
use std::{path::PathBuf, process::ExitCode}; use crate::daemon::{config::CliArg, tracing::LogLevel, Config, ObservableState}; use tracing_subscriber::util::SubscriberInitExt; const USAGE_MSG: &str = "\ usage: ntp-ctl validate [-c PATH] ntp-ctl status [-f FORMAT] [-c PATH] [-o PATH] ntp-ctl -h | ntp-ctl ...
}, CliArg::Argument(option, value) => match option.as_str() { "-c" | "--config" => { options.config = Some(PathBuf::from(value)); } "-f" | "--format" => match value.as_str() { "pl...
{ Err(format!("invalid option provided: {option}"))?; }
conditional_block
MRGnodeHFS.py
#!/usr/bin/env python from neuron import h import os.path as path import os import sys import numpy as np import h5py as h5 __all__ = ['insert_nrn_recorders','pass_parameters_to_nrn', 'createMRGaxon','recordMRGaxon','fix_patternLag_vector', 'record_node_voltage','record_node_spikes', '...
rec['spiketimes'],rec['apcount'] = record_node_spikes(k) if verbose: print('Now recording from '+str(k)) return rec def resetRecorder(rec,verbose=False): ''' Clears hoc vectors in spiketimes and voltage and resets apcounts. ''' for k,o in rec['spiketimes'].iteritems(): ...
rec['voltage'] = record_node_voltage(k)
conditional_block
MRGnodeHFS.py
#!/usr/bin/env python from neuron import h import os.path as path import os import sys import numpy as np import h5py as h5 __all__ = ['insert_nrn_recorders','pass_parameters_to_nrn', 'createMRGaxon','recordMRGaxon','fix_patternLag_vector', 'record_node_voltage','record_node_spikes', '...
Executes a simulation taking the parameters from a configuration file. ''' verbose = True counter = 0 for v in sys.argv: counter+=1 if path.basename(__file__) in v: break filename = sys.argv[counter] par, recpar = readConfigurations(filename) createMRGaxon...
'''
random_line_split
MRGnodeHFS.py
#!/usr/bin/env python from neuron import h import os.path as path import os import sys import numpy as np import h5py as h5 __all__ = ['insert_nrn_recorders','pass_parameters_to_nrn', 'createMRGaxon','recordMRGaxon','fix_patternLag_vector', 'record_node_voltage','record_node_spikes', '...
def createMRGaxon(par, verbose): ''' Initializes the model. Creates the axon and stimulation according to the parameters. ''' h('{load_file("stdgui.hoc")}') fix_patternLag_vector(par) pass_parameters_to_nrn(par,['pattern','patternLag'],verb=verbose) h('{load_file("MRGnodeHFS.hoc")}') ...
''' Records the membrane potential of a particular set of nodes. ''' rec = None segments = [] for n in nodenumber: segments.append(h.node[n](0.5)) for seg,n in zip(segments,nodenumber): rec = insert_nrn_recorders(seg,{'v_node'+str(n):'_ref_v'},rec) return rec
identifier_body
MRGnodeHFS.py
#!/usr/bin/env python from neuron import h import os.path as path import os import sys import numpy as np import h5py as h5 __all__ = ['insert_nrn_recorders','pass_parameters_to_nrn', 'createMRGaxon','recordMRGaxon','fix_patternLag_vector', 'record_node_voltage','record_node_spikes', '...
(): h.resetModel() h.run() def readConfigurations(filename): ''' Reads the parameters from the configuration file. Returns par and recpar or defaults if filename is not a valid file. ''' if path.isfile(filename): fid = open(filename) else: print('File "'+filename+'" does...
runMRGaxon
identifier_name
template_tool.py
from django import template from django.utils.safestring import mark_safe # A site is a piece of ground that is used for a particular purpose or where a particular thing habbens from cadmin.baseadmin import site from common.utils import demark_safe register = template.Library() @register.simple_tag def get...
identifier_name
template_tool.py
from django import template from django.utils.safestring import mark_safe # A site is a piece of ground that is used for a particular purpose or where a particular thing habbens from cadmin.baseadmin import site from common.utils import demark_safe register = template.Library() @register.simple_tag def get...
t_field(group).model.objects.value_list('groupname') table._meta.get_field(group).model._meta.get_field(group).model.objects.value_list('groupname') """ def get_depth_filter(table, field): fields = field.split("__", 1) field_obj = table._meta.get_field(fields[0]) if len(f...
= admin_class.list_editable form_obj = admin_class.model_change_form(instance=table_obj) ret_html = [] ret_html.append('''<td> <div class="checkbox check-transparent"> <input type="checkbox" class="magic-checkbox" id="check_%s" name="check_item" value="%s" onclick="check_comp...
identifier_body
template_tool.py
from django import template from django.utils.safestring import mark_safe # A site is a piece of ground that is used for a particular purpose or where a particular thing habbens from cadmin.baseadmin import site from common.utils import demark_safe register = template.Library() @register.simple_tag def get...
@register.simple_tag def make_url(path_info, filter_dict, action): ''' 对已有的url和get进行重构 :param path_info: :return: ''' param_dict = {} for k, v in filter_dict.items(): param_dict[k] = "%s=%s" % (k, v) url = "%s%s?%s" % (path_info, action, "&".join(param_dict.values()...
''' return mark_safe("".join(ret_html))
random_line_split
template_tool.py
from django import template from django.utils.safestring import mark_safe # A site is a piece of ground that is used for a particular purpose or where a particular thing habbens from cadmin.baseadmin import site from common.utils import demark_safe register = template.Library() @register.simple_tag def get...
else: verbose_name = model_class._meta.get_field(field).verbose_name return verbose_name def get_depth_value(obj, field): """ 递归读取 aa__bb__cc 如果有__说明是外键,往里面走 如果找到最里面的,看是否是choice,如果是,get_该字段_display找值,如果不是,直接按照该字段找值 a__b__c """ fields = field.split("__", 1...
verbose_name = get_field_verbose_name(field_obj.related_model, fields[1])
conditional_block
updateDeps.js
import { writeFileSync } from "fs"; import semver from "semver"; import { isObject, isEqual, transform } from "lodash-es"; import recognizeFormat from "./recognizeFormat.js"; import getManifest from "./getManifest.js"; import { getHighestVersion, getLatestVersion } from "./utils.js"; import { getTags } from "./git.js";...
resolveReleaseType, resolveNextVersion, getVersionFromTag, };
getPreReleaseTag, updateManifestDeps,
random_line_split
train.py
# -*- coding: utf-8 -*- import argparse import os import pprint import random import time import numpy as np import torchtext import torch from tensorboardX import SummaryWriter from tqdm import tqdm from model import * from utility import get_accuracy, get_logger, get_dataset from args import parse_args def train_...
if isinstance(topk, int): accuracy = get_accuracy(qids, predictions, true_labels, 1) return accuracy elif isinstance(topk, list): accuracies = {} for i in topk: accuracy = get_accuracy(qids, predictions, true_labels, i) accuracies[i] = accuracy ret...
random_line_split
train.py
# -*- coding: utf-8 -*- import argparse import os import pprint import random import time import numpy as np import torchtext import torch from tensorboardX import SummaryWriter from tqdm import tqdm from model import * from utility import get_accuracy, get_logger, get_dataset from args import parse_args def train_...
cies = {} for i in topk: accuracy = get_accuracy(qids, predictions, true_labels, i) accuracies[i] = accuracy return accuracies else: raise ValueError('Error topk') def run(): args = parse_args() # 初始化随机数种子,以便于复现实验结果 start_epoch = 1 random.seed(args.s...
labels, 1) return accuracy elif isinstance(topk, list): accura
conditional_block
train.py
# -*- coding: utf-8 -*- import argparse import os import pprint import random import time import numpy as np import torchtext import torch from tensorboardX import SummaryWriter from tqdm import tqdm from model import * from utility import get_accuracy, get_logger, get_dataset from args import parse_args def train_...
start_epoch = 1 random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.device != -1: torch.cuda.manual_seed(args.seed) device = torch.device(f'cuda:{args.device}' if torch.cuda.is_available() and args.device >= 0 else 'cpu') if torch.cuda.is_available() an...
identifier_body
train.py
# -*- coding: utf-8 -*- import argparse import os import pprint import random import time import numpy as np import torchtext import torch from tensorboardX import SummaryWriter from tqdm import tqdm from model import * from utility import get_accuracy, get_logger, get_dataset from args import parse_args def
(epoch, data_loader, model, optimizer, loss_fn, device): """ 进行一次迭代 """ model.train() pbar = tqdm(data_loader, desc='Train Epoch {}'.format(epoch)) total_loss = [] for batch_idx, batch in enumerate(pbar): optimizer.zero_grad() target = torch.ones(batch.batch_size, requires_g...
train_epoch
identifier_name
util.rs
//! Utility traits and functions. use std::ffi; use std::fs::{self, File}; use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::result; use std::time; use anyhow::{Context as ResultExt, Error, Result}; use fs2::{lock_contended_error, FileExt}; use crate::context::{Context, SettingsExt}; /// Returns ...
fn _submodule_update(repo: &Repository, todo: &mut Vec<Repository>) -> Result<(), Error> { for mut submodule in repo.submodules()? { submodule.update(true, None)?; todo.push(submodule.open()?); } Ok(()) } let mut repos = Vec::ne...
} /// Recursively update Git submodules. pub fn submodule_update(repo: &Repository) -> Result<(), Error> {
random_line_split
util.rs
//! Utility traits and functions. use std::ffi; use std::fs::{self, File}; use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::result; use std::time; use anyhow::{Context as ResultExt, Error, Result}; use fs2::{lock_contended_error, FileExt}; use crate::context::{Context, SettingsExt}; /// Returns ...
{ /// The temporary directory or file path. path: Option<PathBuf>, } impl TempPath { /// Create a new `TempPath` based on an original path, the temporary /// filename will be placed in the same directory with a deterministic name. /// /// # Errors /// /// If the temporary path already ...
TempPath
identifier_name
util.rs
//! Utility traits and functions. use std::ffi; use std::fs::{self, File}; use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::result; use std::time; use anyhow::{Context as ResultExt, Error, Result}; use fs2::{lock_contended_error, FileExt}; use crate::context::{Context, SettingsExt}; /// Returns ...
/// Fetch a Git repository. pub fn fetch(repo: &Repository) -> anyhow::Result<()> { with_fetch_options(|mut opts| { repo.find_remote("origin") .context("failed to find remote `origin`")? .fetch(&DEFAULT_REFSPECS, Some(&mut opts), None)?; Ok(()) ...
{ with_fetch_options(|mut opts| { let repo = Repository::init(dir)?; repo.remote("origin", url.as_str())? .fetch(&DEFAULT_REFSPECS, Some(&mut opts), None)?; Ok(repo) }) .with_context(s!("failed to git clone `{}`", url)) }
identifier_body
Main.py
from collections import OrderedDict import copy from itertools import zip_longest import json import logging import os import random import time from BaseClasses import World, CollectionState, Item, Region, Location, Shop from Regions import create_regions, mark_light_world_regions from InvertedRegions import create_i...
elif args.algorithm == 'vt25': distribute_items_restrictive(world, 0) elif args.algorithm == 'vt26': distribute_items_restrictive(world, gt_filler(world), shuffled_locations) elif args.algorithm == 'balanced': distribute_items_restrictive(world, gt_filler(world)) if world.play...
distribute_items_staleness(world)
conditional_block
Main.py
from collections import OrderedDict import copy from itertools import zip_longest import json import logging import os import random import time from BaseClasses import World, CollectionState, Item, Region, Location, Shop from Regions import create_regions, mark_light_world_regions from InvertedRegions import create_i...
(state, region): reversed_path_as_flist = state.path.get(region, (region, None)) string_path_flat = reversed(list(map(str, flist_to_iter(reversed_path_as_flist)))) # Now we combine the flat string list into (region, exit) pairs pathsiter = iter(string_path_flat) pathpairs = zip_l...
get_path
identifier_name
Main.py
from collections import OrderedDict import copy from itertools import zip_longest import json import logging import os import random import time from BaseClasses import World, CollectionState, Item, Region, Location, Shop from Regions import create_regions, mark_light_world_regions from InvertedRegions import create_i...
def gt_filler(world): if world.goal == 'triforcehunt': return random.randint(15, 50) return random.randint(0, 15) def copy_world(world): # ToDo: Not good yet ret = World(world.players, world.shuffle, world.logic, world.mode, world.swords, world.difficulty, world.difficulty_adjustments, world....
start = time.perf_counter() # initialize the world world = World(args.multi, args.shuffle, args.logic, args.mode, args.swords, args.difficulty, args.item_functionality, args.timer, args.progressive, args.goal, args.algorithm, not args.nodungeonitems, args.accessibility, args.shuffleganon, args.quickswap, args....
identifier_body
Main.py
from collections import OrderedDict import copy from itertools import zip_longest import json import logging import os import random import time from BaseClasses import World, CollectionState, Item, Region, Location, Shop from Regions import create_regions, mark_light_world_regions from InvertedRegions import create_i...
if world.mode != 'inverted': old_world.spoiler.paths[str(world.get_region('Big Bomb Shop', player))] = get_path(state, world.get_region('Big Bomb Shop', player)) else: old_world.spoiler.paths[str(world.get_region('Inverted Big Bomb Shop', player))]...
if any(exit == 'Pyramid Fairy' for (_, exit) in path):
random_line_split
misc.go
// Copyright 2010 Gary Burd // // 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 wr...
(seconds int) *Cookie { c.maxAge = seconds; return c } // MaxAgeDays sets the maximum age for the cookie in days. func (c *Cookie) MaxAgeDays(days int) *Cookie { return c.MaxAge(days * 60 * 60 * 24) } // Delete sets the expiration date to a time in the past. func (c *Cookie) Delete() *Cookie { return c.MaxAgeDays(-3...
MaxAge
identifier_name
misc.go
// Copyright 2010 Gary Burd // // 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 wr...
if expectedToken != actualToken { req.Param.Set(paramName, expectedToken) if req.Method == "POST" || req.Method == "PUT" || req.Method == "DELETE" { err := os.NewError("twister: bad xsrf token") if actualToken == "" { err = os.NewError("twister: missing xsrf token") } return err } } retu...
{ actualToken = req.Header.Get(HeaderXXSRFToken) req.Param.Set(paramName, expectedToken) }
conditional_block
misc.go
// Copyright 2010 Gary Burd // // 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 wr...
// Path sets the cookie path attribute. The path must either be "" or start with a // '/'. The NewCookie function initializes the path to "/". If the path is "", // then the path attribute is not included in the header value. func (c *Cookie) Path(path string) *Cookie { c.path = path; return c } // Domain sets the...
{ return &Cookie{name: name, value: value, path: "/", httpOnly: true} }
identifier_body
misc.go
// Copyright 2010 Gary Burd // // 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 wr...
StatusNotModified: "Not Modified", StatusUseProxy: "Use Proxy", StatusTemporaryRedirect: "Temporary Redirect", StatusBadRequest: "Bad Request", StatusUnauthorized: "Unauthorized", StatusPaymentRequired: "Payment Require...
StatusMovedPermanently: "Moved Permanently", StatusFound: "Found", StatusSeeOther: "See Other",
random_line_split
ABCA_topK.py
""" A Python Class A simple Python graph class, demonstrating the essential facts and functionalities of graphs. """ #import queue import math from random import choice #import copy import sys import time from collections import deque #from numba import jit class Graph(object): def __init__(s...
""" returns the vertices of a graph """ return list(self.__graph_dict.keys()) def edges(self): """ returns the edges of a graph """ return self.__generate_edges() def num_vertices(self): """ returns the number of vertices of a graph """ return len(self...
return self.__bfs_dict def vertices(self):
random_line_split
ABCA_topK.py
""" A Python Class A simple Python graph class, demonstrating the essential facts and functionalities of graphs. """ #import queue import math from random import choice #import copy import sys import time from collections import deque #from numba import jit class Graph(object): def __init__(s...
def set_m(graph, eta): m = int(math.log2((graph.num_vertices()**2)/(eta**2))) print("m = %d" %m) return m #@jit def cal_bc(graph, m, s_list, t_list): # m must be much smaller than the number of edges nd_list = list(graph.vertices()) bc_dict = dict((node, 0) for node in nd_...
total_count[current_node.name] = 0 if current_node.name not in tree_map.keys(): return children = tree_map[current_node.name] for child in children: child_node = Node(child) current_node.add_child(child_node) add_branch(tree_map, child_node, total_count) return
identifier_body
ABCA_topK.py
""" A Python Class A simple Python graph class, demonstrating the essential facts and functionalities of graphs. """ #import queue import math from random import choice #import copy import sys import time from collections import deque #from numba import jit class Graph(object): def __init__(s...
(self, s, t): #current_bfs = dict() pre_map = self.bfs(s) if t in pre_map: return [True, pre_map] return[False, pre_map] def __str__(self): res = "vertices: " for k in self.__graph_dict: res += str(k) + " " res += "\nedges: ...
is_connect
identifier_name
ABCA_topK.py
""" A Python Class A simple Python graph class, demonstrating the essential facts and functionalities of graphs. """ #import queue import math from random import choice #import copy import sys import time from collections import deque #from numba import jit class Graph(object): def __init__(s...
else: parents[node].append(s) # record 'parents' of this node pre_dict[node].append(s) node_count_dict.pop('fake_root') return [pre_dict, node_count_dict] # two returns: 1) tree; 2) node count dictionary def dfs(root, total_count): ...
nq.append(node) # let 'node' in queue pre_dict[node] = [s] # the 'parent' (in terms of shortest path from 'root') of 'node' is 's' dist[node] = dist[s] + 1 # shortest path to 'root' visited[node]=1 # 'node' is visted parents[node]=[s] # record 'parents...
conditional_block
zbdsqr.go
package golapack import ( "fmt" "math" "github.com/whipstein/golinalg/golapack/gltest" "github.com/whipstein/golinalg/mat" ) // Zbdsqr computes the singular values and, optionally, the right and/or // left singular vectors from the singular value decomposition (SVD) of // a real N-by-N (upper or lower) bidiagona...
} } } // Increment iteration count iter = iter + m - ll // If SHIFT = 0, do simplified QR iteration if shift == zero { if idir == 1 { // Chase bulge from top to bottom // Save cosines and sines for later singular vector updates cs = one oldcs = one for i = ll; i ...
shift = zero
random_line_split
zbdsqr.go
package golapack import ( "fmt" "math" "github.com/whipstein/golinalg/golapack/gltest" "github.com/whipstein/golinalg/mat" ) // Zbdsqr computes the singular values and, optionally, the right and/or // left singular vectors from the singular value decomposition (SVD) of // a real N-by-N (upper or lower) bidiagona...
{ var lower, rotate bool var abse, abss, cosl, cosr, cs, eps, f, g, h, hndrd, hndrth, meigth, mu, negone, oldcs, oldsn, one, r, shift, sigmn, sigmx, sinl, sinr, sll, smax, smin, sminl, sminoa, sn, ten, thresh, tol, tolmul, unfl, zero float64 var i, idir, isub, iter, j, ll, lll, m, maxit, maxitr, nm1, nm12, nm13, old...
identifier_body
zbdsqr.go
package golapack import ( "fmt" "math" "github.com/whipstein/golinalg/golapack/gltest" "github.com/whipstein/golinalg/mat" ) // Zbdsqr computes the singular values and, optionally, the right and/or // left singular vectors from the singular value decomposition (SVD) of // a real N-by-N (upper or lower) bidiagona...
(uplo mat.MatUplo, n, ncvt, nru, ncc int, d, e *mat.Vector, vt, u, c *mat.CMatrix, rwork *mat.Vector) (info int, err error) { var lower, rotate bool var abse, abss, cosl, cosr, cs, eps, f, g, h, hndrd, hndrth, meigth, mu, negone, oldcs, oldsn, one, r, shift, sigmn, sigmx, sinl, sinr, sll, smax, smin, sminl, sminoa, s...
Zbdsqr
identifier_name
zbdsqr.go
package golapack import ( "fmt" "math" "github.com/whipstein/golinalg/golapack/gltest" "github.com/whipstein/golinalg/mat" ) // Zbdsqr computes the singular values and, optionally, the right and/or // left singular vectors from the singular value decomposition (SVD) of // a real N-by-N (upper or lower) bidiagona...
if ncc > 0 { if err = Zlasr(Left, 'V', 'F', m-ll+1, ncc, rwork.Off(nm12), rwork.Off(nm13), c.Off(ll-1, 0)); err != nil { panic(err) } } // Test convergence if math.Abs(e.Get(m-1-1)) <= thresh { e.Set(m-1-1, zero) } } else { // Chase bulge from bottom to top ...
{ if err = Zlasr(Right, 'V', 'F', nru, m-ll+1, rwork.Off(nm12), rwork.Off(nm13), u.Off(0, ll-1)); err != nil { panic(err) } }
conditional_block
bignum.rs
/* Copyright (c) Fortanix, Inc. * * Licensed under the GNU General Public License, version 2 <LICENSE-GPL or * https://www.gnu.org/licenses/gpl-2.0.html> or the Apache License, Version * 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>, at your * option. This file may not be copied, modified, or ...
() { use std::str::FromStr; fn mod_sqrt_test(a: &str, n: &str, expected: &str) { let a = Mpi::from_str(a).unwrap(); let n = Mpi::from_str(n).unwrap(); let expected = Mpi::from_str(expected).unwrap(); let mut computed = a.mod_sqrt(&n).unwrap(); /* If x = (a*a) mo...
test_mod_sqrt_fn
identifier_name
bignum.rs
/* Copyright (c) Fortanix, Inc. * * Licensed under the GNU General Public License, version 2 <LICENSE-GPL or * https://www.gnu.org/licenses/gpl-2.0.html> or the Apache License, Version * 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>, at your * option. This file may not be copied, modified, or ...
#[test] fn test_base58_encode() { fn test_base58_rt(input: &[u8], expected: &str) { assert_eq!(base58_encode(input).unwrap(), expected); assert_eq!(base58_decode(expected).unwrap(), input); } test_base58_rt(b"", ""); test_base58_rt(&[32], "Z"); test_base58_rt(&[45], "n"); test...
{ let radix: i64 = 58; let mut n = Mpi::new(0)?; fn base58_val(b: u8) -> mbedtls::Result<usize> { for (i, c) in BASE58_ALPHABET.iter().enumerate() { if *c == b { return Ok(i); } } Err(mbedtls::Error::Base64InvalidCharacter) } for c i...
identifier_body
bignum.rs
/* Copyright (c) Fortanix, Inc. * * Licensed under the GNU General Public License, version 2 <LICENSE-GPL or * https://www.gnu.org/licenses/gpl-2.0.html> or the Apache License, Version * 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>, at your * option. This file may not be copied, modified, or ...
#[cfg(feature = "std")] #[test] fn test_jacobi_fn() { use std::str::FromStr; fn jacobi_symbol_test(a: &str, n: &str, expected: i32) { let a = Mpi::from_str(a).unwrap(); let n = Mpi::from_str(n).unwrap(); let j = a.jacobi(&n).unwrap(); //println!("a={} n={} J={}", a, n, j); ...
}
random_line_split
bignum.rs
/* Copyright (c) Fortanix, Inc. * * Licensed under the GNU General Public License, version 2 <LICENSE-GPL or * https://www.gnu.org/licenses/gpl-2.0.html> or the Apache License, Version * 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>, at your * option. This file may not be copied, modified, or ...
assert_eq!(computed, expected); } // Tests generated by Sagemath mod_sqrt_test("2", "7", "4"); mod_sqrt_test("5", "469289024411159", "234325000312516"); mod_sqrt_test( "458050473005020050313790240477", "905858848829014223214249213947", "12647408626047957484571419433...
{ computed = (&n - &computed).unwrap(); }
conditional_block
warc.py
# Copyright (c) 2017 crocoite contributors # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publi...
def _flushLogEntries (self): writer = self.writer self.log.seek (0) # XXX: we should use the type continuation here self.writeRecord (packageUrl ('log'), 'resource', payload=self.log, warc_headers_dict={'Content-Type': 'text/plain; encoding={}'.format (self.logEncodi...
random_line_split
warc.py
# Copyright (c) 2017 crocoite contributors # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publi...
_addRefersTo (self, headers, url): refersTo = self.documentRecords.get (url) if refersTo: headers['WARC-Refers-To'] = refersTo else: self.logger.error ('No document record found for {}'.format (url)) return headers def _writeDomSnapshot (self, item): ...
iled: # should have been handled by the logger already return concurrentTo = self._writeRequest (item) self._writeResponse (item, concurrentTo) def
identifier_body
warc.py
# Copyright (c) 2017 crocoite contributors # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publi...
if payload: payload = BytesIO (payload) warcHeaders['X-Chrome-Base64Body'] = str (payloadBase64Encoded) record = self.writeRecord (req['url'], 'request', payload=payload, http_headers=httpHeaders, warc_headers_dict=warcHeaders) return recor...
rcHeaders['WARC-Truncated'] = bodyTruncated payload = None
conditional_block
warc.py
# Copyright (c) 2017 crocoite contributors # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publi...
em): writer = self.writer encoding = 'utf-8' self.writeRecord (packageUrl ('script/{}'.format (item.path)), 'metadata', payload=BytesIO (str (item).encode (encoding)), warc_headers_dict={'Content-Type': 'application/javascript; charset={}'.format (encoding)}) ...
pt (self, it
identifier_name
api_op_UpdateItem.go
// Code generated by smithy-go-codegen DO NOT EDIT. package dynamodb import ( "context" "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.c...
// One or more values that can be substituted in an expression. Use the : (colon) // character in an expression to dereference an attribute value. For example, // suppose that you wanted to check whether the value of the ProductStatus // attribute was one of the following: Available | Backordered | Discontinued You...
ExpressionAttributeNames map[string]string
random_line_split
api_op_UpdateItem.go
// Code generated by smithy-go-codegen DO NOT EDIT. package dynamodb import ( "context" "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.c...
if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { return err } return nil } func addOpUpdateItemDiscoverEndpointMiddleware(stack *middleware.Stack, o Options, c *Client) error { return stack.Serialize.Insert(&internalEndpointDiscovery.DiscoverEndpoint{ Options: []func(*internalEndpointD...
{ return err }
conditional_block
api_op_UpdateItem.go
// Code generated by smithy-go-codegen DO NOT EDIT. package dynamodb import ( "context" "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.c...
func newServiceMetadataMiddleware_opUpdateItem(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "dynamodb", OperationName: "UpdateItem", } } type opUpdateItemResolveEndpointMiddleware struc...
{ in, ok := input.(*UpdateItemInput) if !ok { return internalEndpointDiscovery.WeightedAddress{}, fmt.Errorf("unknown input type %T", input) } _ = in identifierMap := make(map[string]string, 0) key := fmt.Sprintf("DynamoDB.%v", identifierMap) if v, ok := c.endpointCache.Get(key); ok { return v, nil } d...
identifier_body
api_op_UpdateItem.go
// Code generated by smithy-go-codegen DO NOT EDIT. package dynamodb import ( "context" "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.c...
(ctx context.Context, input interface{}, optFns ...func(*internalEndpointDiscovery.DiscoverEndpointOptions)) (internalEndpointDiscovery.WeightedAddress, error) { in, ok := input.(*UpdateItemInput) if !ok { return internalEndpointDiscovery.WeightedAddress{}, fmt.Errorf("unknown input type %T", input) } _ = in id...
fetchOpUpdateItemDiscoverEndpoint
identifier_name
lib.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG 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...
; <EnclaveRegistry<T>>::insert(enclave_idx, &enclave); Ok(()) } fn remove_enclave(sender: &T::AccountId) -> DispatchResult { ensure!( <EnclaveIndex<T>>::contains_key(sender), <Error<T>>::InexistentEnclave ); let index_to_remove = <EnclaveIndex<T>...
{ let enclaves_count = Self::enclave_count() .checked_add(1) .ok_or("[Teerex]: Overflow adding new enclave to registry")?; <EnclaveIndex<T>>::insert(sender, enclaves_count); <EnclaveCount>::put(enclaves_count); enclaves_count }
conditional_block
lib.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG 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...
} impl<T: Config> OnTimestampSet<T::Moment> for Module<T> { fn on_timestamp_set(moment: T::Moment) { Self::unregister_silent_workers(moment) } } mod benchmarking; #[cfg(test)] mod mock; mod test_utils; #[cfg(test)] mod tests; pub mod weights;
{ use sp_runtime::traits::CheckedSub; let elapsed_time = <timestamp::Pallet<T>>::get() .checked_sub(&T::Moment::saturated_from(report_timestamp)) .ok_or("Underflow while calculating elapsed time since report creation")?; if elapsed_time < T::MomentsPerDay::get() { ...
identifier_body
lib.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG 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...
(index_to_remove: u64, new_enclaves_count: u64) -> DispatchResult { if index_to_remove != new_enclaves_count { let last_enclave = <EnclaveRegistry<T>>::get(&new_enclaves_count); <EnclaveRegistry<T>>::insert(index_to_remove, &last_enclave); <EnclaveIndex<T>>::insert(last_encla...
swap_and_pop
identifier_name
lib.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG 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...
CallConfirmed(AccountId, H256), BlockConfirmed(AccountId, H256), } ); decl_storage! { trait Store for Module<T: Config> as Teerex { // Simple lists are not supported in runtime modules as theoretically O(n) // operations can be executed while only being charged O(1), see substra...
random_line_split
mod.rs
// Copyright 2019 The Exonum Team // // 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 i...
pub trait ChangeSet { fn as_ref(&self) -> Option<&ViewChanges>; /// Provides mutable reference to changes. The implementation for a `RawAccessMut` type /// should always return `Some(_)`. fn as_mut(&mut self) -> Option<&mut ViewChanges>; } /// No-op implementation used in `Snapshot`. impl ChangeSet for...
random_line_split
mod.rs
// Copyright 2019 The Exonum Team // // 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 i...
fn as_mut(&mut self) -> Option<&mut ViewChanges> { None } } impl ChangeSet for ChangesRef { fn as_ref(&self) -> Option<&ViewChanges> { Some(&*self) } fn as_mut(&mut self) -> Option<&mut ViewChanges> { None } } impl ChangeSet for ChangesMut<'_> { fn as_ref(&self) ->...
{ None }
identifier_body
mod.rs
// Copyright 2019 The Exonum Team // // 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 i...
} } } struct ChangesIter<'a, T: Iterator + 'a> { inner: Peekable<T>, _lifetime: PhantomData<&'a ()>, } /// Iterator over a set of changes. impl<'a, T> ChangesIter<'a, T> where T: Iterator<Item = (&'a Vec<u8>, &'a Change)>, { fn new(iterator: T) -> Self { ChangesIter { ...
{ self.ended = true; None }
conditional_block
mod.rs
// Copyright 2019 The Exonum Team // // 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 i...
(&mut self) -> Option<(&[u8], &[u8])> { loop { match self.inner.peek() { Some((key, &Change::Put(ref value))) => { return Some((key.as_slice(), value.as_slice())); } Some((_, &Change::Delete)) => {} None => { ...
peek
identifier_name
fitters.py
""" Glue's fitting classes are designed to be easily subclassed for performing custom model fitting in Glue. """ import numpy as np from glue.core.simpleforms import IntOption, Option __all__ = ['BaseFitter1D', 'PolynomialFitter', 'AstropyFitter1D', 'SimpleAstropyGaussianFitter', ...
return np.exp(-(x - mean) ** 2 / (2 * stddev ** 2)) * amplitude @staticmethod def fit_deriv(x, amplitude, mean, stddev): """ Gaussian1D model function derivatives. """ d_amplitude = np.exp(-0.5 / stddev ** 2 * (x - mean) ** 2) d_mean = amplitude * d_amplitude * ...
@staticmethod def eval(x, amplitude, mean, stddev):
random_line_split
fitters.py
""" Glue's fitting classes are designed to be easily subclassed for performing custom model fitting in Glue. """ import numpy as np from glue.core.simpleforms import IntOption, Option __all__ = ['BaseFitter1D', 'PolynomialFitter', 'AstropyFitter1D', 'SimpleAstropyGaussianFitter', ...
(self, x, y, dy): """ Provide initial guesses for each model parameter. **The base implementation does nothing, and should be overridden** :param x: X - values of the data :type x: :class:`numpy.ndarray` :param y: Y - values of the data :type y: :class:`numpy.nd...
parameter_guesses
identifier_name
fitters.py
""" Glue's fitting classes are designed to be easily subclassed for performing custom model fitting in Glue. """ import numpy as np from glue.core.simpleforms import IntOption, Option __all__ = ['BaseFitter1D', 'PolynomialFitter', 'AstropyFitter1D', 'SimpleAstropyGaussianFitter', ...
def plot(self, fit_result, axes, x, linewidth=None, alpha=None, color=None, normalize=None): """ Plot the result of a fit. :param fit_result: The output from fit :param axes: The Matplotlib axes to add the fit to :param x: The values of X at which to visualize the model ...
setattr(self, k, v)
conditional_block
fitters.py
""" Glue's fitting classes are designed to be easily subclassed for performing custom model fitting in Glue. """ import numpy as np from glue.core.simpleforms import IntOption, Option __all__ = ['BaseFitter1D', 'PolynomialFitter', 'AstropyFitter1D', 'SimpleAstropyGaussianFitter', ...
def _gaussian_parameter_estimates(x, y, dy): amplitude = np.percentile(y, 95) y = np.maximum(y / y.sum(), 0) mean = (x * y).sum() stddev = np.sqrt((y * (x - mean) ** 2).sum()) return dict(mean=mean, stddev=stddev, amplitude=amplitude) class BasicGaussianFitter(BaseFitter1D): """ Fallb...
""" Provide initial guesses for each model parameter. **The base implementation does nothing, and should be overridden** :param x: X - values of the data :type x: :class:`numpy.ndarray` :param y: Y - values of the data :type y: :class:`numpy.ndarray` :param dy: ...
identifier_body