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
script.js
50, rotating:50, } window.timeouts = { } window.maps = [ map1, map2, map3, map4, map5 ] window.state = { paused:true, gameStart:true, crashed:false, completed:false, mapIndex:0, } ///GLOBAL METHODS----------------------------------------- window.killScreen = func...
if( checkVictory() ) return handleVictory() mycar.style.top=`${yPosition}px` mycar.style.left=`${xPosition}px` },myIntervalValues.moving) } //EVENT LISTENERS --------------------------------------------------- window.initListeners = function(){ document.addEventListener('ke...
{ myIntervals.moving = setInterval(()=>{ if(state.paused) return let ratio = (rotationAngle%360)/360 if(ratio < 0 ) ratio=Math.abs(ratio + 1) let ratio2 = (10 * (ratio*4)) if(ratio2 > 20) ratio2 -= 2*(ratio2 - 20) let ratio3 = (10 * (ratio*4)) ...
identifier_body
codon_usage.py
AA_dict = \ collections.defaultdict( lambda:collections.defaultdict(list)) # dict key: AA -> codon list AA_map = { 'Phe':['TTT', 'TTC'], 'Leu':['TTA', 'TTG', 'CTT', 'CTC', 'CTA', 'CTG'], 'Ser':...
file = io.open('AAs_to_compare.txt', 'w') file.write('Compare following AAs\n') # AAs that have only two codon choices and show significant
random_line_split
codon_usage.py
gene_seq = '' # read a gene sequence line else: gene_seq += line.strip() file.close() print('%s:\n%d genes added\n%d are non-triple\n'% (filename[:2],count_all, count_non_tripl...
file = io.open(filename) # list of selected gene sequences, excluded genes that are non-triple all_seq = [] gene_seq = '' count_all = 0 count_non_triple = 0 for line in file: # read a gene information line if line[0]=='>': coun...
identifier_body
codon_usage.py
TAG', 'TGA'], 'Cys':['TGT', 'TGC'], 'Trp':['TGG'], 'Pro':['CCT', 'CCC', 'CCA', 'CCG'], 'His':['CAT', 'CAC'], 'Gln':['CAA', 'CAG'], 'Arg':['CGT', 'CGC', 'CGA', 'CGG', 'AGA', 'AGG'], ...
plot_SP_LP
identifier_name
codon_usage.py
# read a gene sequence line else: gene_seq += line.strip() file.close() print('%s:\n%d genes added\n%d are non-triple\n'% (filename[:2],count_all, count_non_triple)) return (...
count_all += 1 # if a gene has been read, then append it to all_seq if the # sequence is triple if gene_seq!='': if len(gene_seq)%3: count_non_triple += 1 else: ...
conditional_block
game.rs
the next non-zero cell to position i // and retry this entry until line[i] becomes non-zero if line[i] == 0 { line[i] = line[j]; line[j] = 0; continue; // otherwise, if the current cell and next cell are the sa...
/// /// // | F | E | D | C | | F | B | 7 | 3 | /// // | B | A | 9 | 8 | => | E | A | 6 | 2 | /// // | 7 | 6 | 5 | 4 | | D | 9 | 5 | 1 | /// // | 3 | 2 | 1 | 0 | | C | 8 | 4 | 0 | /// /// assert_eq!(Game::transpose(0xFEDC_BA98_7654_3210), 0xFB73_EA62_D951_C840); /// `...
random_line_split
game.rs
the next non-zero cell to position i // and retry this entry until line[i] becomes non-zero if line[i] == 0 { line[i] = line[j]; line[j] = 0; continue; // otherwise, if the current cell and next cell are the sa...
{ pub board: u64 } impl Game { /// Constructs a new `tfe::Game`. /// /// `Game` stores a board internally as a `u64`. /// /// # Examples /// /// Simple example: /// /// ``` /// use tfe::Game; /// /// let mut game = Game::new(); /// # println!("{:016x}", game.board); ...
Game
identifier_name
svg.go
)) for idx, pt := range poly.Points { wall.Verts[idx].X = int(pt.X) wall.Verts[idx].Y = int(pt.Y) } return wall } func (poly *svgPolygon) generatePoints() { vals := strings.FieldsFunc(poly.PointsData, func(r rune) bool { return (r == ' ' || r == '\t' || r == ',') }) poly.Points = make([]svgVert, len(vals)...
} verts = append(verts, geos.NewCoord(p.Points[0].X, p.Points[0].Y)) if poly == nil { newPoly, err := geos.NewPolygon(verts) if err != nil { log.Fatal(fmt.Errorf("New poly creation error: %+v", err)) } poly = newPoly } else { uPoly, _ := geos.NewPolygon(verts) uPolyTy...
random_line_split
svg.go
func (poly *svgPolygon) generatePoints() { vals := strings.FieldsFunc(poly.PointsData, func(r rune) bool { return (r == ' ' || r == '\t' || r == ',') }) poly.Points = make([]svgVert, len(vals)/2) for idx, _ := range poly.Points { x, _ := strconv.ParseFloat(vals[idx*2], 32) y, _ := strconv.ParseFloat(vals[id...
{ wall := jsonWedPolygon{Mode: poly.Mode} wall.Verts = make([]image.Point, len(poly.Points)) for idx, pt := range poly.Points { wall.Verts[idx].X = int(pt.X) wall.Verts[idx].Y = int(pt.Y) } return wall }
identifier_body
svg.go
)) for idx, pt := range poly.Points { wall.Verts[idx].X = int(pt.X) wall.Verts[idx].Y = int(pt.Y) } return wall } func (poly *svgPolygon) generatePoints() { vals := strings.FieldsFunc(poly.PointsData, func(r rune) bool { return (r == ' ' || r == '\t' || r == ',') }) poly.Points = make([]svgVert, len(vals)...
() { if len(group.Polygons) > 0 { var poly *geos.Geometry for _, p := range group.Polygons { if len(p.Points) > 2 { verts := make([]geos.Coord, 0) for _, v := range p.Points { verts = append(verts, geos.NewCoord(v.X, v.Y)) } verts = append(verts, geos.NewCoord(p.Points[0].X, p.Points[0].Y)...
MergePolygons
identifier_name
svg.go
for idx, pt := range poly.Points { wall.Verts[idx].X = int(pt.X) wall.Verts[idx].Y = int(pt.Y) } return wall } func (poly *svgPolygon) generatePoints() { vals := strings.FieldsFunc(poly.PointsData, func(r rune) bool { return (r == ' ' || r == '\t' || r == ',') }) poly.Points = make([]svgVert, len(vals)/2)...
return paths } func geosPolygonToPolygon(poly *geos.Geometry) svgPolygon { shell, err := poly.Shell() if err != nil { log.Fatal(fmt.Errorf("Shell creation error: %+v", err)) } mergedPoly := svgPolygon{} coords, err := shell.Coords() if err != nil { log.Fatal(fmt.Errorf("Coords error: %+v", err)) } for _...
{ p := &paths[idx] for pIdx, _ := range p.Polygons { poly := &p.Polygons[pIdx] for vIdx, _ := range poly.Points { v := &poly.Points[vIdx] v.X += group.translate.X v.Y += group.translate.Y } } }
conditional_block
db_feeds.go
!strings.EqualFold(feedData.Author.Email, "") || !strings.EqualFold(feedData.Author.Name, "") { var authorID int64 if !AuthorExist(db, feedData.Author.Name, feedData.Author.Email) { authorID, err = AddAuthor(db, feedData.Author.Name, feedData.Author.Email) if err != nil { return err } } else...
if !strings.EqualFold(data, "") { //Need to convert the data to a gofeed object feedParser := gofeed.NewParser() feedData, err = feedParser.Parse(strings.NewReader(data)) if err != nil { return feed, fmt.Errorf("gofeed parser was unable to parse data: %s -- %s", data, err.Error()) } } var tags []stri...
{ return feed, fmt.Errorf("No data to retrieve: %s", err.Error()) }
conditional_block
db_feeds.go
if !strings.EqualFold(episode.Author.Email, "") || !strings.EqualFold(episode.Author.Name, "") { var authorID int64 if !AuthorExist(db, episode.Author.Name, episode.Author.Email) { authorID, err = AddAuthor(db, episode.Author.Name, episode.Author.Email) if err != nil { return err } ...
FeedURLExist
identifier_name
db_feeds.go
!strings.EqualFold(feedData.Author.Email, "") || !strings.EqualFold(feedData.Author.Name, "") { var authorID int64 if !AuthorExist(db, feedData.Author.Name, feedData.Author.Email) { authorID, err = AddAuthor(db, feedData.Author.Name, feedData.Author.Email) if err != nil { return err } } else...
if !strings.EqualFold(data, "") { //Need to convert the data to a gofeed object feedParser := gofeed.NewParser() feedData, err = feedParser.Parse(strings.NewReader(data)) if err != nil { return feed, fmt.Errorf("gofeed parser was unable to parse data: %s -- %s", data, err.Error()) } } var tags []strin...
{ var feedData *gofeed.Feed url, err := GetFeedURL(db, id) if err != nil { log.Fatal(err) } title, err := GetFeedTitle(db, id) if err != nil { log.Fatal(err) } if strings.EqualFold(title, "") { title = url } data, err := GetFeedRawData(db, id) if err != nil { return feed, fmt.Errorf("No data to re...
identifier_body
db_feeds.go
) if err != nil { log.Fatal(err) } title, err := GetFeedTitle(db, id) if err != nil { log.Fatal(err) } if strings.EqualFold(title, "") { title = url } data, err := GetFeedRawData(db, id) if err != nil { return feed, fmt.Errorf("No data to retrieve: %s", err.Error()) } if !strings.EqualFold(data, "...
if err != nil { log.Fatal(err)
random_line_split
rtmDiskUsage.js
this.filterUsageText.getValue()) { this.txnFilterDiskUsage = +this.filterUsageText.getValue(); common.WebEnv.Save(this.envKeyUsageLimit, this.txnFilterDiskUsage); this.frameRefresh(); } }, specialkeyEvent: function(me, e) { if (e.getKey() === e.ENTER && me.ol...
a.rows[ix][0], // mount name adata.rows[ix][1], // file system adata.rows[ix][2], // ratio Math.trunc(+adata.rows[ix][3]), // used size Math.trunc(+adata.rows[ix][4]) // tota size ...
conditional_block
rtmDiskUsage.js
FilterDiskUsage = +this.filterUsageText.getValue(); common.WebEnv.Save(this.envKeyUsageLimit, this.txnFilterDiskUsage); this.frameRefresh(); } }, specialkeyEvent: function(me, e) { if (e.getKey() === e.ENTER && me.oldValue !== me.value) { if (me.value < 0) { ...
});
random_line_split
exif-tags.ts
Method", 0x923A : "CIP3DataFile", 0x923B : "CIP3Sheet", 0x923C : "CIP3Side", 0x923F : "StoNits", 0x927C : "MakerNote", 0x9286 : "UserComment", 0x9290 : "SubSecTime", 0x9291 : "SubSecTimeOriginal", 0x9292 : "SubSecTimeDigitized", 0x932F : "MSDocumentText", 0x9330 : "MSProperty...
0xC715 : "ForwardMatrix2",
random_line_split
preprocessing_lpba40.py
import numpy as np import SimpleITK as sitk import matplotlib.pyplot as plt import scipy.stats as stats DEFAULT_CUTOFF = 0.01, 0.99 STANDARD_RANGE = 0, 100 def resample_image(itk_image, out_spacing=(2.0, 2.0, 2.0), is_label=False): original_spacing = itk_image.GetSpacing() original_size = itk_image.GetSize(...
import os import subprocess
random_line_split
preprocessing_lpba40.py
is_label: resample.SetInterpolator(sitk.sitkNearestNeighbor) else: resample.SetInterpolator(sitk.sitkBSpline) return resample.Execute(itk_image) def center_crop(img, size_ratio): x, y, z = img.shape size_ratio_x, size_ratio_y, size_ratio_z = size_ratio size_x = size_ratio_x s...
if not os.path.exists(str(output_path_mask)): os.makedirs(str(output_path_mask)) for i in list(range(1, 41, 1)): for j in list(range(1, 41, 1)): # ~~~~~~~~~~~~~~~ images ~~~~~~~~~~~~~~~ volpath = os.path.join(input_path, 'l{}_to_l{}.nii'.format(str(i), str(j))) ...
os.makedirs(str(output_path_hs_small))
conditional_block
preprocessing_lpba40.py
is_label: resample.SetInterpolator(sitk.sitkNearestNeighbor) else: resample.SetInterpolator(sitk.sitkBSpline) return resample.Execute(itk_image) def center_crop(img, size_ratio): x, y, z = img.shape size_ratio_x, size_ratio_y, size_ratio_z = size_ratio size_x = size_ratio_x s...
def _get_average_mapping(percentiles_database): """Map the landmarks of the database to the chosen range. Args: percentiles_database: Percentiles database over which to perform the averaging. """ # Assuming percentiles_database.shape == (num_data_points, num_percentiles) pc1 ...
quartiles = np.arange(25, 100, 25).tolist() deciles = np.arange(10, 100, 10).tolist() all_percentiles = list(percentiles_cutoff) + quartiles + deciles percentiles = sorted(set(all_percentiles)) return np.array(percentiles)
identifier_body
preprocessing_lpba40.py
is_label: resample.SetInterpolator(sitk.sitkNearestNeighbor) else: resample.SetInterpolator(sitk.sitkBSpline) return resample.Execute(itk_image) def center_crop(img, size_ratio): x, y, z = img.shape size_ratio_x, size_ratio_y, size_ratio_z = size_ratio size_x = size_ratio_x s...
(array, landmarks, mask=None, cutoff=None, epsilon=1e-5): cutoff_ = DEFAULT_CUTOFF if cutoff is None else cutoff mapping = landmarks data = array shape = data.shape data = data.reshape(-1).astype(np.float32) if mask is None: mask = np.ones_like(data, np.bool) mask = mask.reshape(-1...
normalize
identifier_name
git.rs
DirBuilder, File}; use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf}; use std::process::Command as SystemCommand; use crate::error::{RLibError, Result}; //-------------------------------------------------------------------------------// // Enums & Structs //-----------------...
let path = self.local_path.to_string_lossy().to_string() + "\\*.*"; let _ = SystemCommand::new("attrib").arg("-r").arg(path).arg("/s").output(); }
conditional_block
git.rs
file is licensed under the MIT license, which can be found here: // https://github.com/Frodo45127/rpfm/blob/master/LICENSE. //---------------------------------------------------------------------------// //! This module contains the code for the limited Git support. use git2::{Reference, ReferenceFormat, Repository,...
self, contents: &str) -> Result<()> { let mut file = BufWriter::new(File::create(self.local_path.join(".gitignore"))?); file.write_all(contents.as_bytes()).map_err(From::from) } /// This function switches the branch of a `GitIntegration` to the provided refspec. pub fn checkout_branch(&self...
d_gitignore(&
identifier_name
git.rs
file is licensed under the MIT license, which can be found here: // https://github.com/Frodo45127/rpfm/blob/master/LICENSE. //---------------------------------------------------------------------------// //! This module contains the code for the limited Git support. use git2::{Reference, ReferenceFormat, Repository,...
Err(_) => return Ok(GitResponse::NoLocalFiles), }; // Just in case there are loose changes, stash them. // Ignore a fail on this, as it's possible we don't have contents to stash. let current_branch_name = Reference::normalize_name(repo.head()?.name().unwrap(), ReferenceForm...
let mut repo = match Repository::open(&self.local_path) { Ok(repo) => repo, // If this fails, it means we either we don´t have the repo downloaded, or we have a folder without the .git folder.
random_line_split
RPMutils.py
#the number of neurons to use per dimension NEURONS_PER_DIMENSION = 25 #random seed to use when generating vocabulary vectors VOCABULARY_SEED = 100 #the minimum confidence value we will require in order to decide we have a match in cleanup memory MIN_CONFIDENCE = 0.7 #the minimum value we will require to pick either...
#prediction of blank cell from neural module def hypothesisFile(modulename): return os.path.join(CURR_LOCATION, "data", FOLDER_NAME, modulename + "_hypothesis_" + str(JOB_ID) + ".txt") #file to record the rules used to solve a matrix def ruleFile(): return os.path.join(CURR_LOCATION, "data", FOLDER_NAME, "rule...
#rule output from neural module def resultFile(modulename): return os.path.join(CURR_LOCATION, "data", FOLDER_NAME, modulename + "_result_" + str(JOB_ID) + ".txt")
random_line_split
RPMutils.py
#the number of neurons to use per dimension NEURONS_PER_DIMENSION = 25 #random seed to use when generating vocabulary vectors VOCABULARY_SEED = 100 #the minimum confidence value we will require in order to decide we have a match in cleanup memory MIN_CONFIDENCE = 0.7 #the minimum value we will require to pick either...
(names, vectors): return [FunctionInput(names[i], [ConstantFunction(1,x) for x in vec], Units.UNK) for i,vec in enumerate(vectors)] #load vectors from a file and create corresponding output functions def loadInputVectors(filename): file = open(filename) vectors = [str2floatlist(line) for line in file] ...
makeInputVectors
identifier_name
RPMutils.py
NEURONS_PER_DIMENSION = 25 #random seed to use when generating vocabulary vectors VOCABULARY_SEED = 100 #the minimum confidence value we will require in order to decide we have a match in cleanup memory MIN_CONFIDENCE = 0.7 #the minimum value we will require to pick either the same or different result #SAMEDIFF_CHO...
return math.sqrt(sum([x**2 for x in vec]))
identifier_body
RPMutils.py
2 #the size (number of base words) of vocabulary to use (we have different versions depending on how many base words are allowed) VOCAB_SIZE = 80 #true if we are running the controller, false if we are just running the individual modules RUN_WITH_CONTROLLER = True #the maximum similarity we will allow when generatin...
return 0.0
conditional_block
runtime.py
_periods * period, but since there is no delay in the first loop, there will be num_period + 1 loop iterations. """ if period < 0.0: raise RuntimeError('Specified period is invalid. Must be >= 0.') if num_period is not No...
"""Execute control loop defined by agent Interfaces with PlatformIO directly through the geopmdpy.pio module. Args: argv (list(str)): Arguments for application that is executed policy (object): Policy for Agent to use during the run Returns: str: Human rea...
identifier_body
runtime.py
90643310547 """ def __init__(self, period, num_period=None): """Constructor for timed loop object The number of loops executed is one greater than the number of time intervals requested, and that the first iteration is not delayed. The total amount of time spanned by the loop...
random_line_split
runtime.py
: 0.10126090049743652 2: 0.20174455642700195 3: 0.30123186111450195 4: 0.4010961055755615 5: 0.5020360946655273 6: 0.6011238098144531 7: 0.7011349201202393 8: 0.8020164966583252 9: 0.9015650749206543 10: 1.0021190643310547 """ def __init_...
(self): """Get the target time interval for the control loop Returns: float: Time interval in seconds """ raise NotImplementedError('Agent is an abstract base class') def get_report(self): """Summary of all data collected by calls to update() The repor...
get_period
identifier_name
runtime.py
if num_period < 0: raise RuntimeError('Specified num_period is invalid. Must be > 0.') if not isinstance(num_period, int): raise ValueError('num_period must be a whole number.') self._period = period self._num_loop = num_period # Add one to ensure: ...
break
conditional_block
FutureWork.py
"NamesS":NamesShort, "NamesGlobal":NFull, "NamesGlobalS":["Depth\\ [km]", "Vs\\ [km/s]", "Vp\\ [km/s]", "\\rho\\ [T/m^3]"], "DataUnits":"[km/s]", "DataName":"Phase\\ velocity\\ [km/s]", "DataAxis":"...
pool.terminate()
conditional_block
FutureWork.py
(): '''BUILDMODELSET is a function that will build the benchmark model. It does not take any arguments. ''' # Values for the benchmark model parameters: TrueModel1 = np.asarray([0.01, 0.05, 0.120, 0.280, 0.600]) # Thickness and Vs for the 3 layers (variable of the problem) TrueModel2 = np.asarray...
buildMODELSET_MASW
identifier_name
FutureWork.py
[0]),vp=Vp,vs=TrueModel1[nLayer-1:2*nLayer-1],rho=rho,periods=Periods,wave="rayleigh",mode=1,velocity="phase",flat_earth=True) Dataset2 = surf96(thickness=np.append(TrueModel2[0:nLayer-1], [0]),vp=Vp,vs=TrueModel2[nLayer-1:2*nLayer-1],rho=rho,periods=Periods,wave="rayleigh",mode=1,velocity="phase",flat_earth=True)...
forwardFun = funcSurf96 forward = {"Fun":forwardFun,"Axis":Periods} # Building the function for conditions (here, just checks that a sampled model is inside the prior) cond = lambda model: (np.logical_and(np.greater_equal(model,Mins),np.less_equal(model,Maxs))).all() # Initialize the model paramet...
import numpy as np from pysurf96 import surf96 Vp = np.asarray([0.300, 0.750, 1.5]) # Defined again inside the function for parallelization rho = np.asarray([1.5, 1.9, 2.2]) # Idem nLayer = 3 # Idem Frequency = np.logspace(0.1,1.5,50) # I...
identifier_body
FutureWork.py
[0]),vp=Vp,vs=TrueModel1[nLayer-1:2*nLayer-1],rho=rho,periods=Periods,wave="rayleigh",mode=1,velocity="phase",flat_earth=True) Dataset2 = surf96(thickness=np.append(TrueModel2[0:nLayer-1], [0]),vp=Vp,vs=TrueModel2[nLayer-1:2*nLayer-1],rho=rho,periods=Periods,wave="rayleigh",mode=1,velocity="phase",flat_earth=True)...
if ParallelComputing: pool = pp.ProcessPool(mp.cpu_count())# Create the parallel pool with at most the number of available CPU cores ppComp = [True, pool] else: ppComp = [False, None] # No parallel computing '''1) Building a prior with fixed, large number of layers''' if Ru...
seed(0)
random_line_split
MultinomialAdversarialNetwork.py
eter import ConfusionMeter import torch import torch.nn as nn import torch.nn.functional as functional import torch.optim as optim from torch.utils.data import ConcatDataset, DataLoader """ IMPORTANT: for some reason, Model (self.F_s,etc) will not work if inputs are not float32 => need to convert. Dont know if same t...
(self, k, m, model_params=None, log_params=None): super().__init__(k,m,model_params,log_params) def prepare_data(self,d): """ Assume d is a dictionary of dataset where d[domain] = another dataset class Assume labeled domain = train set, unlabeled = test """ t...
__init__
identifier_name
MultinomialAdversarialNetwork.py
eter import ConfusionMeter import torch import torch.nn as nn import torch.nn.functional as functional import torch.optim as optim from torch.utils.data import ConcatDataset, DataLoader """ IMPORTANT: for some reason, Model (self.F_s,etc) will not work if inputs are not float32 => need to convert. Dont know if same t...
for epoch in range(opt.max_epoch): self.F_s.train() self.C.train() self.D.train() for f in self.F_d.values(): f.train() # training accuracy correct, total = defaultdict(int), defaultdict(int) # D accuracy ...
train_loaders, train_iters, unlabeled_loaders, unlabeled_iters = self.prepare_data(d) #Training self.F_s = MlpFeatureExtractor(d['train'].X.shape[1], opt.F_hidden_sizes,opt.shared_hidden_size, opt.dropout) self.F_d = {} for domain in opt.domains: self.F_d[domain] = MlpFeature...
identifier_body
MultinomialAdversarialNetwork.py
eter import ConfusionMeter import torch import torch.nn as nn import torch.nn.functional as functional import torch.optim as optim from torch.utils.data import ConcatDataset, DataLoader """ IMPORTANT: for some reason, Model (self.F_s,etc) will not work if inputs are not float32 => need to convert. Dont know if same t...
return train_loaders, train_iters, unlabeled_loaders, unlabeled_iters def fit(self, d, *args, **kwargs): #minibatches = create_minibatch(X, y, z, batch_size) #TODO: make this able to fit consecutively train_loaders, train_iters, unlabeled_lo...
features, target = torch.from_numpy(d[domain].X.todense().astype('float32')), torch.from_numpy(d[domain].y)#.reshape(-1,1)) uset = data_utils.TensorDataset(features,target) unlabeled_loaders[domain] = DataLoader(uset,opt.batch_size, shuffle = True) unlabeled_iters[domain] = iter(unla...
conditional_block
MultinomialAdversarialNetwork.py
.meter import ConfusionMeter import torch import torch.nn as nn import torch.nn.functional as functional import torch.optim as optim from torch.utils.data import ConcatDataset, DataLoader """ IMPORTANT: for some reason, Model (self.F_s,etc) will not work if inputs are not float32 => need to convert. Dont know if same...
elif opt.loss.lower() == 'l2': d_targets = utils.get_random_domain_label(opt.loss, len(d_inputs)) l_d = functional.mse_loss(d_outputs, d_targets) if opt.lambd > 0: l_d *= opt.lambd ...
random_line_split
fid_pics.py
0' exp4.pz_std = 2.0 exp4.z_dim = 8 exp4.symmetrize = False exp4.dataset = 'mnist' exp4.alias = 'mnist_gan_dcgan' exp4.test_size = 1000 # Exp 5: CelebA with WAE+MMD on 64 dimensional Z space, BEGAN architecture exp5 = ExpInfo() exp5.trained_model_path = cluster_celeba_mmd_began_path...
if len(pic.shape) == 4: pic = pic[0] height = pic.shape[0] width = pic.shape[1] fig = plt.figure(frameon=False, figsize=(width, height))#, dpi=1) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) if exp.symmetrize: pic = (pic + 1.) / 2. if exp.datase...
identifier_body
fid_pics.py
_expC_81' cluster_mnist_mmd2d_path = './mount/GANs/results_mnist_pot_smaller_zdim2_21' cluster_mnist_gan_path = './mount/GANs/results_mnist_pot_sota_worst2d1' cluster_mnist_vae_path = './mount/GANs/results_mnist_vae_81' cluster_mnist_vae2d_path = './mount/GANs/results_mnist_vae_zdim2_21' cluster_cel...
elif exp_name == 'celeba_vae': exp = exp9 exp_list = [exp] for exp in exp_list: output_dir = os.path.join(OUT_DIR, exp.alias) create_dir(output_dir) z_dim = exp.z_dim pz_std = exp.pz_std dataset = exp.dataset model_path = exp.trained_model_path ...
exp = exp8
conditional_block
fid_pics.py
self.symmetrize = None self.dataset = None self.alias = None self.test_size = None def main(): exp_name = sys.argv[-1] create_dir(OUT_DIR) exp_names = ['mnist_gan', 'mnist_mmd', 'celeba_gan', 'celeba_mmd'] cluster_mnist_mmd_path = './mount/GANs/results_mnist_pot_sota_wo...
random_line_split
fid_pics.py
800' exp5.pz_std = 2.0 exp5.z_dim = 64 exp5.symmetrize = True exp5.dataset = 'celebA' exp5.alias = 'celeba_mmd_began' exp5.test_size = 512 # Exp 6: MNIST with VAE on 8 dimensional Z space, DCGAN architecture exp6 = ExpInfo() exp6.trained_model_path = cluster_mnist_vae_path exp6....
create_dir
identifier_name
server_utils.go
, nil } // Prepare bdev storage. Assumes validation has already been performed on server config. Hugepages // are required for both emulated (AIO devices) and real NVMe bdevs. VFIO and IOMMU are not // required for emulated NVMe. func prepBdevStorage(srv *server, iommuEnabled bool) error { defer srv.logDuration(track...
{ srv.log.Debugf("skipping mem check on engine %d, no bdevs", ei) engine.RUnlock() return nil }
conditional_block
server_utils.go
} // Ensure stable ordering of addresses. sort.Slice(addrs, func(i, j int) bool { if !isIPv4(addrs[i]) && isIPv4(addrs[j]) { return false } else if isIPv4(addrs[i]) && !isIPv4(addrs[j]) { return true } return bytes.Compare(addrs[i], addrs[j]) < 0 }) return &net.TCPAddr{IP: addrs[0], Port: iPort}, ni...
{ host, port, err := net.SplitHostPort(addr) if err != nil { return nil, errors.Wrapf(err, "unable to split %q", addr) } iPort, err := strconv.Atoi(port) if err != nil { return nil, errors.Wrapf(err, "unable to convert %q to int", port) } addrs, err := lookup(host) if err != nil { return nil, errors.Wrapf...
identifier_body
server_utils.go
f, err := os.OpenFile(path, os.O_WRONLY, 0644) if err != nil { // Work around a testing oddity that seems to be related to launching // the server via SSH, with the result that the /proc file is unwritable. if os.IsPermission(err) { log.Debugf("Unable to write core dump filter to %s: %s", path, err) retur...
return filepath.Join(cfg.Engines[0].Storage.Tiers.ScmConfigs()[0].Scm.MountPoint, "control_raft") } func writeCoreDumpFilter(log logging.Logger, path string, filter uint8) error {
random_line_split
server_utils.go
VMD && srv.cfg.DisableVFIO: srv.log.Info("VMD not enabled because VFIO disabled in config") case enableVMD && !iommuEnabled: srv.log.Info("VMD not enabled because IOMMU disabled on platform") case enableVMD && bdevCfgs.HaveEmulatedNVMe(): srv.log.Info("VMD not enabled because emulated NVMe devices found in conf...
registerEngineEventCallbacks
identifier_name
path_test.go
testutil.Setup(t, packageDir) t.Logf("Adding File: %s", inventoryFilePath) tf.WriteFile(t, inventoryFilePath, inventoryConfigMap) t.Logf("Adding File: %s", secondInventoryFilePath) tf.WriteFile(t, secondInventoryFilePath, secondInventoryConfigMap) t.Logf("Adding File: %s", podAFilePath) tf.WriteFile(t, podAFileP...
}) } } func TestFilterInputFile(t *testing.T) { tf := testutil.Setup(t) defer tf.Clean() testCases := map[string]struct { configObjects [][]byte expectedObjects [][]byte }{ "Empty config objects writes empty file": { configObjects: [][]byte{}, expectedObjects: [][]byte{}, }, "Only inventor...
{ assert.Equal(t, err.Error(), tc.errFromDemandOneDirectory) }
conditional_block
path_test.go
testutil.Setup(t, packageDir) t.Logf("Adding File: %s", inventoryFilePath) tf.WriteFile(t, inventoryFilePath, inventoryConfigMap) t.Logf("Adding File: %s", secondInventoryFilePath) tf.WriteFile(t, secondInventoryFilePath, secondInventoryConfigMap) t.Logf("Adding File: %s", podAFilePath) tf.WriteFile(t, podAFileP...
(configs ...[]byte) []byte { r := []byte{} for i, config := range configs { if i > 0 { r = append(r, []byte(configSeparator)...) } r = append(r, config...) } return r } func TestProcessPaths(t *testing.T) { tf := setupTestFilesystem(t) defer tf.Clean() trueVal := true testCases := map[string]struct {...
buildMultiResourceConfig
identifier_name
path_test.go
testutil.Setup(t, packageDir) t.Logf("Adding File: %s", inventoryFilePath) tf.WriteFile(t, inventoryFilePath, inventoryConfigMap) t.Logf("Adding File: %s", secondInventoryFilePath) tf.WriteFile(t, secondInventoryFilePath, secondInventoryConfigMap) t.Logf("Adding File: %s", podAFilePath) tf.WriteFile(t, podAFileP...
func TestProcessPaths(t *testing.T) { tf := setupTestFilesystem(t) defer tf.Clean() trueVal := true testCases := map[string]struct { paths []string expectedFileNameFlags genericclioptions.FileNameFlags errFromDemandOneDirectory string }{ "empty slice means reading from StdIn": { ...
{ r := []byte{} for i, config := range configs { if i > 0 { r = append(r, []byte(configSeparator)...) } r = append(r, config...) } return r }
identifier_body
path_test.go
testutil.Setup(t, packageDir) t.Logf("Adding File: %s", inventoryFilePath) tf.WriteFile(t, inventoryFilePath, inventoryConfigMap) t.Logf("Adding File: %s", secondInventoryFilePath) tf.WriteFile(t, secondInventoryFilePath, secondInventoryConfigMap) t.Logf("Adding File: %s", podAFilePath) tf.WriteFile(t, podAFileP...
} }) } } func TestFilterInputFile(t *testing.T) { tf := testutil.Setup(t) defer tf.Clean() testCases := map[string]struct { configObjects [][]byte expectedObjects [][]byte }{ "Empty config objects writes empty file": { configObjects: [][]byte{}, expectedObjects: [][]byte{}, }, "Only inve...
assert.Equal(t, tc.expectedFileNameFlags, fileNameFlags) if err != nil && err.Error() != tc.errFromDemandOneDirectory { assert.Equal(t, err.Error(), tc.errFromDemandOneDirectory)
random_line_split
pandas_gp.py
057,4073,4079,4091,4093,4099, # 4111,4127,4129,4133,4139,4153,4157,4159,4177,4201,4211,4217,4219, # 4229,4231] # load the data ibex = cPickle.load(open("ibex.pickle", "rb")) #we need to have pd_df_bool terminals for gp to work #better to have them as a column in the dataset #the...
sharpe = -99999
conditional_block
pandas_gp.py
constrained by the size of the vector ibex["Ones"] = True ibex["Zeros"] = False # Transaction costs - 10 Eur per contract #cost = 30 cost = 50 # equiv (30/10000) * 10 points # Split into train and test train = ibex["2000":"2015"].copy() test = ibex["2016":].copy() # Functions and terminal for GP class pd_df_floa...
nodes, edges, labels = gp.graph(individual) g = nx.Graph() g.add_nodes_from(nodes) g.add_edges_from(edges) pos = nx.drawing.nx_agraph.graphviz_layout(g, prog="dot") nx.draw_networkx_nodes(g, pos) nx.draw_networkx_edges(g, pos) nx.draw_networkx_labels(g, pos, labels) plt.show()
identifier_body
pandas_gp.py
531,1543,1549,1553,1559,1567,1571,1579,1583,1597,1601,1607, # 1609,1613,1619,1621,1627,1637,1657,1663,1667,1669,1693,1697,1699, # 1709,1721,1723,1733,1741,1747,1753,1759,1777,1783,1787,1789,1801, # 1811,1823,1831,1847,1861,1867,1871,1873,1877,1879,1889,1901,1907, # 1913,1931,1933,194...
pd_subtract
identifier_name
pandas_gp.py
1949,1951,1973,1979,1987,1993,1997,1999,2003,2011, # 2017,2027,2029,2039,2053,2063,2069,2081,2083,2087,2089,2099,2111, # 2113,2129,2131,2137,2141,2143,2153,2161,2179,2203,2207,2213,2221, # 2237,2239,2243,2251,2267,2269,2273,2281,2287,2293,2297,2309,2311, # 2333,2339,2341,2347,2351,23...
pset = gp.PrimitiveSetTyped('MAIN', [pd_df_float,
random_line_split
gke.go
/api/container/v1" ) type GKENodePoolCall struct { targetLabel string projectID string error error s *compute.Service ctx context.Context targetLabelValue string } func GKENodePool(ctx context.Context, projectID string) *GKENodePoolCall { s, err := compute.New...
() (*model.Report, error) { if r.error != nil { return nil, r.error } managerList, err := compute.NewInstanceGroupManagersService(r.s).AggregatedList(r.projectID).Do() if err != nil { return nil, err } // add instance group name of cluster node pool to Set gkeNodePoolInstanceGroupSet, err := r.getGKEInstan...
Recovery
identifier_name
gke.go
* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed ...
*
random_line_split
gke.go
[len(zoneUrlElements)-1] ms := compute.NewInstanceGroupManagersService(r.s) if _, err := ms.Resize(r.projectID, zone, manager.Name, size).Do(); err != nil { res = multierror.Append(res, err) continue } doneRes = append(doneRes, manager.Name) } time.Sleep(CallInterval) } return &model.Report...
{ //TODO Temp impl return l }
conditional_block
gke.go
/api/container/v1" ) type GKENodePoolCall struct { targetLabel string projectID string error error s *compute.Service ctx context.Context targetLabelValue string } func GKENodePool(ctx context.Context, projectID string) *GKENodePoolCall { s, err := compute.New...
func (r *GKENodePoolCall) Resize(size int64) (*model.Report, error) { if r.error != nil { return nil, r.error } // get all instance group mangers list managerList, err := compute.NewInstanceGroupManagersService(r.s).AggregatedList(r.projectID).Do() if err != nil { return nil, err } // add instance group ...
{ if r.error != nil { return r } r.targetLabel = labelName r.targetLabelValue = value return r }
identifier_body
blob.go
TA_AOT = 0 /* OOP-JIT sub-types -- XOJIT type kept for external dependencies */ CS_LINKAGE_APPLICATION_XOJIT_PREVIEWS = 1 CS_LINKAGE_APPLICATION_OOPJIT_INVALID = 0 CS_LINKAGE_APPLICATION_OOPJIT_PREVIEWS = 1 CS_LINKAGE_APPLICATION_OOPJIT_MLCOMPILER = 2 CSTYPE_INDEX_REQUIREMENTS = 0x00000002 /* compat with...
case CSSLOT_LAUNCH_CONSTRAINT_SELF: return "Launch Constraint (self)" case CSSLOT_LAUNCH_CONSTRAINT_PARENT:
random_line_split
blob.go
application types we support for linkage signatures */ CS_LINKAGE_APPLICATION_INVALID = 0 CS_LINKAGE_APPLICATION_ROSETTA = 1 /* XOJIT has been renamed to OOP-JIT */ CS_LINKAGE_APPLICATION_XOJIT = 2 CS_LINKAGE_APPLICATION_OOPJIT = 2 /* The set of application sub-types we support for linkage signatures */ /* ...
if err := binary.Write(buf, o, s.Index); err != nil { return fmt.Errorf("failed to write SuperBlob indices to buffer: %v", err) } for _, blob := range s.Blobs { if err := binary.Write(buf, o, blob.BlobHeader); err != nil { return fmt.Errorf("failed to write blob header to superblob buffer: %v", err) } if...
{ return fmt.Errorf("failed to write SuperBlob header to buffer: %v", err) }
conditional_block
blob.go
_DEPENDENCY_BLOB Magic = 0xfade0c05 MAGIC_EMBEDDED_ENTITLEMENTS Magic = 0xfade7171 /* embedded entitlements */ MAGIC_EMBEDDED_ENTITLEMENTS_DER Magic = 0xfade7172 /* embedded entitlements */ MAGIC_DETACHED_SIGNATURE Magic = 0xfade0cc1 // multi-arch collection of embedded signatures MAGIC_BLOBWRAPPER...
{ h := sha256.New() if err := binary.Write(h, binary.BigEndian, b.BlobHeader); err != nil { return nil, fmt.Errorf("failed to hash blob header: %v", err) } if err := binary.Write(h, binary.BigEndian, b.Data); err != nil { return nil, fmt.Errorf("failed to hash blob header: %v", err) } return h.Sum(nil), nil }
identifier_body
blob.go
0xfade0c00 // single Requirement blob MAGIC_REQUIREMENTS Magic = 0xfade0c01 // Requirements vector (internal requirements) MAGIC_CODEDIRECTORY Magic = 0xfade0c02 // CodeDirectory blob MAGIC_EMBEDDED_SIGNATURE Magic = 0xfade0cc0 // embedded form of signature data MAGIC_EMBEDDED_SIG...
Sha256Hash
identifier_name
storage.go
sql.DB func executeStatements() { for { if qa, ok := <-chQueryArgs; ok { _, err := db.Exec(qa.query, qa.args...) if err != nil { log.Fatal(err) } } } } //NewStorage creates returns a new Storage object. //DBName is the name of the sqllite database file where //all the users and tweets data will be ...
} //StoreScreenName inserts the given screenName into the `screenames` table func (s *Storage) StoreScreenName(screenName string) { _, err := s.db.Exec("INSERT OR IGNORE INTO screennames (screen_name) VALUES (?)", screenName) if err != nil { log.Fatal(err) } } //StoreUser inserts the Twitter user details into t...
{ log.Fatalf("%q: %s\n", err, sqlStmt) return }
conditional_block
storage.go
sql.DB func executeStatements() { for { if qa, ok := <-chQueryArgs; ok { _, err := db.Exec(qa.query, qa.args...) if err != nil { log.Fatal(err) } } } } //NewStorage creates returns a new Storage object. //DBName is the name of the sqllite database file where //all the users and tweets data will be ...
} mutex.Unlock() return s } func (s *Storage) setupTables() { tableName := "users" s.makeTable(tableName, fmt.Sprintf(` CREATE TABLE IF NOT EXISTS %s ( user_id INTEGER PRIMARY KEY, screen_name TEXT CONSTRAINT uniquescreenname UNIQUE, description TEXT CONSTRAINT defaultdesc DEFAULT "", ...
s.setupTables()
random_line_split
storage.go
{} mutex.Lock() if db == nil { s.checkMakeDatabase(DBName) db = s.db if chQueryArgs == nil { chQueryArgs = make(chan *queryArgs, 100) go executeStatements() } s.setupTables() } mutex.Unlock() return s } func (s *Storage) setupTables() { tableName := "users" s.makeTable(tableName, fmt.Sprintf(` ...
MarkUserLatestTweetsCollected
identifier_name
storage.go
sql.DB func executeStatements() { for { if qa, ok := <-chQueryArgs; ok { _, err := db.Exec(qa.query, qa.args...) if err != nil { log.Fatal(err) } } } } //NewStorage creates returns a new Storage object. //DBName is the name of the sqllite database file where //all the users and tweets data will be ...
//StoreUser inserts the Twitter user details into the `users` table. func (s *Storage) StoreUser(userID int64, screenName, description string, protected bool, blob []byte) { chQueryArgs <- &queryArgs{"INSERT OR IGNORE INTO users (user_id, screen_name, description, protected, blob) VALUES (?, ?, ?, ?, ?)", []interf...
{ _, err := s.db.Exec("INSERT OR IGNORE INTO screennames (screen_name) VALUES (?)", screenName) if err != nil { log.Fatal(err) } }
identifier_body
equilibrium_computation.py
3.5)+Iext2 =0 p0 = 0.2 * x1eq - 0.3 * (zeq - 3.5) + Iext2 x2eq = numpy.zeros(shape, dtype=type) for i in range(shape[1]): x2eq[0 ,i] = numpy.min(numpy.real(numpy.roots([-1.0, 0.0, 1.0, p0[0 ,i]]))) return x2eq, y2eq # def pop2eq_calc(n_regions,x1eq,zeq,Iext2): # shape = x1eq.shape # type...
jac_e_x1o = -numpy.dot(i_x0, K[:,iE]) * w[iE][:,ix0] jac_x0_x0e = numpy.zeros((no_x0,no_e),dtype = type) jac_x0_x1o = numpy.diag(4 + 3 * x[ix0] ** 2 + 4 * x[ix0] + K[ix0] * numpy.sum(w[ix0][:,ix0], axis=1)) \ - numpy.dot(i_x0, K[:, ix0]) * w[ix0][:, ix0] jac = numpy.zeros((n_regions,n_...
jac_e_x0e = numpy.diag(- 4 * rx0[iE])
random_line_split
equilibrium_computation.py
.5)+Iext2 =0 p0 = 0.2 * x1eq - 0.3 * (zeq - 3.5) + Iext2 x2eq = numpy.zeros(shape, dtype=type) for i in range(shape[1]):
return x2eq, y2eq # def pop2eq_calc(n_regions,x1eq,zeq,Iext2): # shape = x1eq.shape # type = x1eq.dtype # #g_eq = 0.1*x1eq (1) # #y2eq = 6*(x2eq+0.25)*x1eq (2) # #-x2eq**3 + x2eq -y2eq+2*g_eq-0.3*(zeq-3.5)+Iext2 =0=> (1),(2) # #-x2eq**3 + x2eq -6*(x2eq+0.25)*x1eq+2*0.1*x1eq-0.3*(zeq-3.5)+Iext2 ...
x2eq[0 ,i] = numpy.min(numpy.real(numpy.roots([-1.0, 0.0, 1.0, p0[0 ,i]])))
conditional_block
equilibrium_computation.py
(X1_DEF, X1_EQ_CR_DEF, n_regions): #The default initial condition for x1 equilibrium search return numpy.repeat(numpy.array((X1_EQ_CR_DEF + X1_DEF) / 2.0), n_regions) def x1_lin_def(X1_DEF, X1_EQ_CR_DEF, n_regions): # The point of the linear Taylor expansion return numpy.repeat(numpy.array((X1_EQ_CR_D...
x1eq_def
identifier_name
equilibrium_computation.py
def zeq_6d_calc(x1eq, y0, Iext1): return fx1_6d_calc(x1eq, z=0, y0=y0, Iext1=Iext1) def y1eq_calc(x1eq, d=5.0): return 1 - d * x1eq ** 2 def pop2eq_calc(x1eq, zeq, Iext2): shape = x1eq.shape type = x1eq.dtype # g_eq = 0.1*x1eq (1) # y2eq = 0 (2) y2eq = numpy.zeros(shape, dtype=type) ...
return fx1_2d_calc(x1eq, z=0, y0=y0, Iext1=Iext1)
identifier_body
hverse-encounter-helper.user.js
1.8.0 - title text now includes a short description of the last event detected, updating cross-tab v1.9.0 - reverted to background tabs for the automatic link opening - the rest has changed enough that foregrounding is too annoying; if `#game` is added to URL, opens in current tab v1.10.0 - shorten the time-since label...
news.first().prepend(eventPane); } else if (gallery.length) { gallery.after(eventPane); } } if (!eventPane .find('a[href]') .filter((i, e) => (e.href || '').toLowerCase().includes('hentaiverse.org')) .length ) { eventPane.append('<p><a href="https://hentaiverse.org/">Enter the HentaiVerse</a></p>...
const gallery = $('#nb'); if (news.length) {
random_line_split
hverse-encounter-helper.user.js
1.8.0 - title text now includes a short description of the last event detected, updating cross-tab v1.9.0 - reverted to background tabs for the automatic link opening - the rest has changed enough that foregrounding is too annoying; if `#game` is added to URL, opens in current tab v1.10.0 - shorten the time-since label...
this); for (let i = 0; i < 5; i++) { s += bits.splice(Math.floor(Math.random() * bits.length), 1); } return s; }, }); // SCRIPT CORE BEGINS \\ ((window, $, moment) => { // eslint-disable-next-line no-extend-native Set.prototype.addAll = Set.prototype.addAll || function addAll(iterable) { Array.from(iter...
from(
identifier_name
hverse-encounter-helper.user.js
1.8.0 - title text now includes a short description of the last event detected, updating cross-tab v1.9.0 - reverted to background tabs for the automatic link opening - the rest has changed enough that foregrounding is too annoying; if `#game` is added to URL, opens in current tab v1.10.0 - shorten the time-since label...
LAST_EVENT_TIMESTAMP_KEY, 0) || Date.now().valueOf()); const expandTemplate = (tmpl, durationObj, eventKey) => { const durationStr = durationObj.humanize(); return tmpl .replace(/\$PERIOD\$/gu, durationStr) .replace( /\$PERIOD.SHORT\$/gu, durationStr .replace(/^a\s+few\s+/ui, "0 ") .replace...
nt.js library').css('border-bottom', '2px dotted red'); return; } const lastEvent = () => moment(GM_getValue(
conditional_block
hverse-encounter-helper.user.js
1.8.0 - title text now includes a short description of the last event detected, updating cross-tab v1.9.0 - reverted to background tabs for the automatic link opening - the rest has changed enough that foregrounding is too annoying; if `#game` is added to URL, opens in current tab v1.10.0 - shorten the time-since label...
moment) => { // eslint-disable-next-line no-extend-native Set.prototype.addAll = Set.prototype.addAll || function addAll(iterable) { Array.from(iterable).forEach(e => this.add(e)); }; const genid = () => ([1e7] + 1e3 + 4e3 + 8e3 + 1e11) .repeat(2) .replace( /[018]/gu, c => (c ^ crypto.getRandomValues(n...
s); for (let i = 0; i < 5; i++) { s += bits.splice(Math.floor(Math.random() * bits.length), 1); } return s; }, }); // SCRIPT CORE BEGINS \\ ((window, $,
identifier_body
experiment_types.go
Names of candidates",format="byte" // +kubebuilder:printcolumn:name="phase",type="string",JSONPath=".status.phase",description="Phase of the experiment",format="byte" // +kubebuilder:printcolumn:name="winner found",type="boolean",JSONPath=".status.assessment.winner.winning_version_found",description="Winner identified"...
// Noted that at most one reward metric is allowed // If more than one reward criterion is included, the first would be used while others would be omitted // +optional Criteria []Criterion `json:"criteria,omitempty"` // TrafficControl provides instructions on traffic management for an experiment // +optional Tr...
// Criteria contains a list of Criterion for assessing the target service
random_line_split
Blockchain.go
} if b != nil { // Create the genesis block with a coinbase transaction txCoinbase := NewCoinbaseTransacion(address) genesisBlock := CreateGenesisBlock([]*Transaction{txCoinbase}) err := b.Put(genesisBlock.BlockHash, gobEncode(genesisBlock)) if err != nil { log.Panic(err) } // Update Tip o...
{ DBName := fmt.Sprintf(DBName, nodeID) if DBExists(DBName) { fmt.Println("Genesis block already exist!") os.Exit(1) } fmt.Println("Creating genesis block....") db, err := bolt.Open(DBName, 0600, nil) if err != nil { log.Panic(err) } defer db.Close() err = db.Update(func(tx *bolt.Tx) error { b, err...
identifier_body
Blockchain.go
= append(txs, tx) } return txs } // Package transactions and mine a new Block func (blockchain *Blockchain) MineNewBlock(originalTxs []*Transaction) *Block { // Reward of mining a block coinBaseTransaction := NewRewardTransacion() txs := []*Transaction{coinBaseTransaction} txs = append(txs, originalTxs...) // ...
fmt.Println("没找到对应交易") } else { //fmt.Println("preTxs___________________________________") //fmt.Println(prevT
if len(prevTxs) == 0 {
random_line_split
Blockchain.go
= append(txs, tx) } return txs } // Package transactions and mine a new Block func (blockchain *Blockchain) MineNewBlock(originalTxs []*Transaction) *Block { // Reward of mining a block coinBaseTransaction := NewRewardTransacion() txs := []*Transaction{coinBaseTransaction} txs = append(txs, originalTxs...) // ...
ame := fmt.Sprintf(DBName, nodeID) if DBExists(DBName) { db, err := bolt.Open(DBName, 0600, nil) if err != nil { log.Panic(err) } defer db.Close() var blockchain *Blockchain err = db.View(func(tx *bolt.Tx) error { b := tx.Bucket([]byte(BlockBucketName)) if b != nil { hash := b.Get([]byte("l"))...
*Blockchain { DBN
conditional_block
Blockchain.go
// If current block is genesis block, exit loop if big.NewInt(0).Cmp(hashInt) == 0 { break } } return utxos } // calculate utxos func caculate(tx *Transaction, address string, spentOutputMap map[string][]int, utxos []*UTXO) []*UTXO { // collect all inputs into spentOutputMap if !tx.IsCoinBaseTransaction() ...
.NewInt(0
identifier_name
channel.pb.go
,name=payload,proto3" json:"payload,omitempty"` } func (x *Message) Reset() { *x = Message{} if protoimpl.UnsafeEnabled { mi := &file_channel_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Message) String() string { return protoimpl.X.MessageStr...
}.Build() File_channel_proto = out.File file_channel_proto_rawDesc = nil file_channel_proto_goTypes = nil file_channel_proto_depIdxs = nil } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure t...
random_line_split
channel.pb.go
0x6f, 0x74, 0x6f, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x0e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x00, 0x28, 0x01, 0x30, 0x01, 0x12, 0x30, 0x0a, 0x08, 0x50, 0x65, 0x65, 0x72, 0x43, 0x68, 0x61, 0x74, 0x12, 0x0e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,...
{ return srv.(ChannelServer).PeerChat(&channelPeerChatServer{stream}) }
identifier_body
channel.pb.go
=payload,proto3" json:"payload,omitempty"` } func (x *Message) Reset() { *x = Message{} if protoimpl.UnsafeEnabled { mi := &file_channel_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Message) String() string { return protoimpl.X.MessageStringOf...
type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_channel_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 1, }, GoTypes: file_channel_proto_goTypes, Depen...
{ file_channel_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Message); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } }
conditional_block
channel.pb.go
=payload,proto3" json:"payload,omitempty"` } func (x *Message) Reset() { *x = Message{} if protoimpl.UnsafeEnabled { mi := &file_channel_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Message) String() string { return protoimpl.X.MessageStringOf...
() ([]byte, []int) { return file_channel_proto_rawDescGZIP(), []int{0} } func (x *Message) GetPayload() []byte { if x != nil { return x.Payload } return nil } var File_channel_proto protoreflect.FileDescriptor var file_channel_proto_rawDesc = []byte{ 0x0a, 0x0d, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x2e,...
Descriptor
identifier_name
ag.py
.sub("(\n\r|\n|\r\n)[ \t]*(\n\r|\n|\r\n)","\n\n",s) defined=set() data=[] rs=p.split(s) # cut via "\n\n\n" #print(p.groups+1),print(rs[1:1+p.groups+1]),print(rs[1+(p.groups+1)*1:1+(p.groups+1)*2]),exit() #print(rs[0]),exit() # debug for i in range(1,len(rs),p.groups+1): # rs[0] is "not match", omi...
x.size() for k,v in tmp.items(): rtv[k]+=v
conditional_block
ag.py
ommited this function will NOT do the arrangement make sure the lines of constraints: labels are in increasing order items of the same label are in lexicographical order format: each line: label item ([ \t]*\~?[0-9]+|include|gonear) lines not match will be omitted ''' # pre...
ef fromStr(self,s,cd='./',extView=None): s=s.replace('\r','') ''' \r\n , \n\r , \n -> \n format: see self.fromTxt ''' # unset filename self.filename=None self.extendedView=extView #old=self.sets p=self.__class__.parser_set s=re.sub("(\n\r|\n|\r\n)[ \t]*(\n\r|\n|\r\n)","\n\n",s) def...
rn [ k for k in self.sets if self.getSucc(k)=='-' ] d
identifier_body
ag.py
self.constraints=[] # [ (int(label),item,negate?) ... ] self.maxLabel=-1 self.including=False self.arrangeNeeded=False self.extendedView=None # inherit from Goaltree def __eq__(self,rhs): self.arrange() if isinstance(rhs,self.__class__): return self.constraints==rhs.constraints else: ra...
random_line_split
ag.py
is ommited this function will NOT do the arrangement make sure the lines of constraints: labels are in increasing order items of the same label are in lexicographical order format: each line: label item ([ \t]*\~?[0-9]+|include|gonear) lines not match will be omitted ''' # ...
f,k): return self.sets[k][2] def getSuccsStr(self,k): return self.sets[k][3][0] def getPrecs(self,k): return self.sets[k][4] def getOpts(self,k): rtv=dict(self.sets[k][5]) for i in rtv: rtv[i]=rtv[i][1] return rtv def getFinals(self): return [ k for k in self.sets if self.getSucc(k)=='-' ] ...
uccs(sel
identifier_name
daemon.go
Manager returns the underlay peer.TaskManager for downloading when embed dragonfly in custom binary ExportTaskManager() peer.TaskManager // ExportPeerHost returns the underlay scheduler.PeerHost for scheduling ExportPeerHost() *scheduler.PeerHost } type clientDaemon struct { once *sync.Once done chan bool sched...
if opt.Security.Cert == "" || opt.Security.Key == "" { return nil, -1, errors.New("empty cert or key for tls") } // Create the TLS ClientOption with the CA pool and enable Client certificate validation if opt.Security.TLSConfig == nil { opt.Security.TLSConfig = &tls.Config{} } tlsConfig := opt.Security.TLS...
{ return ln, port, err }
conditional_block
daemon.go
(pemClientCA) { return nil, fmt.Errorf("failed to add client CA's certificate") } // Load server's certificate and private key serverCert, err := tls.LoadX509KeyPair(opt.Cert, opt.Key) if err != nil { return nil, err } // Create the credentials and return it if opt.TLSConfig == nil { opt.TLSConfig = &tls...
{ return cd.PeerTaskManager }
identifier_body
daemon.go
Manager returns the underlay peer.TaskManager for downloading when embed dragonfly in custom binary ExportTaskManager() peer.TaskManager // ExportPeerHost returns the underlay scheduler.PeerHost for scheduling ExportPeerHost() *scheduler.PeerHost } type clientDaemon struct { once *sync.Once done chan bool sched...
schedPeerHost: host, Option: *opt, RPCManager: rpcManager, PeerTaskManager: peerTaskManager, PieceManager: pieceManager, ProxyManager: proxyManager, UploadManager: uploadManager, StorageManager: storageManager, GCManager: gc.NewManager(opt.GCInterval.Duration), }, nil } f...
once: &sync.Once{}, done: make(chan bool),
random_line_split
daemon.go
Manager returns the underlay peer.TaskManager for downloading when embed dragonfly in custom binary ExportTaskManager() peer.TaskManager // ExportPeerHost returns the underlay scheduler.PeerHost for scheduling ExportPeerHost() *scheduler.PeerHost } type clientDaemon struct { once *sync.Once done chan bool sched...
(opt config.SecurityOption) (credentials.TransportCredentials, error) { // Load certificate of the CA who signed client's certificate pemClientCA, err := ioutil.ReadFile(opt.CACert) if err != nil { return nil, err } certPool := x509.NewCertPool() if !certPool.AppendCertsFromPEM(pemClientCA) { return nil, fmt...
loadGPRCTLSCredentials
identifier_name
main.rs
: {}", details), } } } fn connect_db() -> Result<Connection, ServiceError> { let url = env::var("DATABASE_URL").unwrap_or(String::from(DEFAULT_URL)); println!("Connecting: {}", &url); match Connection::connect(url, TlsMode::None) { Ok(connection) => Ok(connection), Err(error) =...
struct SearchService; impl NewService for SearchService { type ReqBody = Body; type ResBody = Body; type Error = ServiceError; type Service = SearchService; type Future = Box<Future<Item = Self::Service, Error = Self::Error> + Send>; type InitError = ServiceError; fn new_service(&self) -...
{ futures::future::ok( Response::builder() .header(header::CONTENT_TYPE, "application/json") .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*") .header(header::ACCESS_CONTROL_ALLOW_METHODS, "GET") .header(header::ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type") ...
identifier_body
main.rs
: {}", details), } } } fn connect_db() -> Result<Connection, ServiceError> { let url = env::var("DATABASE_URL").unwrap_or(String::from(DEFAULT_URL)); println!("Connecting: {}", &url); match Connection::connect(url, TlsMode::None) { Ok(connection) => Ok(connection), Err(error) =...
(query: SearchPaginate, db: &Connection) -> FutureResult<Body, ServiceError> { let text = &query.text; let results = fetch_search_results(text.to_string(), query.page, db); futures::future::ok(Body::from( json!({ "meta": { "text": text, "page": query.page, "total": results.1 }, ...
search_text
identifier_name
main.rs
: {}", details), } } } fn connect_db() -> Result<Connection, ServiceError> { let url = env::var("DATABASE_URL").unwrap_or(String::from(DEFAULT_URL)); println!("Connecting: {}", &url); match Connection::connect(url, TlsMode::None) { Ok(connection) => Ok(connection), Err(error) =...
.unwrap(), ) } struct SearchService; impl NewService for SearchService { type ReqBody = Body; type ResBody = Body; type Error = ServiceError; type Service = SearchService; type Future = Box<Future<Item = Self::Service, Error = Self::Error> + Send>; type InitError = ServiceError...
.header(header::ACCESS_CONTROL_ALLOW_METHODS, "GET") .header(header::ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type") .body(body)
random_line_split
domain_randomization.py
to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A...
def randomizer(self) -> DomainRandomizer: # Forward to the wrapped DomainRandWrapper return self._wrapped_env.randomizer @randomizer.setter def randomizer(self, dr: DomainRandomizer): # Forward to the wrapped DomainRandWrapper self._wrapped_env.randomizer = dr def adapt...
self.dp_mapping = dp_mapping @property
random_line_split
domain_randomization.py
distribution of all randomizable domain parameters, pass `None` if you want to subclass wrapping another `DomainRandWrapper` and use its randomizer """ if not isinstance(inner_env(wrapped_env), SimEnv): raise pyrado.TypeErr(given=wrapp...
env = remove_env(env, DomainRandWrapper)
conditional_block
domain_randomization.py
to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A...
(self, init_state: np.ndarray = None, domain_param: dict = None) -> np.ndarray: if domain_param is None: # No explicit specification of domain parameters, so randomizer is requested if isinstance(self._buffer, dict): # The buffer consists of one domain parameter set ...
reset
identifier_name