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
efi.rs
_CORRUPTED = ERROR_BIT | 10, /// There is no more space on the file system. VOLUME_FULL = ERROR_BIT | 11, /// The device does not contain any medium to perform the operation. NO_MEDIA = ERROR_BIT | 12, /// The medium in the device has changed since the last access. ...
{ let string = match *self { EFI_MEMORY_TYPE::EfiReservedMemoryType => "ReservedMemory", EFI_MEMORY_TYPE::EfiLoaderCode => "LoaderCode", EFI_MEMORY_TYPE::EfiLoaderData => "LoaderData", EFI_MEMORY_TYPE::EfiBootServicesCode => "BootServicesCode", EFI_MEMORY_TYPE::EfiBootServicesData => ...
identifier_body
efi.rs
data pending upon return. NOT_READY = ERROR_BIT | 6, /// The physical device reported an error while attempting the operation. DEVICE_ERROR = ERROR_BIT | 7, /// The device cannot be written to. WRITE_PROTECTED = ERROR_BIT | 8, /// A resource has run out. ...
{ pub Hdr: EFI_TABLE_HEADER, // Task Priority Services dummy1: [usize;2], // Memory Services pub AllocatePages: unsafe extern "C" fn(Type: EFI_ALLOCATE_TYPE, MemoryType: EFI_MEMORY_TYPE, Pages:usize, Memory: &mut u64) -> EFI_STATUS, dymmy2a: [usize;1], pub GetMemoryMap: unsafe extern "C" fn(MemoryMapSize:...
EFI_BOOT_SERVICES
identifier_name
efi.rs
data pending upon return. NOT_READY = ERROR_BIT | 6, /// The physical device reported an error while attempting the operation. DEVICE_ERROR = ERROR_BIT | 7, /// The device cannot be written to. WRITE_PROTECTED = ERROR_BIT | 8, /// A resource has run out. ...
// Library Services dummy9a: [usize;2], pub LocateProtocol: unsafe extern "C" fn (Protocol: &EFI_GUID, Registration: *mut c_void, Interface: &mut *mut c_void) -> EFI_STATUS, dummy9b: [usize;2], // 32-bit CRC Services dummy10: [usize;1], // Miscellaneous Services dummy11: [usize;3], } #[repr(C)] pub stru...
dummy7: [usize;2], // Open and Close Protocol Services dummy8: [usize;3],
random_line_split
schellyhook.go
MB float64 `json:"size_mb",omitempty` } //Backuper interface for who is implementing specific backup operations on backend type Backuper interface { //Init register command line flags here etc Init() error //RegisterFlags register flags for command line options RegisterFlags() error //CreateNewBackup create a ne...
(w http.ResponseWriter, r *http.Request) { logrus.Debugf("GetBackup r=%s", r) params := mux.Vars(r) apiID := params["id"] if RunningBackupAPIID == apiID { sendSchellyResponse(apiID, "", "running", "backup is running", -1, http.StatusOK, w) return } resp, err := currentBackuper.GetBackup(apiID) if err != n...
getBackup
identifier_name
schellyhook.go
} currentBackuper = backuper err := currentBackuper.RegisterFlags() if err != nil { return err } listenPort := flag.Int("listen-port", 7070, "REST API server listen port") listenIP := flag.String("listen-ip", "0.0.0.0", "REST API server listen ip address") logLevel := flag.String("log-level", "info", "debug, i...
{ uuid := uuid.NewV4() return uuid.String() }
identifier_body
schellyhook.go
MB float64 `json:"size_mb",omitempty` } //Backuper interface for who is implementing specific backup operations on backend type Backuper interface { //Init register command line flags here etc Init() error //RegisterFlags register flags for command line options RegisterFlags() error //CreateNewBackup create a ne...
bk, err := currentBackuper.GetBackup(apiID) if err != nil { logrus.Warnf("Error calling deleteBackup() with id %s", apiID) http.Error(w, err.Error(), http.StatusInternalServerError) return } else if bk == nil { logrus.Warnf("Backup %s not found", apiID) http.Error(w, fmt.Sprintf("Backup %s not found", api...
} return }
random_line_split
schellyhook.go
MB float64 `json:"size_mb",omitempty` } //Backuper interface for who is implementing specific backup operations on backend type Backuper interface { //Init register command line flags here etc Init() error //RegisterFlags register flags for command line options RegisterFlags() error //CreateNewBackup create a ne...
else { logrus.Debug("Pre-backup command success") } } //run
{ status := currentBackupContext.CmdRef.Status() if status.Exit == -1 { logrus.Warnf("Pre-backup command timeout enforced (%d seconds)", (status.StopTs-status.StartTs)/1000000000) } logrus.Debugf("Pre-backup command error. out=%s; err=%s", out, err.Error()) RunningBackupAPIID = "" return }
conditional_block
util.py
than that elif index > min_length - 1 and (start and index > len(start) - 1) and (end and index > len(end) - 1): continue if not start_reached: start_reached = True # workaround for "ch" being considered a separate char. # uses (temp_seed + variant) as a final n...
'''Convert list of (key, value) tuples to dict of lists''' dol = {} for k, val in lot: if k not in dol: dol[k] = [] dol[k].append(val) return dol
identifier_body
util.py
>>> start='ho', >>> end='hq', >>> variants={'o': ['oh', 'ok', 'obuh']}, >>> min_length=4, >>> index=1 >>> ) # From string 'hi', generates all strings that start with 'ho' and 'hq' (inclusive) and everything in between, >>> # whereas the string combinations start at index 1 ("...
url_obj = parse.urlparse(url) q_obj = parse.parse_qs(url_obj.query) q_obj = map_dict_val(lambda l: l[0], q_obj) return url_obj, q_obj def pack_url(url_obj, q_obj): ''' Get url string from URL object and Query object. Reverse of unpack_url ''' url_obj = url_obj._replace(query=par...
Reverse of pack_url '''
random_line_split
util.py
>>> start='ho', >>> end='hq', >>> variants={'o': ['oh', 'ok', 'obuh']}, >>> min_length=4, >>> index=1 >>> ) # From string 'hi', generates all strings that start with 'ho' and 'hq' (inclusive) and everything in between, >>> # whereas the string combinations start at index 1 ("...
else: out[name[:-1]] = x flatten(y) return out @functools.wraps(filter) def lfilter(functionOrNone, iterable): return list(filter(functionOrNone, iterable)) @functools.wraps(map) def lmap(func, *iterables): return list(map(func, *iterables)) @functools.wraps(map) def map2str(*...
i = 0 for a in x: flatten(a, name + str(i) + '_') i += 1
conditional_block
util.py
>>> start='ho', >>> end='hq', >>> variants={'o': ['oh', 'ok', 'obuh']}, >>> min_length=4, >>> index=1 >>> ) # From string 'hi', generates all strings that start with 'ho' and 'hq' (inclusive) and everything in between, >>> # whereas the string combinations start at index 1 ("...
(name, path): ''' See https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path # importing-a-source-file-directly and https://docs.python.org/3/library/importlib.html ''' spec = importlib.util.spec_from_file_location(name, path) mdl = importlib.util.module_from_sp...
module_from_abs_path
identifier_name
website.go
, err) return } input, _ := ioutil.ReadAll(f) // thunder.Login(config["thunder-user"], config["thunder-password"]) files, err := thunder.NewTaskWithTorrent(input) if err == nil { writeJson(w, files) } else { writeError(w, err) } } func stopHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Va...
{ w.Header().Set("Access-Control-Allow-Origin", "*") s.r.ServeHTTP(w, req) }
identifier_body
website.go
(name) if err != nil { log.Print(err) } } } func resumeHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) name := vars["name"] fmt.Printf("resume download \"%s\".\n", name) if err := task.ResumeTask(name); err != nil { writeError(w, err) } } func newTaskHandler(w http.ResponseWrite...
(w http.ResponseWriter, r *http.Request) { defer func() { if re := recover(); re != nil { err := re.(error) log.Print(err) log.Print(string(debug.Stack())) w.Write([]byte(html.EscapeString(err.Error()))) } }() input, _ := ioutil.ReadAll(r.Body) m := make(map[string]string) err := json.Unmarshal...
thunderNewHandler
identifier_name
website.go
func checkIfSubtitle(input string) bool { return !(strings.Contains(input, "://") || strings.HasSuffix(input, ".torrent") || strings.HasPrefix(input, "magnet:")) } func checkIfSpeed(input string) (int64, bool) { num, err := strconv.ParseUint(input, 10, 64) if err != nil { return 0, false } if num > 10*1024*1024...
random_line_split
website.go
(name) if err != nil { log.Print(err) } } } func resumeHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) name := vars["name"] fmt.Printf("resume download \"%s\".\n", name) if err := task.ResumeTask(name); err != nil { writeError(w, err) } } func newTaskHandler(w http.ResponseWrite...
for i := downloadingCnt; i < cnt; i++ { err, _ := task.ResumeNextTask() if err != nil { log.Print(err) } } util.SaveConfig("simultaneous-downloads", string(input)) } else { writeError(w, fmt.Errorf("Simultaneous must greater than zero.")) } } func setAutoShutdownHandler(w http.ResponseWriter, ...
{ err := task.QueueDownloadingTask() if err != nil { log.Print(err) } }
conditional_block
createpost.component.ts
'; import { ImageService } from '~/app/services/image.service'; import { PostService } from '~/app/services/post.service'; // Dataclasses
import { Image } from 'tns-core-modules/ui/image'; @Component({ selector: 'ns-createpost', templateUrl: './createpost.component.html', styleUrls: ['./createpost.component.css'], moduleId: module.id }) export class CreatepostComponent implements OnInit { // Get button-elements from the template to temporary...
import { Drink } from '~/app/dataclasses/drink'; import { Post } from '~/app/dataclasses/post';
random_line_split
createpost.component.ts
import { ImageService } from '~/app/services/image.service'; import { PostService } from '~/app/services/post.service'; // Dataclasses import { Drink } from '~/app/dataclasses/drink'; import { Post } from '~/app/dataclasses/post'; import { Image } from 'tns-core-modules/ui/image'; @Component({ selector: 'ns-createp...
* * OPEN CAMERA AND TAKE PICTURE TO THE POST * * Calls service's takePicture() -method to get picture and base64-string of it. * Returned values will be placed inside global variables inside class. * */ public takePicture(): void
his.post.drink_name = ''; this.post.drink_type = ''; this.post.rating = 0; } /*
identifier_body
createpost.component.ts
import { ImageService } from '~/app/services/image.service'; import { PostService } from '~/app/services/post.service'; // Dataclasses import { Drink } from '~/app/dataclasses/drink'; import { Post } from '~/app/dataclasses/post'; import { Image } from 'tns-core-modules/ui/image'; @Component({ selector: 'ns-createp...
eld?: TextField, typeField?: TextField, descField?: TextField): void { if (nameField) nameField.dismissSoftInput(); if (typeField) typeField.dismissSoftInput(); if (descField) descField.dismissSoftInput(); if (this.imageOptionsUp) this.toggleImageOptions(); this.search(''); } /** * CLOSES A...
ements(nameFi
identifier_name
prio_bitmap.rs
} }; /// Trait for [`FixedPrioBitmap`]. /// /// All methods panic when the given bit position is out of range. pub trait PrioBitmap: Init + Send + Sync + Clone + Copy + fmt::Debug + 'static { /// Get the bit at the specified position. fn get(&self, i: usize) -> bool; /// Clear the bit at the specified...
gen_test!( #[cfg(any(target_pointer_width = "32", target_pointer_width = "64", target_pointer_width = "128"))] mod size_10000, 10000
random_line_split
prio_bitmap.rs
WORD_LEN - 1) / WORD_LEN}>, {(LEN + WORD_LEN - 1) / WORD_LEN} > } else if (LEN <= WORD_LEN * WORD_LEN * WORD_LEN) { TwoLevelPrioBitmapImpl< TwoLevelPrioBitmapImpl< OneLevelPrioBitmap<{(LEN + WORD_LEN * WORD_LEN - 1) / (WORD_LEN * WORD_LEN)}>, ...
}) } fn enum_set_bits(bitmap: &impl PrioBitmap, bitmap_len: usize) -> Vec<usize> { (0..bitmap_len).filter(|&i| bitmap.get(i)).collect() } fn test_inner<T: PrioBitmap>(bytecode: Vec<u8>, size: usize
None }
conditional_block
prio_bitmap.rs
WORD_LEN - 1) / WORD_LEN}>, {(LEN + WORD_LEN - 1) / WORD_LEN} > } else if (LEN <= WORD_LEN * WORD_LEN * WORD_LEN) { TwoLevelPrioBitmapImpl< TwoLevelPrioBitmapImpl< OneLevelPrioBitmap<{(LEN + WORD_LEN * WORD_LEN - 1) / (WORD_LEN * WORD_LEN)}>, ...
-> Self { Self(BTreeSet::new()) } fn enum_set_bits(&self) -> Vec<usize> { self.0.iter().cloned().collect() } fn clear(&mut self, i: usize) { self.0.remove(&i); } fn set(&mut self, i: usize) { self.0.insert(i); } ...
w()
identifier_name
table.go
, must end with / Path, Name, DefFilePath, DataFilePath string DefFile, DataFile *os.File Columns map[string]*column.Column RowLength int // sequence of columns ColumnsInOrder []*column.Column } // Opens a table. func Open(path, name s...
(rowNumber int) int { status := table.Seek(rowNumber) if status == st.OK { del, exists := table.Columns["~del"] if exists { // Set ~del column value to "y" indicating the row is deleted return table.Write(del, "y") } else { return st.TableDoesNotHaveDelColumn } } return st.OK } // Updates a row. f...
Delete
identifier_name
table.go
, must end with / Path, Name, DefFilePath, DataFilePath string DefFile, DataFile *os.File Columns map[string]*column.Column RowLength int // sequence of columns ColumnsInOrder []*column.Column } // Opens a table. func Open(path, name s...
return table, st.OK } // Load the table (column definitions, etc.). func (table *Table) Init() int { // This function may be called multiple times, thus clear previous state. table.RowLength = 0 table.Columns = make(map[string]*column.Column) table.ColumnsInOrder = make([]*column.Column, 0) table.DefFilePath = ...
{ logg.Err("table", "Open", "Failed to open"+path+name+" Err: "+string(status)) return nil, status }
conditional_block
table.go
, must end with / Path, Name, DefFilePath, DataFilePath string DefFile, DataFile *os.File Columns map[string]*column.Column RowLength int // sequence of columns ColumnsInOrder []*column.Column } // Opens a table. func Open(path, name s...
// Writes a column value without seeking to a cursor position. func (table *Table) Write(column *column.Column, value string) int { _, err := table.DataFile.WriteString(util.TrimLength(value, column.Length)) if err != nil { return st.CannotWriteTableDataFile } return st.OK } // Inserts a row to the bottom of t...
{ row := make(map[string]string) status := table.Seek(rowNumber) if status == st.OK { rowInBytes := make([]byte, table.RowLength) _, err := table.DataFile.Read(rowInBytes) if err == nil { // For the columns in their order for _, column := range table.ColumnsInOrder { // column1:value2, column2:value2...
identifier_body
table.go
, must end with / Path, Name, DefFilePath, DataFilePath string DefFile, DataFile *os.File Columns map[string]*column.Column RowLength int // sequence of columns ColumnsInOrder []*column.Column } // Opens a table. func Open(path, name s...
// For the columns in their order for _, column := range table.ColumnsInOrder { value, exists := row[column.Name] if !exists { value = "" } // Keep writing the column value. status := table.Write(column, value) if status != st.OK { return status } } // Write a new-line character. ...
if err == nil {
random_line_split
fsexp.go
"sigs.k8s.io/controller-runtime/pkg/client" "github.com/chaosblade-io/chaosblade-spec-go/spec" "github.com/chaosblade-io/chaosblade-operator/channel" "github.com/chaosblade-io/chaosblade-operator/exec/model" "github.com/chaosblade-io/chaosblade-operator/pkg/apis/chaosblade/v1alpha1" chaosfs "github.com/chaosbla...
errnoStr, ok := expModel.ActionFlags["errno"] if ok && len(errnoStr) != 0 { if errno, err = strconv.Atoi(errnoStr); err != nil { logrusField.Error("errno must be integer") statuses = append(statuses, status.CreateFailResourceStatus( spec.ParameterIllegal.Sprintf("errno", errnoStr, err), spec.Param...
{ if percent, err = strconv.Atoi(percentStr); err != nil { logrusField.Error("percent must be integer") statuses = append(statuses, status.CreateFailResourceStatus( spec.ParameterIllegal.Sprintf("percent", percentStr, err), spec.ParameterIllegal.Code)) continue } }
conditional_block
fsexp.go
"delay", Desc: "file io delay time, ms", }, }, ActionFlags: []spec.ExpFlagSpec{ &spec.ExpFlag{ Name: "path", Desc: "I/O exception path or file", }, &spec.ExpFlag{ Name: "random", Desc: "random inject I/O code", NoArgs: true, }, &spec.ExpFlag{ Name: "...
random_line_split
fsexp.go
" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/chaosblade-io/chaosblade-spec-go/spec" "github.com/chaosblade-io/chaosblade-operator/channel" "github.com/chaosblade-io/chaosblade-operator/exec/model" "github.com/chaosblade-io/chaosblade-operator/pkg/apis/chaosblade/v1alpha1" chaosfs "github.com/chaosb...
() []string { return []string{} } func (*PodIOActionSpec) ShortDesc() string { return "Pod File System IO Exception" } func (*PodIOActionSpec) LongDesc() string { return "Pod File System IO Exception" } type PodIOActionExecutor struct { client *channel.Client } func (*PodIOActionExecutor) Name() string { retur...
Aliases
identifier_name
fsexp.go
/O error code", }, }, ActionExecutor: &PodIOActionExecutor{client: client}, ActionExample: `# Two types of exceptions were injected for the READ operation, with an exception rate of 60 percent blade create k8s pod-pod IO --method read --delay 1000 --path /home --percent 60 --errno 28 --labels "app=test" --...
{ port, err := getContainerPort(webhook.FuseServerPortName, pod) if err != nil { return nil, err } addr := fmt.Sprintf("%s:%d", pod.Status.PodIP, port) return chaosfs.NewChabladeHookClient(addr), nil }
identifier_body
index.js
'} //console.log(message); rpsFrontEnd(yourChoice.id, botChoice, message); } //bot's random number between 1-3 function randToRpsInt() { return Math.floor(Math.random() * 3); } function numberToChoice(number) { return ["rock", "paper", "scissors"][number]; } function decideWinner(yourChoice, computerChoice) ...
document.querySelector("#blackjack-result").textContent = "Let's play"; document.querySelector("#blackjack-result").style.color = "black"; blcakjackGame["turnsOver"] = true;
random_line_split
index.js
("div"); let messageDiv = document.createElement("div"); humanDiv.innerHTML = "<img src='" + ImagesDatabase[humanImageChoice] + " ' height=150 width=150 style=' box-shadow: 0px 10px 50px rgba(37, 50, 233, 1);'>"; botDiv.innerHTML = "<img src='" + ImagesDatabase[botImageChoice] + " ' heigh...
{ // conditions: higher score than dealer or dealer busts but your 21 or less if (YOU["score"] > DEALER["score"] || DEALER["score"] > 21) { blcakjackGame["wins"]++; winner = YOU; } else if (YOU["score"] < DEALER["score"]) { blcakjackGame["losses"]++; winner = DEALER; } else if (Y...
conditional_block
index.js
//challenge 2: Generate cat function generateCat() { let image = document.createElement("img"); let div = document.getElementById("flex-cat-gen"); image.src = "https://thecatapi.com/api/images/get?format=src&type=gif&size=small"; div.appendChild(image); } // challenge 3: Rock, Paper, Scissor----> functi...
{ document.getElementById("ageInDays").remove(this.editor); }
identifier_body
index.js
(result); // {'message' : 'You Won', 'color': 'green'} //console.log(message); rpsFrontEnd(yourChoice.id, botChoice, message); } //bot's random number between 1-3 function randToRpsInt() { return Math.floor(Math.random() * 3); } function
(number) { return ["rock", "paper", "scissors"][number]; } function decideWinner(yourChoice, computerChoice) { var rpsDatabase = { rock: { scissors: 1, rock: 0.5, paper: 0 }, paper: { rock: 1, paper: 0.5, scissors: 0 }, scissors: { paper: 1, scissors: 0.5, rock: 0 }, }; let yourScore = rpsDatabase...
numberToChoice
identifier_name
stat.go
} // println("min/max", min, max) if min == max { // TODO. Also NaN and Inf min -= 1 max += 1 } var binWidth float64 = s.BinWidth var numBins int var origin float64 if binWidth == 0 { binWidth = (max - min) / 30 numBins = 30 } else { numBins = int((max-min)/binWidth + 0.5) } if s.Origin != nil...
if count == 0 && s.Drop { continue } X.Data[i] = bin2x(bin) Count.Data[i] = float64(count) NCount.Data[i] = float64(count) / float64(maxcount) density := float64(count) / binWidth / float64(data.N) Density.Data[i] = density if density > maxDensity { maxDensity = density } // println("bin =", b...
Density := NewField(nr, Float, pool) NDensity := NewField(nr, Float, pool) i := 0 maxDensity := float64(0) for bin, count := range counts {
random_line_split
stat.go
} // println("min/max", min, max) if min == max { // TODO. Also NaN and Inf min -= 1 max += 1 } var binWidth float64 = s.BinWidth var numBins int var origin float64 if binWidth == 0 { binWidth = (max - min) / 30 numBins = 30 } else { numBins = int((max-min)/binWidth + 0.5) } if s.Origin != nil...
s.B = sy / sx s.A = ym - s.B*xm aErr, bErr := s.A*0.2, s.B*0.1 // BUG // See http://en.wikipedia.org/wiki/Simple_linear_regression#Normality_assumption // for convidance intervalls of A and B. pool := data.Pool result := NewDataFrame(fmt.Sprintf("linear regression of %s", data.Name), pool) result.N = 1 int...
{ x := xc[i] y := yc[i] dx := x - xm sx += dx * dx sy += dx * (y - ym) }
conditional_block
stat.go
} // println("min/max", min, max) if min == max { // TODO. Also NaN and Inf min -= 1 max += 1 } var binWidth float64 = s.BinWidth var numBins int var origin float64 if binWidth == 0 { binWidth = (max - min) / 30 numBins = 30 } else { numBins = int((max-min)/binWidth + 0.5) } if s.Origin != nil...
sy += dx * (y - ym) } s.B = sy / sx s.A = ym - s.B*xm aErr, bErr := s.A*0.2, s.B*0.1 // BUG // See http://en.wikipedia.org/wiki/Simple_linear_regression#Normality_assumption // for convidance intervalls of A and B. pool := data.Pool result := NewDataFrame(fmt.Sprintf("linear regression of %s", data.Name), p...
{ if data == nil { return nil } xc, yc := data.Columns["x"].Data, data.Columns["y"].Data xm, ym := float64(0), float64(0) for i := 0; i < data.N; i++ { xm += xc[i] ym += yc[i] } xm /= float64(data.N) ym /= float64(data.N) sy, sx := float64(0), float64(0) for i := 0; i < data.N; i++ { x := xc[i] y ...
identifier_body
stat.go
binWidth = (max - min) / 30 numBins = 30 } else { numBins = int((max-min)/binWidth + 0.5) } if s.Origin != nil { origin = *s.Origin } else { origin = math.Floor(min/binWidth) * binWidth // round origin TODO: might overflow } x2bin := func(x float64) int { return int((x - origin) / binWidth) } bin2x := ...
Name
identifier_name
mkPlots2.py
ROOT->ForceStyle();') gStyle.SetPadLeftMargin(0.18) gStyle.SetPadRightMargin(0.04) gStyle.SetStripDecimals(0) markers = [20, 21, 20 , 23] colours = [kBlack,kBlue,kRed,kGreen+2] return markers, colours #################################################################################################### #def IN...
s['tree'].Draw("%s:%s>>+%s"%(v['root'],"mva%s"%sel,hProf[(sel,v['var'],'BDT','QCD' if 'QCD' in s['fname'] else 'DAT')].GetName()),TCut(cutextra)*TCut(cut),"prof") if 'mbbReg' in v['var']: continue s['tree'].Draw("%s:%s>>+%s"%(v['root'],"mbbReg[%d]"%(1 if sel=='NOM' else 2),hProf[(sel,v['var'],'mbbReg',...
continue
conditional_block
mkPlots2.py
#################################################################################################### def INTERNALstyle(): gROOT.ProcessLine("TH1::SetDefaultSumw2(1);") gROOT.ProcessLine(".x %s/styleCMSTDR.C++"%basepath) gROOT.ProcessLine('gROOT->ForceStyle();') gStyle.SetPadLeftMargin(0.18) gStyle.SetPadRightMar...
h.SetBinError(ix,0) return h
random_line_split
mkPlots2.py
return jsons #################################################################################################### def INTERNALblind(h,min,max): for ix in range(1,h.GetNbinsX()+1): x = h.GetBinCenter(ix) if x>=min and x<=max: h.SetBinContent(ix,0) h.SetBinError(ix,0) return h ###########################...
makeDirs(os.path.split(opts.fout)[0]) makeDirs('plots') jsonsamp = json.loads(filecontent(opts.jsonsamp)) jsonvars = json.loads(filecontent(opts.jsonvars)) jsoninfo = json.loads(filecontent(opts.jsoninfo)) jsoncuts = json.loads(filecontent(opts.jsoncuts)) jsons = {'samp':jsonsamp,'vars':jsonvars,'info':jsoninfo,'...
identifier_body
mkPlots2.py
ROOT->ForceStyle();') gStyle.SetPadLeftMargin(0.18) gStyle.SetPadRightMargin(0.04) gStyle.SetStripDecimals(0) markers = [20, 21, 20 , 23] colours = [kBlack,kBlue,kRed,kGreen+2] return markers, colours #################################################################################################### #def IN...
(opts,sels,jsons): hProf = {} vars = jsons['vars']['variables'] for s in sels: for v in opts.variable: vroot = vars[v]['root'] if s=='NOM' and '[2]' in vroot: continue if s=='VBF' and '[1]' in vroot: continue if 'mva' in v and not s in v: continue for tag in ['QCD','DAT']: vy = 'BDT' vy2 = ...
INTERNALhistograms
identifier_name
criterion.rs
/// Changes the size of a sample /// /// A sample consists of severals measurements #[experimental] pub fn sample_size(&mut self, n: uint) -> &mut Criterion { self.sample_size = n; self } /// Changes the significance level /// /// Significance level to use for hypo...
{ self.nresamples = n; self }
identifier_body
criterion.rs
(&mut self, sl: f64) -> &mut Criterion { assert!(sl > 0.0 && sl < 1.0); self.significance_level = sl; self } /// Changes the warm up time /// /// The program/function under test is executed during `warm_up_time` ms before the real /// measurement starts #[experimental] ...
significance_level
identifier_name
criterion.rs
= root.join("base"); let change_dir = root.join("change"); let new_dir = root.join("new"); match target { Program(_) => { let _clock_cost = external_clock_cost(&mut target, criterion, &new_dir.join("clock"), id); // TODO use clock_cost to set minimal measur...
random_line_split
send.go
cmn.Assert(rc >= 0) // remove } // SCQ completion callback if rc == 0 { if obj.Callback != nil { obj.Callback(obj.Hdr, obj.Reader, obj.CmplPtr, err) } else if s.callback != nil { s.callback(obj.Hdr, obj.Reader, obj.CmplPtr, err) } } if obj.Reader != nil { obj.Reader.Close() // NOTE: always closing ...
dryrun
identifier_name
send.go
SCQ form a FIFO as far as ordering of transmitted objects. // // NOTE: header-only objects are supported; when there's no data to send (that is, // when the header's Dsize field is set to zero), the reader is not required and the // corresponding argument in Send() can be set to nil. // // NOTE: object reader is alway...
{ s.eoObj(nil) }
conditional_block
send.go
orig reader => zw sgl *memsys.SGL // zw => bb => network blockMaxSize int // *uncompressed* block max size frameChecksum bool // true: checksum lz4 frames } sendoff struct { obj Obj // in progress off int64 dod int64 } cmpl struct { // send completions => SCQ obj Obj err...
func (s *Stream) ID() (string, int64) { return s.trname, s.sessID } func (s *Stream) String() string { return s.lid } func (s *Stream) Terminated() (terminated bool) { s.term.mu.Lock() terminated = s.term.terminated s.term.mu.Unlock() return } func (s *Stream) terminate() { s.term.mu.Lock() cmn.Assert(!s.te...
{ return s.toURL }
identifier_body
send.go
) // stream TCP/HTTP session: inactive <=> active transitions const ( inactive = iota active ) // termination: reasons const ( reasonUnknown = "unknown" reasonError = "error" endOfStream = "end-of-stream" reasonStopped = "stopped" ) // API types type ( Stream struct { client Client // http client this s...
burstNum = 32 // default max num objects that can be posted for sending without any back-pressure
random_line_split
base_wizard.py
WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import keystore from wallet import Wallet, Imported_Wallet, Standard_Wallet, Multisig_Wallet, WalletStorage, wallet_types from i18n import _ from p...
elif keystore.is_private(text): self.add_password(text) else: self.create_keystore(text, None) def import_addresses(self): v = keystore.is_address_list title = _("Import Bitcoin Addresses") message = _("Enter a list of Bitcoin addresses. This will cr...
self.wallet = Imported_Wallet(self.storage) for x in text.split(): self.wallet.import_address(x) self.terminate()
conditional_block
base_wizard.py
, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import keystore from wallet import Wallet, Imported_Wallet, Standard_Wallet, Multisig_Wallet, WalletStorage, wallet_types from i18n import _ from ...
self.devices = devices choices = [] for name, device_info in devices: choices.append( ((name, device_info), device_info.description) ) msg = _('Select a device') + ':' self.choice_dialog(title=title, message=msg, choices=choices, run_next=self.on_device) def on_d...
# select device
random_line_split
base_wizard.py
WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import keystore from wallet import Wallet, Imported_Wallet, Standard_Wallet, Multisig_Wallet, WalletStorage, wallet_types from i18n import _ from p...
(self): assert self.wallet_type in ['standard', 'multisig'] c = self.wallet_type == 'multisig' and len(self.keystores)>0 title = _('Add cosigner') + ' %d'%len(self.keystores) if c else _('Keystore') message = _('Do you want to create a new seed, or to restore a wallet using an existing s...
choose_keystore
identifier_name
base_wizard.py
WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import keystore from wallet import Wallet, Imported_Wallet, Standard_Wallet, Multisig_Wallet, WalletStorage, wallet_types from i18n import _ from p...
elif hasattr(self, action): f = getattr(self, action) apply(f, args) else: raise BaseException("unknown action", action) def can_go_back(self): return len(self.stack)>1 def go_back(self): if not self.can_go_back(): return ...
def __init__(self, config, network, path): super(BaseWizard, self).__init__() self.config = config self.network = network self.storage = WalletStorage(path) self.wallet = None self.stack = [] self.plugin = None def run(self, *args): action = args[0] ...
identifier_body
plugin.go
error) { p.Debugf("creating check run %q on %s/%s @ %s...", p.Name, owner, repo, headSHA) checkRun, res, err := client.Checks.CreateCheckRun( context.TODO(), owner, repo, github.CreateCheckRunOptions{ Name: p.Name, HeadSHA: headSHA, Status: Started.StringP(), }, ) p.Debugf("create check AP...
{ p.Debugf("%q handler", actionSync) // Get the check run checkRun, err := p.getCheckRun(env.Client, env.Owner, env.Repo, env.Event.GetBefore()) if err != nil { return err } // Rerun the tests if they weren't finished if !Finished.Equal(checkRun.GetStatus()) { // Process the PR and submit the results chec...
identifier_body
plugin.go
PRPlugin struct { ProcessPR func(pr *github.PullRequest) (string, error) Name string Title string log.Logger } // init initializes the PRPlugin func (p *PRPlugin) init() { p.Logger = log.NewFor(p.Name) p.Debug("plugin initialized") } // processPR executes the provided ProcessPR and parses the result ...
p.Debugf("duplicating check run %q on %s/%s @ %s...", p.Name, owner, repo, headSHA) checkRun, res, err := client.Checks.CreateCheckRun( context.TODO(), owner, repo, github.CreateCheckRunOptions{ Name: p.Name, HeadSHA: headSHA, DetailsURL: checkRun.DetailsURL, ExternalID: checkRun.Ext...
// duplicateCheckRun creates a new Check-Run with the same info as the provided one but for a new headSHA func (p PRPlugin) duplicateCheckRun(client *github.Client, owner, repo, headSHA string, checkRun *github.CheckRun) (*github.CheckRun, error) {
random_line_split
plugin.go
Run, err := p.finishCheckRun(env.Client, env.Owner, env.Repo, checkRun.GetID(), conclusion, summary, text) if err != nil { return checkRun, err } // Return failure here too so that the whole suite fails (since the actions // suite seems to ignore failing check runs when calculating general failure) if procErr !...
onSync
identifier_name
plugin.go
PRPlugin struct { ProcessPR func(pr *github.PullRequest) (string, error) Name string Title string log.Logger } // init initializes the PRPlugin func (p *PRPlugin) init() { p.Logger = log.NewFor(p.Name) p.Debug("plugin initialized") } // processPR executes the provided ProcessPR and parses the result ...
// Process the PR and submit the results _, err = p.processAndSubmit(env, checkRun) return err } // onReopen handles "reopen
{ return err }
conditional_block
bosh.ts
'; import StreamManagement from '../helpers/StreamManagement'; import { fetch, Duplex } from '../platform'; import { Stream } from '../protocol'; import { JSONData, ParsedData, Registry, StreamParser } from '../jxt'; import { sleep, timeoutPromise } from '../Utils'; class RequestChannel { public rid!: number; ...
} } public async send(dataOrName: string, data?: JSONData): Promise<void> { let output: string | undefined; if (data) { output = this.stanzas.export(dataOrName, data)?.toString(); } if (!output) { return; } return new Promise<void...
} else { this.stream = undefined; this.sid = undefined; this.rid = undefined; this.client.emit('--transport-disconnected');
random_line_split
bosh.ts
import StreamManagement from '../helpers/StreamManagement'; import { fetch, Duplex } from '../platform'; import { Stream } from '../protocol'; import { JSONData, ParsedData, Registry, StreamParser } from '../jxt'; import { sleep, timeoutPromise } from '../Utils'; class RequestChannel { public rid!: number; p...
this._send({ lang: opts.lang, maxHoldOpen: this.maxHoldOpen, maxWaitTime: this.maxWaitTime, to: opts.server, version: '1.6', xmppVersion: '1.0' }); } public restart(): void { this.hasStream = false; this._...
{ this.hasStream = true; this.stream = {}; this.client.emit('connected'); this.client.emit('session:prebind', this.config.jid); this.client.emit('session:started'); return; }
conditional_block
bosh.ts
'; import StreamManagement from '../helpers/StreamManagement'; import { fetch, Duplex } from '../platform'; import { Stream } from '../protocol'; import { JSONData, ParsedData, Registry, StreamParser } from '../jxt'; import { sleep, timeoutPromise } from '../Utils'; class RequestChannel { public rid!: number; ...
(): Promise<void> { if (this.isEnded) { return; } const rid = this.rid!++; const body = this.stanzas .export('bosh', { rid, sid: this.sid })! .toString(); this.client.emit('raw', 'outgoing', body); ...
_poll
identifier_name
mod.rs
input), "while" => while_loop2(input), _ => unknown_atrule(name, input0, input), } } fn unknown_atrule<'a>( name: SassString, start: Span, input: Span<'a>, ) -> PResult<'a, Item> { let (input, args) = terminated(opt(unknown_rule_args), opt(ignore_space))(input)?; fn x_arg...
let (input, next) = if val.is_some() { alt((tag("{"), tag(";"), tag("")))(input)? } else { tag("{")(input)?
random_line_split
mod.rs
(data: &[u8]) -> Result<Value, Error> { let data = code_span(data); let value = all_consuming(value_expression)(data.borrow()); Ok(ParseError::check(value)?) } #[test] fn test_parse_value_data_1() -> Result<(), Error> { let v = parse_value_data(b"17em")?; assert_eq!(Value::Numeric(Numeric::new(17, ...
parse_value_data
identifier_name
mod.rs
|(v, _eof)| v, ), )(input) } fn top_level_item(input: Span) -> PResult<Item> { let (rest, tag) = alt((tag("$"), tag("/*"), tag("@"), tag("")))(input)?; match tag.fragment() { b"$" => into(variable_declaration2)(rest), b"/*" => comment_item(rest), b"@" => at_rule2(input), ...
}; Ok(( rest, Item::AtRule { name, args: args.map_or(Value::Null, x_args), body, pos: start.up_to(&input).to_owned(), }, )) } fn expression_argument(input: Span) -> PResult<Value> { terminated(value_expression, opt(tag(";")))(inpu...
{ let (input, args) = terminated(opt(unknown_rule_args), opt(ignore_space))(input)?; fn x_args(value: Value) -> Value { match value { Value::Variable(name, _pos) => { Value::Literal(SassString::from(format!("${name}"))) } Value::Map(map) => Val...
identifier_body
http2.go
s", x.Subject.String())) logging.Server(fmt.Sprintf("Starting reaper Server using an X.509 certificate with a SHA256 hash, "+ "calculated by reaper, of %s", sha256Fingerprint)) // Configure TLS TLSConfig := &tls.Config{ Certificates: []tls.Certificate{cer}, MinVersion: tls.VersionTLS...
logging.Server(fmt.Sprintf("[DEBUG]URI: %s", r.RequestURI)) logging.Server(fmt.Sprintf("[DEBUG]Method: %s", r.Method)) logging.Server(fmt.Sprintf("[DEBUG]Protocol: %s", r.Proto)) logging.Server(fmt.Sprintf("[DEBUG]Headers: %s", r.Header)) logging.Server(fmt.Sprintf("[DEBUG]TLS Negotiated Protocol: %s", r.TLS....
{ if core.Verbose { message("note", fmt.Sprintf("Received %s %s connection from %s", r.Proto, r.Method, r.RemoteAddr)) logging.Server(fmt.Sprintf("Received HTTP %s connection from %s", r.Method, r.RemoteAddr)) } if core.Debug { message("debug", fmt.Sprintf("HTTP Connection Details:")) message("debug", fmt.S...
identifier_body
http2.go
%v", j)) } if core.Verbose { message("info", fmt.Sprintf("Received %s message from %s at %s", j.Type, j.ID, time.Now().UTC().Format(time.RFC3339))) } // Allowed authenticated message with PSK JWT and JWE encrypted with derived secret switch j.Type { case "AuthComplete": returnMessage, err = ...
agentID = uuid.FromStringOrNil(claims.ID) AgentWaitTime, errWait := agents.GetAgentFieldValue(agentID, "WaitTime")
random_line_split
http2.go
(iface string, port int, protocol string, key string, certificate string, psk string) (Server, error) { s := Server{ ID: uuid.NewV4(), Protocol: protocol, Interface: iface, Port: port, Mux: http.NewServeMux(), jwtKey: []byte(core.RandStringBytesMaskImprSrc(32)), // Used to sign and en...
New
identifier_name
http2.go
// Parse into X.509 format x, errX509 := x509.ParseCertificate(cer.Certificate[0]) if errX509 != nil { m := fmt.Sprintf("There was an error parsing the tls.Certificate structure into a x509.Certificate"+ " structure:\r\n%s", errX509.Error()) logging.Server(m) message("warn", m) return s, errX509 } // ...
{ m := "Unable to import certificate for use in reaper: empty certificate structure." logging.Server(m) message("warn", m) return s, errors.New("empty certificate structure") }
conditional_block
cache.go
{ Name string Values []interface{} _param *Parameter } CacheInput struct { Selector *Selector Column string MetaColumn string IndexMeta bool } CacheInputFn func() ([]*CacheInput, error) ) const ( defaultType = "" afsType = "afs" aerospikeType = "aerospike" ) func (c Caches)
(name string) bool { for _, candidate := range c { if candidate.Name == name { return true } } return false } func (r *Caches) Append(cache *Cache) { if r.Has(cache.Name) { return } *r = append(*r, cache) } func (c *Cache) init(ctx context.Context, resource *Resource, aView *View) error { if c._initia...
Has
identifier_name
cache.go
{ Name string Values []interface{} _param *Parameter } CacheInput struct { Selector *Selector Column string MetaColumn string IndexMeta bool } CacheInputFn func() ([]*CacheInput, error) ) const ( defaultType = "" afsType = "afs" aerospikeType = "aerospike" ) func (c Caches) H...
if err != nil { return "", 0, "", err } return segments[0], port, namespace, nil } func (c *Cache) unsupportedLocationFormat(location string) error { return fmt.Errorf("unsupported location format: %v, supported location format: [protocol][hostname]:[port]/[namespace]", location) } func (c *Cache) inheritIfNe...
{ actualScheme := url.Scheme(location, "") hostPart, namespace := url.Split(location, actualScheme) if namespace == "" { return "", 0, "", c.unsupportedLocationFormat(location) } hostStart := 0 if actualScheme != "" { hostStart = len(actualScheme) + 3 } segments := strings.Split(hostPart[hostStart:len(h...
identifier_body
cache.go
ParamValue struct { Name string Values []interface{} _param *Parameter } CacheInput struct { Selector *Selector Column string MetaColumn string IndexMeta bool } CacheInputFn func() ([]*CacheInput, error) ) const ( defaultType = "" afsType = "afs" aerospikeType = "aerospike" ) ...
}
random_line_split
cache.go
{ Name string Values []interface{} _param *Parameter } CacheInput struct { Selector *Selector Column string MetaColumn string IndexMeta bool } CacheInputFn func() ([]*CacheInput, error) ) const ( defaultType = "" afsType = "afs" aerospikeType = "aerospike" ) func (c Caches) H...
clientProvider := aClientPool.Client(host, port) expanded, err := c.expandLocation(aView) if err != nil { return nil, err } timeoutConfig := &aerospike.TimeoutConfig{ MaxRetries: c.AerospikeConfig.MaxRetries, TotalTimeoutMs: c.AerospikeConfig.TotalTimeoutInMs, SleepBetweenRetriesMs: c...
{ return nil, err }
conditional_block
torch_MLE_link_pred.py
= torch.nn.Parameter(torch.randn(self.input_size[1], self.latent_dim)) #Change sample weights for each partition self.sampling_i_weights = torch.ones(input_size[0]) self.sampling_j_weights = torch.ones(input_size[1]) #Change sample sizes for each partition self.sample_i_size = s...
if __name__ == "__main__": A = adj_m #Lists to obtain values for AUC, FPR, TPR and loss AUC_scores = [] tprs = [] base_fpr = np.linspace(0, 1, 101) plt.figure(figsize=(5,5)) train_loss = [] test_loss = [] #Binarize data-set if True binarized = False link_pred = True ...
with torch.no_grad(): idx_test = torch.where(torch.isnan(A_test) == False) z_dist = (((self.latent_zi[idx_test[0]] - self.latent_zj[idx_test[1]] + 1e-06)**2).sum(-1))**0.5 #Unsqueeze eller ej? bias_matrix = self.beta[idx_test[0]] + self.gamma[idx_test[1]] Lambda = (bias_...
identifier_body
torch_MLE_link_pred.py
= torch.nn.Parameter(torch.randn(self.input_size[1], self.latent_dim)) #Change sample weights for each partition self.sampling_i_weights = torch.ones(input_size[0]) self.sampling_j_weights = torch.ones(input_size[1]) #Change sample sizes for each partition self.sample_i_size = s...
#Define the model with training data. #Cross-val loop validating 5 seeds; model = LSM(A=A, input_size=A.shape, latent_dim=2, sparse_i_idx= idx[0], sparse_j_idx=idx[1], count=count, sample_i_size = 1000, sample_j_size = 500) #Deine the optimizer. optimizer = optim.Adam(params=m...
np.random.seed(i) torch.manual_seed(i) #Sample test-set from multinomial distribution. if link_pred: A_shape = A.shape num_samples = 400000 idx_i_test = torch.multinomial(input=torch.arange(0,float(A_shape[0])), num_samples=num_samples, ...
conditional_block
torch_MLE_link_pred.py
= torch.nn.Parameter(torch.randn(self.input_size[1], self.latent_dim)) #Change sample weights for each partition self.sampling_i_weights = torch.ones(input_size[0]) self.sampling_j_weights = torch.ones(input_size[1]) #Change sample sizes for each partition self.sample_i_size = s...
#Define the model with training data. #Cross-val loop validating 5 seeds; model = LSM(A=A, input_size=A.shape, latent_dim=2, sparse_i_idx= idx[0], sparse_j_idx=idx[1], count=count, sample_i_size = 1000, sample_j_size = 500) #Deine the optimizer. optimizer = optim.Adam(params=mo...
random_line_split
torch_MLE_link_pred.py
= torch.nn.Parameter(torch.randn(self.input_size[1], self.latent_dim)) #Change sample weights for each partition self.sampling_i_weights = torch.ones(input_size[0]) self.sampling_j_weights = torch.ones(input_size[1]) #Change sample sizes for each partition self.sample_i_size = s...
(self): sample_i_idx, sample_j_idx, sparse_i_sample, sparse_j_sample, valueC = self.sample_network() self.z_dist = (((torch.unsqueeze(self.latent_zi[sample_i_idx], 1) - self.latent_zj[sample_j_idx]+1e-06)**2).sum(-1))**0.5 bias_matrix = torch.unsqueeze(self.beta[sample_i_idx], 1) + self.gamma[sa...
log_likelihood
identifier_name
main.py
0, 0, 0) ZERO = 0 NEGATIVE = -1 DEFAULT_FONT_SIZE = 72 DEFAULT_IMAGE_WIDTH = 1080 EMOJI = 4 FULL_WIDTH = 3 HALF_WIDTH = 1 EMOJI_IMG_SIZE = 72 class Emoji2Pic(object): """将带有emoji的文本绘制到图片上,返回 'PIL.Image.Image'。 Text with emoji draw to the image.return class 'PIL.Image.Image' :param text: 文本内容 :pa...
font_type = self.half_font_type y = self.y - self.half_font_offset else: font_type = self.full_width_font_type y = self.y ImageDraw.Draw(self.img).text(xy=(self.x, y), text=self.char, ...
F_WIDTH # 半角字符 else: return FULL_WIDTH # 全角字符 def draw_character(self, half_width=False): """ 绘制文本 Draw character """ if self.char in ('\u200d', '\ufe0f', '\u20e3'): self.x -= self.font_size return if half_width is True: ...
conditional_block
main.py
0, 0, 0) ZERO = 0 NEGATIVE = -1 DEFAULT_FONT_SIZE = 72 DEFAULT_IMAGE_WIDTH = 1080 EMOJI = 4 FULL_WIDTH = 3 HALF_WIDTH = 1 EMOJI_IMG_SIZE = 72 class Emoji2Pic(object): """将带有emoji的文本绘制到图片上,返回 'PIL.Image.Image'。 Text with emoji draw to the image.return class 'PIL.Image.Image' :param text: 文本内容 :p...
else: font_type = self.full_width_font_type y = self.y ImageDraw.Draw(self.img).text(xy=(self.x, y), text=self.char, fill=self.font_color, font=font_type) ret...
font_type = self.half_font_type y = self.y - self.half_font_offset
random_line_split
main.py
0, 0, 0) ZERO = 0 NEGATIVE = -1 DEFAULT_FONT_SIZE = 72 DEFAULT_IMAGE_WIDTH = 1080 EMOJI = 4 FULL_WIDTH = 3 HALF_WIDTH = 1 EMOJI_IMG_SIZE = 72 class Emoji2Pic(object): """将带有emoji的文本绘制到图片上,返回 'PIL.Image.Image'。 Text with emoji draw to the image.return class 'PIL.Image.Image' :param text: 文本内容 :pa...
return HALF_WIDTH # 半角字符 return EMOJI # emoji elif u'\x20' <= self.char <= u'\x7e': return HALF_WIDTH # 半角字符 else: return FULL_WIDTH # 全角字符 def draw_character(self, half_width=False): """ 绘制文本 Draw character """ if se...
TH:
identifier_name
main.py
0, 0, 0) ZERO = 0 NEGATIVE = -1 DEFAULT_FONT_SIZE = 72 DEFAULT_IMAGE_WIDTH = 1080 EMOJI = 4 FULL_WIDTH = 3 HALF_WIDTH = 1 EMOJI_IMG_SIZE = 72 class Emoji2Pic(object): """将带有emoji的文本绘制到图片上,返回 'PIL.Image.Image'。 Text with emoji draw to the image.return class 'PIL.Image.Image' :param text: 文本内容 :pa...
mage.new(mode=self.background_color_mode, size=(img_width, img_height), color=self.background_color) return img def stdout_progress_bar(self): """ 输出进度条 Progress bar """ self.progress_bar_count += 1 display_leng...
one): """ 创建空白图片 Make a blank image """ if img_width is None: img_width = self.img_width if img_height is None: img_height = self.font_size + self.line_space img = I
identifier_body
smallnorb_input_record.py
]), tf.int32) label.set_shape([1]) depth_major = tf.reshape( tf.strided_slice(uint_data, [label_bytes], [record_bytes]), [depth, height, height]) image = tf.cast(tf.transpose(a=depth_major, perm=[1, 2, 0]), tf.float32) return image, label def _distort_resize(image, image_size): """Distorts inp...
Hinton2018: "We downsample smallNORB to 48 × 48 pixels and normalize each image to have zero mean and unit variance. During training, we randomly crop 32 × 32 patches and add random brightness and contrast to the cropped images. During test, we crop a 32 × 32 patch from the center of the image and a...
def _val_preprocess(img, lab, cat, elv, azi, lit): """Preprocessing for validation/testing. Preprocessing from Hinton et al. (2018) "Matrix capsules with EM routing."
random_line_split
smallnorb_input_record.py
]), tf.int32) label.set_shape([1]) depth_major = tf.reshape( tf.strided_slice(uint_data, [label_bytes], [record_bytes]), [depth, height, height]) image = tf.cast(tf.transpose(a=depth_major, perm=[1, 2, 0]), tf.float32) return image, label def _distort_resize(image, image_size): """Distorts inp...
batched_features['labels'] = tf.reshape(batched_features['labels'], [batch_size, 5]) batched_features['recons_label'] = tf.reshape( batched_features['recons_label'], [batch_size]) batched_features['height'] = image_size batched_features['width'] = image_size ba...
batched_features = tf.compat.v1.train.batch( features, batch_size=batch_size, num_threads=1, capacity=10000 + 3 * batch_size)
conditional_block
smallnorb_input_record.py
_image': image, 'recons_label': label, } if split == 'train': batched_features = tf.compat.v1.train.shuffle_batch( features, batch_size=batch_size, num_threads=16, capacity=10000 + 3 * batch_size, min_after_dequeue=10000) else: batched_features = tf.compat.v1....
batch from the input pipeline. Author: Ashley Gritzman 15/11/2018 Args: is_train: Returns: img, lab, cat, elv, azi, lit: """ # Create batched dataset dataset = input_fn(path, is_train,batch_size=batch_size, epochs=epochs) # Create one-shot iterator iterator = tf.com...
identifier_body
smallnorb_input_record.py
]), tf.int32) label.set_shape([1]) depth_major = tf.reshape( tf.strided_slice(uint_data, [label_bytes], [record_bytes]), [depth, height, height]) image = tf.cast(tf.transpose(a=depth_major, perm=[1, 2, 0]), tf.float32) return image, label def _distort_resize(image, image_size): """Distorts inp...
(img, lab, cat, elv, azi, lit): """Preprocessing for training. Preprocessing from Hinton et al. (2018) "Matrix capsules with EM routing." Hinton2018: "We downsample smallNORB to 48 × 48 pixels and normalize each image to have zero mean and unit variance. During training, we randomly crop 32 × 32 pa...
_train_preprocess
identifier_name
game.rs
ShiftRng; use std::path::PathBuf; use std::time::Instant; // This is the top-level of the GUI logic. This module should just manage interactions between the // top-level game states. pub struct GameState { pub mode: Mode, pub ui: UI, } // TODO Need to reset_sim() when entering Edit, Tutorial, Mission, or ABTe...
(&self, canvas: &Canvas) { println!( "********************************************************************************" ); println!("UI broke! Primary sim:"); self.ui.primary.sim.dump_before_abort(); if let Mode::ABTest(ref abtest) = self.mode { if let Som...
dump_before_abort
identifier_name
game.rs
orShiftRng; use std::path::PathBuf; use std::time::Instant; // This is the top-level of the GUI logic. This module should just manage interactions between the // top-level game states. pub struct GameState { pub mode: Mode, pub ui: UI, } // TODO Need to reset_sim() when entering Edit, Tutorial, Mission, or AB...
rng.gen_range(0.0, bounds.max_y), ); canvas.cam_zoom = 10.0; canvas.center_on_map_pt(at); Screensaver { line: Line::new(at, goto), started: Instant::now(), } } fn update( &mut self, rng: &mut XorShiftRng, inpu...
let goto = Pt2D::new( rng.gen_range(0.0, bounds.max_x),
random_line_split
game.rs
ShiftRng; use std::path::PathBuf; use std::time::Instant; // This is the top-level of the GUI logic. This module should just manage interactions between the // top-level game states. pub struct GameState { pub mode: Mode, pub ui: UI, } // TODO Need to reset_sim() when entering Edit, Tutorial, Mission, or ABTe...
.map .all_lanes() .choose(&mut rng) .and_then(|l| ID::Lane(l.id).canonical_point(&game.ui.primary)) }) .expect("Can't get canonical_point of a random building or lane"); if splash { ctx.canvas.ce...
{ let splash = !flags.no_splash && !format!("{}", flags.sim_flags.load.display()).contains("data/save"); let mut rng = flags.sim_flags.make_rng(); let mut game = GameState { mode: Mode::Sandbox(SandboxMode::new(ctx)), ui: UI::new(flags, ctx), }; ...
identifier_body
sparse.rs
) } fn set_zero(&mut self, i: usize) { if let Ok(index) = self.get_data_index(i) { self.data.remove(index); } } /// Increase the length of the vector by passing with zeros. pub fn extend(&mut self, extra_len: usize) { self.len += extra_len; } /// Conver...
(&mut self, i: usize, value: F) { debug_assert!(i < self.len); debug_assert!(value.borrow().is_not_zero()); match self.get_data_index(i) { Ok(index) => self.data[index].1 = value, Err(index) => self.data.insert(index, (i, value)), } } fn get(&self, index...
set
identifier_name
sparse.rs
_sorted()); // All values are unique debug_assert!(indices.iter().collect::<HashSet<_>>().len() == indices.len()); debug_assert!(indices.iter().all(|&i| i < self.len)); debug_assert!(indices.len() < self.len); remove_sparse_indices(&mut self.data, indices); self.len -= i...
writeln!(f)
random_line_split
sparse.rs
) } fn set_zero(&mut self, i: usize) { if let Ok(index) = self.get_data_index(i) { self.data.remove(index); } } /// Increase the length of the vector by passing with zeros. pub fn extend(&mut self, extra_len: usize) { self.len += extra_len; } /// Conver...
/// Whether this vector has zero size. fn is_empty(&self) -> bool { self.len == 0 } /// The size of this vector in memory. fn size(&self) -> usize { self.data.len() } } impl<F, C> Sparse<F, C> where F: SparseElement<C>, C: SparseComparator, { /// Create a `SparseV...
{ self.len }
identifier_body
sparse.rs
`. /// /// # Arguments /// /// * `i`: Index of the value. New tuple will be inserted, potentially causing many values to /// be shifted. /// * `value`: Value to be taken at index `i`. Should not be very close to zero to avoid /// memory usage and numerical error build-up. fn set(&mut sel...
{ match self.data[self_lowest..].binary_search_by_key(&other_sought, |&(i, _)| i) { Err(diff) => { self_lowest += diff; other_lowest += 1; }, Ok(diff) => { ...
conditional_block
lib.rs
io::task::{Id, JoinError, JoinHandle, JoinSet}; /// Copy our (thread-local or task-local) stdio destination and current workunit parent into /// the task. The former ensures that when a pantsd thread kicks off a future, any stdio done /// by it ends up in the pantsd log as we expect. The latter ensures that when a new...
/// /// Run a Future on a tokio Runtime as a new Task, and return a Future handle to it. /// /// If the background Task exits abnormally, the given closure will be called to recover: usually /// it should convert the resulting Error to a relevant error type. /// /// If the returned Future is dropped, th...
{ let _context = self.handle.enter(); f() }
identifier_body
lib.rs
/// all clones of the Executor will not cause the Runtime to be shut down. Likewise, the owner of /// the Runtime must ensure that it is kept alive longer than all Executor instances, because /// existence of a Handle does not prevent a Runtime from shutting down. This is guaranteed by /// the scope of the toki...
if inner.task_set.is_empty() { return; }
random_line_split
lib.rs
}) } /// /// Executors come in two flavors: /// * "borrowed" /// * Created with `Self::new()`, or `self::to_borrowed()`. /// * A borrowed Executor will not be shut down when all handles are dropped, and shutdown /// methods will have no impact. /// * Used when multiple runs of Pants will borrow a s...
spawn_on
identifier_name
lib.rs
_all(); if env::var("PANTS_DEBUG").is_ok() { runtime_builder.on_thread_start(on_thread_start); }; let runtime = runtime_builder .build() .map_err(|e| format!("Failed to start the runtime: {e}"))?; let handle = runtime.handle().clone(); Ok(Executor { runtime: Arc::new(Mutex...
{ log::debug!( "{} session end task(s) failed to complete within timeout: {}", inner.task_set.len(), inner.id_to_name.values().join(", "), ); inner.task_set.abort_all(); }
conditional_block
traphandlers.rs
An indicator for whether this may have been a trap generated from an /// interrupt, used for switching what would otherwise be a stack /// overflow trap to be an interrupt trap. maybe_interrupted: bool, }, /// A trap raised from a wasm libcall Wasm { /// Code of the trap. ...
backtrace, maybe_interrupted, }) } UnwindReason::Panic(panic) => { debug_assert_eq!(ret, 0); std::panic::resume_unwind(panic) } } } /// Checks and/or initializes the wasm native ...
{ let _reset = self.update_stack_limit()?; let ret = tls::set(&self, || closure(&self)); match self.unwind.replace(UnwindReason::None) { UnwindReason::None => { debug_assert_eq!(ret, 1); Ok(()) } UnwindReason::UserTrap(data) => ...
identifier_body
traphandlers.rs
UnwindReason::LibTrap(trap) => Err(trap), UnwindReason::JitTrap { backtrace, pc } => { debug_assert_eq!(ret, 0); let interrupts = self.trap_info.interrupts(); let maybe_interrupted = interrupts.stack_limit.load(SeqCst) == wasmtime_environ:...
replace
identifier_name
traphandlers.rs
/// An indicator for whether this may have been a trap generated from an /// interrupt, used for switching what would otherwise be a stack /// overflow trap to be an interrupt trap. maybe_interrupted: bool, }, /// A trap raised from a wasm libcall Wasm { /// Code of the tra...
} /// Invokes the contextually-defined context's out-of-gas function. /// /// (basically delegates to `wasmtime::Store::out_of_gas`) pub fn out_of_gas() { tls::with(|state| state.unwrap().trap_info.out_of_gas()) } /// Temporary state stored on the stack which is registered in the `tls` module /// below for calls ...
random_line_split
traphandlers.rs
new OOM trap with the given source location and trap code. /// /// Internally saves a backtrace when constructed. pub fn oom() -> Self { let backtrace = Backtrace::new_unresolved(); Trap::OOM { backtrace } } } /// Catches any wasm traps that happen within the execution of `closure`, //...
{ // The stack limit was previously set by a previous wasm // call on the stack. We leave the original stack limit for // wasm in place in that case, and don't reset the stack // limit when we're done. false }
conditional_block
travel-assistance.js
<div className="privacy-content-holder"> <p className="lead left"> When to visit:</p> <p className="content"> If you want to do an intro to scuba program or an Open Water course, you can come at any time of the year. The sites that you visit as part of these programs are accessib...
worst on the islands ( Airtel and Vodafone have decent coverage in
<p className="content"> Indian residents please note - BSNL is considered to be the best of the
random_line_split
lifecycle.rs
uintptr_t*)NULL); rc = sys_shmem_detach(mrapi_db_local); if (!rc) { fprintf(stderr, "mrapi_impl_free_resources: ERROR: sys_shmem detach (mrapi_db) failed\n"); } } // if there are no other valid nodes in the whole system, then free the shared memory if (last_man_standing) { // free the mrapi inter...
MRAPI_TID.with(|id| { id.set(tid); }); // Seed random number generator os_srand(tid);
random_line_split
main_test.go
Client // resolver esClient elastic.ESClient // elastic client to verify the results elasticsearchAddr string // elastic address elasticsearchName string // name of the elasticsearch server name; used to stop the server elasticsearchDir...
if t.storeConfig == nil { t.storeConfig = &events.StoreConfig{} } t.recorders = &recorders{} // start elasticsearch if err = t.startElasticsearch(); err != nil { t.logger.Errorf("failed to start elasticsearch, err: %v", err) return err } // create elasticsearch client if err = t.createElasticClient()...
{ t.batchInterval = 100 * time.Millisecond }
conditional_block