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
stat.go
stock_map := smap.New(true) stock_map.Set(kline_data.Stockcode, stat) acc_map = smap.New(true) acc_map.Set(account, stock_map) mapResult.Set(user, acc_map) } DoCalculateSTK(kline_data, stat) } func GetTransaction() { for { var con *kdb.KDBConn var err error con, err = kdb.DialKDB("127.0.0.1", ...
ice //临时对象记录下之前的均价 //卖的大于原有仓位 var flag bool = false if AbsInt(newOrder.Bidvol) >= AbsInt(stat.SpaceStk.SpaceVol) { flag = true } stat.SpaceStk.SpaceVol = stat.SpaceStk.SpaceVol + newOrder.Bidvol fmt.Println("算仓位", stat.SpaceStk.SpaceVol) if newOrder.Bidvol > 0 { //算均价 if spaceTemp < 0 { if ...
identifier_body
stat.go
go GetTransaction() printMap() // <-marketChan fmt.Println("==stat=over===") } func SelectTransaction() { fmt.Println("==SelectTransaction==") var con *kdb.KDBConn var err error con, err = kdb.DialKDB("139.224.9.75", 52800, "") // con, err = kdb.DialKDB("139.196.77.165", 5033, "") if err != nil { fmt.Pri...
onnect kdb: %s", err.Error()) return } err = con.AsyncCall(".u.sub", &kdb.K{-kdb.KS, kdb.NONE, "Market"}, &kdb.K{-kdb.KS, kdb.NONE, ""}) if err != nil { fmt.Println("Subscribe: %s", err.Error()) return } res, _, err := con.ReadMessage() if err != nil { fmt.Println("Error processing message: ...
iled to c
identifier_name
expdescription.py
.isDataChanged(): self.writeExperimentConfiguration(ask=True) Qt.QWidget.closeEvent(self, event) def setModel(self, model): '''reimplemented from :class:`TaurusBaseWidget`''' TaurusBaseWidget.setModel(self, model) self._reloadConf(force=True) #set the model of so...
def deleteMntGrp(self): '''creates a new Measurement Group''' activeMntGrpName = str(self.ui.activeMntGrpCB.currentText()) op = Qt.QMessageBox.question(self, "Delete Measurement Group",
random_line_split
expdescription.py
(Qt.QWidget, TaurusBaseWidget): ''' A widget for editing the configuration of a experiment (measurement groups, plot and storage parameters, etc). It receives a Sardana Door name as its model and gets/sets the configuration using the `ExperimentConfiguration` environmental variable for that Doo...
ExpDescriptionEditor
identifier_name
expdescription.py
self.togglePlotsAction.setEnabled(plotsButton) self.addAction(self.togglePlotsAction) self.connect(self.togglePlotsAction, Qt.SIGNAL("toggled(bool)"), self.onPlotsButtonToggled) self.ui.plotsButton.setDefaultAction(self.togglePlotsAction) if door is not No...
'''creates a new Measurement Group''' if self._localConfig is None: return mntGrpName, ok = Qt.QInputDialog.getText(self, "New Measurement Group", "Enter a name for the new measurement Group") if not ok: return mntGrpName = s...
identifier_body
expdescription.py
BaseWidget.__init__(self, 'ExpDescriptionEditor') self.loadUi() self.ui.buttonBox.setStandardButtons(Qt.QDialogButtonBox.Reset | Qt.QDialogButtonBox.Apply) newperspectivesDict = copy.deepcopy(self.ui.sardanaElementTree.KnownPerspectives) #newperspectivesDict[self.ui.sardanaElementTree.Df...
door = self.getModelObj() if door is None: return conf = door.getExperimentConfiguration() self._originalConfiguration = copy.deepcopy(conf) self.setLocalConfig(conf) self._setDirty(False) self._dirtyMntGrps = set() #set a list of available channels ...
op = Qt.QMessageBox.question(self, "Reload info from door", "If you reload, all current experiment configuration changes will be lost. Reload?", Qt.QMessageBox.Yes | Qt.QMessageBox.Cancel) if op != Qt.QMessageBox.Yes: return
conditional_block
a1.py
AG", "CTGA") True >>> pair_genes("TCAG", "CCAG") False ''' # declare a boolean that indicates whether the two genes are pairable can_pair = False # create a sample of gene that can pair sample_gene = "" for nucleotide in first_gene: if (nucleotide == "A"): ...
# check if the indices are found in source gene if (source_start_anchor != -1 and source_end_anchor != -1): # check if the indices are found in destination gene if (destination_start_anchor != -1 and destination_end_anchor != -1): # for loop to find the anchor sequence from t...
destination_start_anchor = destination_gene.rfind(start_anchor) destination_end_anchor = destination_gene.rfind( end_anchor, destination_start_anchor)
conditional_block
a1.py
] == "A"): zip_length_count += 1 # once the gene can no longer zip, # returns the zip length right away else: return zip_length_count def splice_gene(source, destination, start_anchor, end_anchor): ''' (list, list, str, str) -> None This function perfo...
process_gene_file
identifier_name
a1.py
AG", "CTGA") True >>> pair_genes("TCAG", "CCAG") False ''' # declare a boolean that indicates whether the two genes are pairable can_pair = False # create a sample of gene that can pair sample_gene = "" for nucleotide in first_gene: if (nucleotide == "A"): ...
destination_gene = "" for j in range(len(destination)): destination_gene += destination[j] # find the index of start and end anchor from the source source_start_anchor = source_gene.find(start_anchor) source_end_anchor = source_gene.find(end_anchor, source_start_anchor) # start...
''' (list, list, str, str) -> None This function performs splicing of gene sequences. Splicing of genes can be done by taking a nucleotide sequence from one gene and replace it with a nucleotide sequence from another. First, find the anchor sequences, which are the sequences found within the st...
identifier_body
a1.py
AG", "CTGA") True >>> pair_genes("TCAG", "CCAG") False ''' # declare a boolean that indicates whether the two genes are pairable can_pair = False # create a sample of gene that can pair sample_gene = "" for nucleotide in first_gene: if (nucleotide == "A"): ...
>>> zip_length("AGTCTCGCT") 2 >>> zip_length("AGTCTCGAG") 0 ''' # declare a variable that counts the zip length zip_length_count = 0 # for loop that is in charge of each nucleotides from the left for left_index in range(len(gene)): # declare a variable that is in...
This function returns an integer value that indicates the maximum number of nucleotides pairs that the gene can zip. REQ: genes must be consisted of letters {A, G, C, T}
random_line_split
runner.rs
of threads to use to run tasks. pub fn jobs(&mut self, jobs: usize) { self.jobs = jobs; } /// Adds a path to Lua's require path for modules. pub fn include_path<P: Into<PathBuf>>(&mut self, path: P) { self.spec.include_paths.push(path.into()); } /// Sets a variable value. ...
return Err(format!("no matching task or rule for '{}'", name.as_ref()).into()); }
conditional_block
runner.rs
_all(&runtime); // Set include paths. for path in &self.include_paths { runtime.include_path(&path); } // Set the OS runtime.state().push_string(if cfg!(windows) { "windows" } else { "unix" }); runtime.state().set_glob...
(&mut self) { self.spec.always_run = true; } /// Run all tasks even if they throw errors. pub fn keep_going(&mut self) { self.spec.keep_going = true; } /// Sets the number of threads to use to run tasks. pub fn jobs(&mut self, jobs: usize) { self.jobs = jobs; } ...
always_run
identifier_name
runner.rs
(&runtime); // Set include paths. for path in &self.include_paths { runtime.include_path(&path); } // Set the OS runtime.state().push_string(if cfg!(windows) { "windows" } else { "unix" }); runtime.state().set_global("...
/// Run all tasks even if they throw errors. pub fn keep_going(&mut self) { self.spec.keep_going = true; } /// Sets the number of threads to use to run tasks. pub fn jobs(&mut self, jobs: usize) { self.jobs = jobs; } /// Adds a path to Lua's require path for modules. ...
{ self.spec.always_run = true; }
identifier_body
runner.rs
pub fn new<P: Into<PathBuf>>(path: P) -> Result<Runner, Box<Error>> { // By default, set the number of jobs to be one less than the number of available CPU cores. let jobs = cmp::max(1, num_cpus::get() - 1); let path = path.into(); let directory: PathBuf = match path.parent() { ...
current_tasks.insert(thread_id, task.name().to_string()); free_threads.remove(&thread_id);
random_line_split
assembly_finishing_objects.py
um_sequences[self.contigs[current+1].search_true_first_sequence(start, step)].start): # could it fit after the next contig self.swap_contigs(current, current + 1) continue # restart the loop if(j == len(c.mum_sequences)): # all mum_sequences fit on the already treated part, so we discard it cur...
while(i < len(mums)): if (mums[i][5] != orientation): self.mum_sequences.append(Mum_sequence(orientation, mums[j:i])) orientation = mums[i][5] j = i elif (abs(mums[i-1][1] - mums[i][1]) > 2000000): # arbitrary value that is much bigger than any small jump that could happen, but smaller than the size...
j = 0 if (len(mums) == 1): self.mum_sequences.append(Mum_sequence(orientation, mums)) return
random_line_split
assembly_finishing_objects.py
= current else: tmp = current + 1 else: if (c.futur == 0): tmp = current +1 else: tmp = current self.contigs[tmp : rev] = reversed(self.contigs[tmp : rev]) #################### orientation = 0 current = rev-1 j += 1 break # because ...
ind_rolling_gap(
identifier_name
assembly_finishing_objects.py
_sequences[j].height): # good if (not recursion): if orientation == 0: orientation = 1 # else: # orientation = 0 else: break # print "\n\n\n\n\n\nINVERSED CONCATENATION ORDER\n\n\n\n\n\n" tmp_start = c.get_position_before_gap(step) self.orientate(curre...
= j + 1 start_height = self.mum_sequences[j].height current_height = start_height restarted = False while (i < len(self.mum_sequences)): if (self.mum_sequences[i].height > current_height): # current_height = self.mum_sequences[i].height ## ADDED THIS i += 1 continue elif (self.mum_sequences[i...
identifier_body
assembly_finishing_objects.py
_sequences[self.contigs[current+1].search_true_first_sequence(start, step)].start): # could it fit after the next contig self.swap_contigs(current, current + 1) continue # restart the loop if(j == len(c.mum_sequences)): # all mum_sequences fit on the already treated part, so we discard it curre...
if (res == 1): # rolling case print "\n\nHERE\n\n" # search for vertical gap between a and b # while (compare_heights(a, b)): ## TODO need a function to check when it goes from top to bottom gap, if direct/direct, fisrt higher, if reverse/reverse, first lower res = c.find_rolling_gap() # c...
c.futur = 1
conditional_block
Ch11. Ex.py
first batch of input the user would enter Chris Jesse Sally # this is the second batch of input the user would enter Grade for Chris: 90 Grade for Jesse: 80 Grade for Sally: 70 # below is what your program should output Class roster: Chris (90.0) Jesse (80.0) Sally (70.0) Average grade: 80.0 """ import sys sys.setE...
contacts):
identifier_name
Ch11. Ex.py
0 percentage scale. Use 2 lists (grades and students) and the enumerate function in your solution. A test run of this program would yield the following: # this is the first batch of input the user would enter Chris Jesse Sally # this is the second batch of input the user would enter Grade for Chris: 90 Grade for Jes...
print("\nAverage grade:", (total_score / len(students))) #3. Implement the functionality of the above program using a dictionary instead of a list. import sys sys.setExecutionLimit(70000) students = {} total_score = 0.0 name = input("Enter the name of a student. (When finished, enter nothing)") while (name != "...
tal_score += grades[index] print("{0} ({1:.1})".format(student, grades[index]))
conditional_block
Ch11. Ex.py
if __name__ == "__main__": main() """2. Write a program that will function as a grade book, allowing a user (a professor or teacher) to enter the class roster for a course, along with each student’s cumulative grade. It then prints the class roster along with the average cumulative grade. Grades are on a 0-1...
text = input("Please enter a sentence: ") chars = create_dict(text) print_dict(chars)
identifier_body
Ch11. Ex.py
0 percentage scale. Use 2 lists (grades and students) and the enumerate function in your solution. A test run of this program would yield the following: # this is the first batch of input the user would enter Chris Jesse Sally # this is the second batch of input the user would enter Grade for Chris: 90 Grade for Jes...
students = [] grades = [] total_score = 0.0 name = input("Enter the name of a student. (When finished, enter nothing)") while (name != ""): students += [name] name = input("Enter the name of a student. (When finished, enter nothing)") for i in range(len(students)): score = float(input("Grade for {0}:".f...
random_line_split
train_folds.py
anaconda3\envs\arc105\bin'.format(homepath), \ r'{}\anaconda3\condabin'.format(homepath)] for i in list_lib: os.environ['PATH'] = '%s;%s' % (i, os.environ['PATH']) os.environ['CUDA_LAUNCH_BLOCKING'] = '1' import numpy as np #print(np.__version__) import argparse, copy, shutil import random from torch.utils...
num_workers=4, drop_last=True) dataset_val = dataloader.RS_Loader_Semantic(dataset_dir, num_classes, mode='val', indices=indices['val'], isRGB=isRGB) dataloaders_d...
batch_size=batch_size,
random_line_split
train_folds.py
anaconda3\envs\arc105\bin'.format(homepath), \ r'{}\anaconda3\condabin'.format(homepath)] for i in list_lib: os.environ['PATH'] = '%s;%s' % (i, os.environ['PATH']) os.environ['CUDA_LAUNCH_BLOCKING'] = '1' import numpy as np #print(np.__version__) import argparse, copy, shutil import random from torch.utils...
#print(indices_train) #print(indices_val) #print(indices_test) indices = {} indices['train'] = indices_train indices['val'] = indices_val indices['test'] = indices_test return indices def main(): parser = argparse.ArgumentParser(description='Semantic Segmen...
list_folds = np.array(range(5)) # Roll in axis tmp_set = np.roll(list_folds,id_fold) indices_train = [] indices_val = [] indices_test = [] # Train for i in tmp_set[:3]: indices_train += list(data[data[:,1].astype(int) == i][:,0]) # Val for i in tmp_set[3:4]: ...
identifier_body
train_folds.py
anaconda3\envs\arc105\bin'.format(homepath), \ r'{}\anaconda3\condabin'.format(homepath)] for i in list_lib: os.environ['PATH'] = '%s;%s' % (i, os.environ['PATH']) os.environ['CUDA_LAUNCH_BLOCKING'] = '1' import numpy as np #print(np.__version__) import argparse, copy, shutil import random from torch.utils...
# Test for i in tmp_set[4:]: indices_test += list(data[data[:,1].astype(int) == i][:,0]) #print(indices_train) #print(indices_val) #print(indices_test) indices = {} indices['train'] = indices_train indices['val'] = indices_val indices['test'] = indice...
indices_val += list(data[data[:,1].astype(int) == i][:,0])
conditional_block
train_folds.py
anaconda3\envs\arc105\bin'.format(homepath), \ r'{}\anaconda3\condabin'.format(homepath)] for i in list_lib: os.environ['PATH'] = '%s;%s' % (i, os.environ['PATH']) os.environ['CUDA_LAUNCH_BLOCKING'] = '1' import numpy as np #print(np.__version__) import argparse, copy, shutil import random from torch.utils...
(id_fold, data): # Instantiate Folds list_folds = np.array(range(5)) # Roll in axis tmp_set = np.roll(list_folds,id_fold) indices_train = [] indices_val = [] indices_test = [] # Train for i in tmp_set[:3]: indices_train += list(data[data[:,1].astype(int) == i][:,0]) ...
get_indices
identifier_name
backtrace.rs
; use intrinsics; use io; use libc; use mem; use path::Path; use ptr; use str; use sync::{StaticMutex, MUTEX_INIT}; use sys_common::backtrace::*; #[allow(non_snake_case)] extern "system" { fn GetCurrentProcess() -> libc::HANDLE; fn GetCurrentThread() -> libc::HANDLE; fn RtlCaptureContext(ctx: *mut arch::C...
{ Offset: u64, Segment: u16, Mode: ADDRESS_MODE, } pub struct STACKFRAME64 { AddrPC: ADDRESS64, AddrReturn: ADDRESS64, AddrFrame: ADDRESS64, AddrStack: ADDRESS64, AddrBStore: ADDRESS64, FuncTableEntry: *mut libc::c_void, Params: [u64; 4], Far: libc::BOOL, Virtual: libc:...
ADDRESS64
identifier_name
backtrace.rs
; use intrinsics; use io; use libc; use mem; use path::Path; use ptr; use str; use sync::{StaticMutex, MUTEX_INIT}; use sys_common::backtrace::*; #[allow(non_snake_case)] extern "system" { fn GetCurrentProcess() -> libc::HANDLE; fn GetCurrentThread() -> libc::HANDLE; fn RtlCaptureContext(ctx: *mut arch::C...
type SymInitializeFn = extern "system" fn(libc::HANDLE, *mut libc::c_void, libc::BOOL) -> libc::BOOL; type SymCleanupFn = extern "system" fn(libc::HANDLE) -> libc::BOOL; type StackWalk64Fn = extern "system" fn(libc::DWORD, libc::HANDLE, libc::HANDLE, *mut STACK...
*mut SYMBOL_INFO) -> libc::BOOL;
random_line_split
backtrace.rs
size up to MAX_SYM_NAME. Name: [libc::c_char; MAX_SYM_NAME], } #[repr(C)] enum ADDRESS_MODE { AddrMode1616, AddrMode1632, AddrModeReal, AddrModeFlat, } struct ADDRESS64 { Offset: u64, Segment: u16, Mode: ADDRESS_MODE, } pub struct STACKFRAME64 { AddrPC: ADDRESS64, AddrReturn...
{ break }
conditional_block
platform_types.rs
(ref cp1), Ok(ref cp2)) if cp1 == cp2 => { Equal } _ => { p1.cmp(p2) } } } (Path(_), Scratch(_)) => { Less } (Scratch(_), Path(_)) => { Greater ...
MenuView::FileSwitcher(ref fs) => Some(&fs.search), _ => Option::None,
random_line_split
platform_types.rs
other.into(); k.cmp(&o) }); #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HighlightKind { User, Result, CurrentResult, } d!(for HighlightKind: HighlightKind::User); #[derive(Clone, Debug, PartialEq, Eq)] pub struct Highlight { pub min: Position, pub max: Position, pub kind: Highl...
(&self) -> MenuMode { match self { Self::None => MenuMode::Hidden, Self::FileSwitcher(_) => MenuMode::FileSwitcher, Self::FindReplace(v) => MenuMode::FindReplace(v.mode), Self::GoToPosition(_) => MenuMode::GoToPosition, } } } #[must_use] pub fn kind_e...
get_mode
identifier_name
platform_types.rs
), Ok(ref cp2)) if cp1 == cp2 => { Equal } _ => { p1.cmp(p2) } } } (Path(_), Scratch(_)) => { Less } (Scratch(_), Path(_)) => { Greater } ...
{ use BufferIdKind::*; match self.current_buffer_kind { // Seems like we never actually need to access the Text buffer // cursors here. If we want to later, then some additional restructuring // will be needed, at least according to the comment this comment ...
identifier_body
pvc-clone-controller.go
") } if err := addCloneToken(dataVolume, pvc); err != nil { return err } sourceNamespace := dataVolume.Spec.Source.PVC.Namespace if sourceNamespace == "" { sourceNamespace = dataVolume.Namespace } pvc.Annotations[cc.AnnCloneRequest] = sourceNamespace + "/" + dataVolume.Spec.Source.PVC.Name return nil } fun...
{ // TODO preper const eventReason := "CloneSourceInUse" // Check if any pods are using the source PVC inUse, err := r.sourceInUse(datavolume, eventReason) if err != nil { return false, err } // Check if the source PVC is fully populated populated, err := r.isSourcePVCPopulated(datavolume) if err != nil { ...
identifier_body
pvc-clone-controller.go
error { dv := syncState.dvMutated if err := r.populateSourceIfSourceRef(dv); err != nil { return err } return nil } func (r *PvcCloneReconciler) cleanup(syncState *dvSyncState) error { dv := syncState.dvMutated if err := r.populateSourceIfSourceRef(dv); err != nil { return err } if dv.DeletionTimestamp =...
(dv *cdiv1.DataVolume, pvc *corev1.PersistentVolumeClaim) error { // first clear out tokens that may have already been added delete(pvc.Annotations, cc.AnnCloneToken) delete(pvc.Annotations, cc.AnnExtendedCloneToken) if isCrossNamespaceClone(dv) { // only want this initially // extended token is added later t...
addCloneToken
identifier_name
pvc-clone-controller.go
getKey := func(namespace, name string) string { return namespace + "/" + name } if err := mgr.GetFieldIndexer().IndexField(context.TODO(), &cdiv1.DataVolume{}, dvDataSourceField, func(obj client.Object) []string { if sourceRef := obj.(*cdiv1.DataVolume).Spec.SourceRef; sourceRef != nil && sourceRef.Kind == cdiv...
random_line_split
pvc-clone-controller.go
{ dv := syncState.dvMutated if err := r.populateSourceIfSourceRef(dv); err != nil { return err } return nil } func (r *PvcCloneReconciler) cleanup(syncState *dvSyncState) error { dv := syncState.dvMutated if err := r.populateSourceIfSourceRef(dv); err != nil { return err } if dv.DeletionTimestamp == nil ...
pvc = newPvc } if syncRes.usePopulator { if err := r.reconcileVolumeCloneSourceCR(&syncRes); err != nil { return syncRes, err } ct, ok := pvc.Annotations[cc.AnnCloneType] if ok { cc.AddAnnotation(datavolume, cc.AnnCloneType, ct) } } else { cc.AddAnnotation(datavolume, cc.AnnCloneType, string(c...
{ if cc.ErrQuotaExceeded(err) { syncErr = r.syncDataVolumeStatusPhaseWithEvent(&syncRes, cdiv1.Pending, nil, Event{ eventType: corev1.EventTypeWarning, reason: cc.ErrExceededQuota, message: err.Error(), }) if syncErr != nil { log.Error(syncErr, "failed to sync DataVolume...
conditional_block
migration.ts
const existingImport = findImportSpecifier(node.elements, oldImport); if (!existingImport) { throw new Error(`Could not find an import to replace using ${oldImport}.`); } return ts.updateNamedImports(node, [ ...node.elements.filter(current => current !== existingImport), // Create a new import whil...
(node: ts.CallExpression): ts.Node { const [target, name, args] = node.arguments; const isNameStatic = ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name); const isArgsStatic = !args || ts.isArrayLiteralExpression(args); if (isNameStatic && isArgsStatic) { // If the name is a static string...
migrateInvokeElementMethod
identifier_name
migration.ts
const existingImport = findImportSpecifier(node.elements, oldImport); if (!existingImport) { throw new Error(`Could not find an import to replace using ${oldImport}.`); } return ts.updateNamedImports(node, [ ...node.elements.filter(current => current !== existingImport), // Create a new import whil...
return node; } /** * Migrates a call to `invokeElementMethod(target, method, [arg1, arg2])` either to * `target.method(arg1, arg2)` or `(target as any)[method].apply(target, [arg1, arg2])`. */ function migrateInvokeElementMethod(node: ts.CallExpression): ts.Node { const [target, name, args] = node.arguments; ...
{ // We need the checks for string literals, because the type of something // like `"blue"` is the literal `blue`, not `string`. if (lastArgType === 'string' || lastArgType === 'number' || ts.isStringLiteral(args[2]) || ts.isNoSubstitutionTemplateLiteral(args[2]) || ts.isNumericLiteral(args[2])) { ...
conditional_block
migration.ts
const existingImport = findImportSpecifier(node.elements, oldImport); if (!existingImport) { throw new Error(`Could not find an import to replace using ${oldImport}.`); } return ts.updateNamedImports(node, [ ...node.elements.filter(current => current !== existingImport), // Create a new import whil...
// Otherwise create a ternary on the variable. return ts.createConditional(isAddArgument, createRendererCall(true), createRendererCall(false)); } /** * Migrates a call to `setElementStyle` call either to a call to * `setStyle` or `removeStyle`. or to an expression like * `value == null ? removeStyle(el, key) :...
{ // Clone so we don't mutate by accident. Note that we assume that // the user's code is providing all three required arguments. const outputMethodArgs = node.arguments.slice(); const isAddArgument = outputMethodArgs.pop()!; const createRendererCall = (isAdd: boolean) => { const innerExpression = node.ex...
identifier_body
migration.ts
const existingImport = findImportSpecifier(node.elements, oldImport); if (!existingImport) { throw new Error(`Could not find an import to replace using ${oldImport}.`); } return ts.updateNamedImports(node, [ ...node.elements.filter(current => current !== existingImport), // Create a new import whil...
/** * Migrates a call to `setElementClass` either to a call to `addClass` or `removeClass`, or * to an expression like `isAdd ? addClass(el, className) : removeClass(el, className)`. */ function migrateSetElementClass(node: PropertyAccessCallExpression): ts.Node { // Clone so we don't mutate by accident. Note that...
return node; }
random_line_split
page.js
( req, res ) { var cmds = {}; function cmd( group, url, link, help ) { this.url = url; this.link = link; this.help = help; if(!cmds[group]) { cmds[group] = {}; cmds[group].items = [ ] }; cmds[group].items.push(this); } var user = loginstate.getU...
buildMenu
identifier_name
page.js
; cmds[group].items.push(this); } var user = loginstate.getUser(req); new cmd('safeharbor', '/about', 'About', 'Learn about Safe Harbor'); new cmd('safeharbor', '/learn', 'Learn', 'Learn about your rights and the DMCA'); new cmd('safeharbor', '/support', 'Support', 'Ask us stuf...
{ cmds[group] = {}; cmds[group].items = [ ] }
conditional_block
page.js
ellings":"PA"} ,{name:"Papua New Guinea","data-alternative-spellings":"PG"} ,{name:"Paraguay","data-alternative-spellings":"PY"} ,{name:"Peru","data-alternative-spellings":"PE"} ,{name:"Philippines","data-alternative-spellings":"PH Pilipinas","data-relevancy-booster":"1.5"} ,{name:"Pitcairn","data-alternative-spel...
random_line_split
page.js
var user = loginstate.getUser(req); new cmd('safeharbor', '/about', 'About', 'Learn about Safe Harbor'); new cmd('safeharbor', '/learn', 'Learn', 'Learn about your rights and the DMCA'); new cmd('safeharbor', '/support', 'Support', 'Ask us stuff'); if( user ) { new c...
{ this.url = url; this.link = link; this.help = help; if(!cmds[group]) { cmds[group] = {}; cmds[group].items = [ ] }; cmds[group].items.push(this); }
identifier_body
eval.rs
Val> { unwrap_from_context("Variable", id, self.vars.get(id)) } pub fn add_var(&mut self, id: Ident, val: RunVal, ty: Type) -> Ret { self.vars.insert(id.clone(), val); self.types.add_var_type(id, ty) } pub fn find_type(&self, id: &Ident) -> Ret<Type> { self.types.find_type(id) } pub fn add_type(&mut...
(&mut self, id: String, variants: Vec<Ident>) -> Ret { let rc = Rc::new(DataType {id: id.clone(), variants: variants.clone()}); for (i, variant) in variants.iter().enumerate() { self.add_var(variant.clone(), RunVal::Data(rc.clone(), i), Type::Data(rc.clone()))?; } self.add_type(id, Type::Data(rc)) } pub ...
add_datatype
identifier_name
eval.rs
RunVal> { unwrap_from_context("Variable", id, self.vars.get(id)) } pub fn add_var(&mut self, id: Ident, val: RunVal, ty: Type) -> Ret { self.vars.insert(id.clone(), val); self.types.add_var_type(id, ty) } pub fn find_type(&self, id: &Ident) -> Ret<Type> { self.types.find_type(id) } pub fn add_type(&...
} eval_exp(exp, ctx) }, _ => eval_exp(exp, ctx), } } pub fn eval_exp_seq(seq: &Vec<Exp>, ctx: &Context) -> Vec<RunVal> { seq.iter().flat_map(|e| { if let Exp::Expand(ref e) = e { let val = eval_exp(e, ctx); let err = Error(format!("Cannot expand value: {}", val)); iter...
for decl in decls { eval_decl(decl, ctx).unwrap();
random_line_split
eval.rs
, ctx)), // build_state(eval_exp(then_exp, ctx)), // ]), Type::Any /* TODO determine from then/else types */) panic!("Non-boolean value: {}", val) } }, &Exp::Lambda(ref pat, ref body) => { let ty = infer_type(exp, ctx.types()).unwrap(); RunVal::Func(Rc::new(ctx.clone()), pat.clone(),...
{ Some((0..i).map(RunVal::Index).collect()) }
conditional_block
eval.rs
} #[derive(Clone,Debug,PartialEq)] pub struct Context { path: String, vars: HashMap<Ident, RunVal>, types: TypeContext, } impl Context { pub fn new(path: String) -> Context { Context { path, vars: HashMap::new(), types: TypeContext::new(), } } pub fn path(&self) -> &String { &self.path } p...
{ match self { &RunVal::Index(ref n) => write!(f, "{}", n), &RunVal::String(ref s) => write!(f, "{:?}", s), &RunVal::Data(ref dt, ref index) => write!(f, "{}", dt.variants[*index]), &RunVal::Tuple(ref vals) => write!(f, "({})", vals.iter().map(|val| format!("{}", val)).collect::<Vec<_>>().join(", ")), ...
identifier_body
avx.rs
1 * Cb + 23 * Cr) / 32 let g4 = _mm256_srai_epi16::<5>(g3); // Y - (11 * Cb + 23 * Cr) / 32 ; let g = YmmRegister { mm256: clamp_avx(_mm256_sub_epi16(y_c, g4)) }; // b = Y + 113 * Cb / 64 // 113 * cb let b1 = _mm256_mullo_epi16(_mm256_set1_epi16(113), cb_r); //113 * Cb / 64 ...
let max_v = _mm256_max_epi16(reg, min_s); //max(a,0) let min_v = _mm256_min_epi16(max_v, max_s); //min(max(a,0),255)
random_line_split
avx.rs
offset: &mut usize ) { // Load output buffer let tmp: &mut [u8; 48] = out .get_mut(*offset..*offset + 48) .expect("Slice to small cannot write") .try_into() .unwrap(); let (r, g, b) = ycbcr_to_rgb_baseline(y, cb, cr); let mut j = 0; let mut i = 0; while i < 48 ...
{ unsafe { ycbcr_to_rgba_unsafe(y, cb, cr, out, offset); } }
identifier_body
avx.rs
= out .get_mut(*offset..*offset + 48) .expect("Slice to small cannot write") .try_into() .unwrap(); let (r, g, b) = ycbcr_to_rgb_baseline(y, cb, cr); let mut j = 0; let mut i = 0; while i < 48 { tmp[i] = r.array[j] as u8; tmp[i + 1] = g.array[j] as u8;...
ycbcr_to_rgba_unsafe
identifier_name
run.js
(scam) { let abusereport = stripIndents`I would like to inform you of suspicious activities at the domain ${url.parse(scam.url).hostname} ${'ip' in scam ? `located at IP address ${scam['ip']}`: ''}. ${'subcategory' in scam && scam.subcategory == "NanoWallet" ? `The domain is impersonating NanoWallet.io, ...
generateAbuseReport
identifier_name
run.js
/report/address/ or /report/domain/fake-mycrypto.com app.get('/report/:type?/:value?', async function (req, res, next) { let value = '' if (req.params.value) { value = safeHtml`${req.params.value}` } switch (`${req.params.type}`) { case 'address': res.send(await helpers.layout('...
var intActiveScams = 0 var intInactiveScams = 0 scams.forEach(function (scam) { if ('addresses' in scam) { scam.addresses.forEach(function (address) { addresses[address] = true }) } if ('status' in scam) { if (scam.status === 'Active') { ++intA...
let addresses = {}
random_line_split
run.js
/report/address/ or /report/domain/fake-mycrypto.com app.get('/report/:type?/:value?', async function (req, res, next) { let value = '' if (req.params.value) { value = safeHtml`${req.params.value}` } switch (`${req.params.type}`) { case 'address': res.send(await helpers.layout('...
else { return -1 } }) break case 'subcategory': sorting.subcategory = 'sorted' direction.subcategory = currentDirection scams.sort(function (a, b) { if ('subcategory' in a && 'subcategory' in b && a.subcategory && b.subcategory) { ...
{ return a.category.localeCompare(b.category) }
conditional_block
run.js
Please shut down this domain so further attacks will be prevented.` return abusereport } /* Start the web server */ function startWebServer() { app.use(express.static('_static')); // Serve all static pages first app.use('/screenshot', express.static('_cache/screenshots/')); // Serve all screenshots app...
{ let abusereport = stripIndents`I would like to inform you of suspicious activities at the domain ${url.parse(scam.url).hostname} ${'ip' in scam ? `located at IP address ${scam['ip']}`: ''}. ${'subcategory' in scam && scam.subcategory == "NanoWallet" ? `The domain is impersonating NanoWallet.io, a websi...
identifier_body
Index.js
status: '2' }, filterValue: { status: [2] }, searchData: {}, downloadStatus: 0, agencyTree: null, } } async componentDidMount() { this.getRechargeDetails(); this.getAgencyTree(); } getAgencyTree() { DataAgencys.getTreeData(this.props.match.params.id, (data) => { this.setState(...
= { time_exp: `${moment().startOf('day').add(-1, 'month').unix()},${moment().endOf('day').unix()}`, ...state.filterInfo, ...state.searchData }; this.setState({ downloadStatus: 2 }); NetOperation.exportRecharge(data).then((res) => { const items = res.data; if (items && items.id) { this.download...
const data
identifier_name
Index.js
status: '2' }, filterValue: { status: [2] }, searchData: {}, downloadStatus: 0, agencyTree: null, } } async componentDidMount() { this
encyTree() { DataAgencys.getTreeData(this.props.match.params.id, (data) => { this.setState({ agencyTree: data }); }, true); } getRechargeDetails() { const { filterInfo, searchData } = this.state; const data = { time_exp: `${moment().startOf('day').add(-1, 'month').unix()},${moment().endOf('day').unix()...
.getRechargeDetails(); this.getAgencyTree(); } getAg
identifier_body
Index.js
status: '2' }, filterValue: { status: [2] }, searchData: {}, downloadStatus: 0, agencyTree: null, } } async componentDidMount() { this.getRechargeDetails(); this.getAgencyTree(); } getAgencyTree() { DataAgencys.getTreeData(this.props.match.params.id, (data) => { this.setState(...
} }, { title: '交易金额', width: 100, align: 'right', render: (data) => utils.formatMoney((data.price * data.goods_amount) / 100) }, { title: '交易时间', dataIndex: 'create_time', width: 130, render: data => { if (data) { return moment.unix(data).format('YYYY-MM-DD HH:mm'); ...
render: data => { if (data.trim()) { return data; } return '-';
random_line_split
Index.js
status: '2' }, filterValue: { status: [2] }, searchData: {}, downloadStatus: 0, agencyTree: null, } } async componentDidMount() { this.getRechargeDetails(); this.getAgencyTree(); } getAgencyTree() { DataAgencys.getTreeData(this.props.match.params.id, (data) => { this.setState({ a...
mns = [ { title: '流水号', dataIndex: 'order_number', fixed: 'left', width: 210 }, { title: '三方单号', dataIndex: 'serial_number', fixed: 'left', width: 320, render: data => { if (data.trim()) { return data; } return '-'; } }, { title: '交易金额', widt...
creatColumns(state) { const colu
conditional_block
day_06.rs
/// /// This view is partial - the actual grid extends infinitely in all directions. /// Using the Manhattan distance, each location's closest coordinate can be /// determined, shown here in lowercase: /// /// aaaaa.cccc /// aAaaa.cccc /// aaaddecccc /// aadddeccCc /// ..dDdeeccc /// bb.deEeecc /// bBb.eeee.. /// bbb.e...
.unwrap(); println!("The biggest non-infinite area size is: {}", biggest_area_size); let concentrated_area = count_points_below(&points, &bounds, 10_000); println!("The size of the area that have a total distance less than \ 10.000 is: {}", concentrated_area); } fn create_grid(points...
{ let points = parse_input(include_str!("../input/day_06.txt")); let bounds = create_bounds(&points); let grid = create_grid(&points, &bounds); let mut areas = HashMap::new(); let mut infinite_areas = HashSet::new(); for (point, area_number) in grid.iter() { if on_bounds(point,&bounds)...
identifier_body
day_06.rs
For example, suppose you want the sum of the Manhattan distance to all of /// the coordinates to be less than 32. For each location, add up the distances /// to all of the given coordinates; if the total of those distances is less /// than 32, that location is within the desired region. Using the same /// coordinates ...
fn test_on_bounds() { let x_range = Range {min:0, max:3}; let y_range = Range {min:2, max:6};
random_line_split
day_06.rs
/// /// This view is partial - the actual grid extends infinitely in all directions. /// Using the Manhattan distance, each location's closest coordinate can be /// determined, shown here in lowercase: /// /// aaaaa.cccc /// aAaaa.cccc /// aaaddecccc /// aadddeccCc /// ..dDdeeccc /// bb.deEeecc /// bBb.eeee.. /// bbb.e...
(reference_point: &Point, points: &Vec<Point>) -> i32 { points.iter() .map(|point| distance(reference_point, point)) .sum() } fn closest_point(reference_point: &Point, points: &Vec<Point>) -> Option<usize> { let (index, _) = points.iter() .map(|point| distance(reference_point, point)) ...
total_distance
identifier_name
lib.rs
the License. // We take the "low road" here when returning the structs - we expose the // items (and arrays of items) as strings, which are JSON. The rust side of // the world gets serialization and deserialization for free and it makes // memory management that little bit simpler. extern crate failure; extern crate...
(&self, record: &log::Record) { let message = format!("{}:{} -- {}", record.level(), record.target(), record.args()); println!("{}", message); #[cfg(target_os = "android")] { unsafe { let message = ::std::ffi::CString::new(message).unwrap(); le...
log
identifier_name
lib.rs
// We take the "low road" here when returning the structs - we expose the // items (and arrays of items) as strings, which are JSON. The rust side of // the world gets serialization and deserialization for free and it makes // memory management that little bit simpler. extern crate failure; extern crate serde_json; ex...
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License.
random_line_split
lib.rs
the License. // We take the "low road" here when returning the structs - we expose the // items (and arrays of items) as strings, which are JSON. The rust side of // the world gets serialization and deserialization for free and it makes // memory management that little bit simpler. extern crate failure; extern crate...
#[no_mangle] pub unsafe extern "C" fn sync15_passwords_sync( state: *mut PasswordState, key_id: *const c_char, access_token: *const c_char, sync_key: *const c_char, tokenserver_url: *const c_char, error: *mut ExternError ) { with_translated_void_result(error, || { assert_pointer_not...
Ok(url::Url::parse(url)?) }
identifier_body
lucy.go
); extern cfish_Vector* GOLUCY_Doc_Field_Names(lucy_Doc *self); extern cfish_Vector* (*GOLUCY_Doc_Field_Names_BRIDGE)(lucy_Doc *self); extern bool GOLUCY_Doc_Equals(lucy_Doc *self, cfish_Obj *other); extern bool (*GOLUCY_Doc_Equals_BRIDGE)(lucy_Doc *self, cfish_Obj *other); extern void GOLUCY_Doc_Destroy(lucy_Doc *self...
(docID int32) Doc { retvalCF := C.lucy_Doc_new(nil, C.int32_t(docID)) return WRAPDoc(unsafe.Pointer(retvalCF)) } //export GOLUCY_Doc_init func GOLUCY_Doc_init(d *C.lucy_Doc, fields unsafe.Pointer, docID C.int32_t) *C.lucy_Doc { ivars := C.lucy_Doc_IVARS(d) if fields != nil { ivars.fields = unsafe.Pointer(C.cfish...
NewDoc
identifier_name
lucy.go
field); extern cfish_Vector* GOLUCY_Doc_Field_Names(lucy_Doc *self); extern cfish_Vector* (*GOLUCY_Doc_Field_Names_BRIDGE)(lucy_Doc *self); extern bool GOLUCY_Doc_Equals(lucy_Doc *self, cfish_Obj *other); extern bool (*GOLUCY_Doc_Equals_BRIDGE)(lucy_Doc *self, cfish_Obj *other); extern void GOLUCY_Doc_Destroy(lucy_Doc ...
registry.delete(rxID) C.cfish_super_destroy(unsafe.Pointer(rt), C.LUCY_REGEXTOKENIZER) } //export GOLUCY_RegexTokenizer_Tokenize_Utf8 func GOLUCY_RegexTokenizer_Tokenize_Utf8(rt *C.lucy_RegexTokenizer, str *C.char, stringLen C.size_t, inversion *C.lucy_Inversion) { ivars := C.lucy_RegexTokenizer_IVARS(rt) rxID :...
random_line_split
lucy.go
); extern cfish_Vector* GOLUCY_Doc_Field_Names(lucy_Doc *self); extern cfish_Vector* (*GOLUCY_Doc_Field_Names_BRIDGE)(lucy_Doc *self); extern bool GOLUCY_Doc_Equals(lucy_Doc *self, cfish_Obj *other); extern bool (*GOLUCY_Doc_Equals_BRIDGE)(lucy_Doc *self, cfish_Obj *other); extern void GOLUCY_Doc_Destroy(lucy_Doc *self...
else { patternGo = clownfish.CFStringToGo(unsafe.Pointer(pattern)) } rx, err := regexp.Compile(patternGo) if err != nil { panic(err) } rxID := registry.store(rx) ivars.token_re = unsafe.Pointer(rxID) return rt } //export GOLUCY_RegexTokenizer_Destroy func GOLUCY_RegexTokenizer_Destroy(rt *C.lucy_RegexToke...
{ patternGo = "\\w+(?:['\\x{2019}]\\w+)*" }
conditional_block
lucy.go
); extern cfish_Vector* GOLUCY_Doc_Field_Names(lucy_Doc *self); extern cfish_Vector* (*GOLUCY_Doc_Field_Names_BRIDGE)(lucy_Doc *self); extern bool GOLUCY_Doc_Equals(lucy_Doc *self, cfish_Obj *other); extern bool (*GOLUCY_Doc_Equals_BRIDGE)(lucy_Doc *self, cfish_Obj *other); extern void GOLUCY_Doc_Destroy(lucy_Doc *self...
//export GOLUCY_Doc_Set_Fields func GOLUCY_Doc_Set_Fields(d *C.lucy_Doc, fields unsafe.Pointer) { ivars := C.lucy_Doc_IVARS(d) temp := ivars.fields ivars.fields = unsafe.Pointer(C.cfish_inc_refcount(fields)) C.cfish_decref(temp) } //export GOLUCY_Doc_Get_Size func GOLUCY_Doc_Get_Size(d *C.lucy_Doc) C.uint32_t { ...
{ ivars := C.lucy_Doc_IVARS(d) if fields != nil { ivars.fields = unsafe.Pointer(C.cfish_inc_refcount(fields)) } else { ivars.fields = unsafe.Pointer(C.cfish_Hash_new(0)) } ivars.doc_id = docID return d }
identifier_body
settings.py
(section, option): return config.get(section, option) if config.has_option(section, option) else None return get(section, option) if section else get mailman_cfg = read_cfg('/etc/mailman.cfg') BASE_DIR = '/usr/lib/bundles/mailman-webui' CONF_DIR = '/etc/mailman-webui' DATA_DIR = '/var/lib/mailman-webui' ...
get
identifier_name
settings.py
return get(section, option) if section else get mailman_cfg = read_cfg('/etc/mailman.cfg') BASE_DIR = '/usr/lib/bundles/mailman-webui' CONF_DIR = '/etc/mailman-webui' DATA_DIR = '/var/lib/mailman-webui' LOG_DIR = '/var/log/mailman-webui' # Hosts/domain names that are valid for this site. # NOTE: You MUST add d...
return config.get(section, option) if config.has_option(section, option) else None
identifier_body
settings.py
Django settings for HyperKitty + Postorius Pay attention to settings ALLOWED_HOSTS and DATABASES! """ from os.path import abspath, dirname, join as joinpath from ConfigParser import SafeConfigParser def read_cfg(path, section=None, option=None): config = SafeConfigParser() config.read(path) def get(secti...
"""
random_line_split
settings.py
allauth', 'allauth.account', 'allauth.socialaccount', # Uncomment providers that you want to use, if any. #'allauth.socialaccount.providers.openid', #'allauth.socialaccount.providers.github', #'allauth.socialaccount.providers.gitlab', #'allauth.socialaccount.providers.google', #'allauth....
import ldap from django_auth_ldap.config import LDAPSearch ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, '/etc/ssl/certs') AUTH_LDAP_SERVER_URI = 'ldaps://ldap.example.org' AUTH_LDAP_USER_SEARCH = LDAPSearch( 'ou=People,dc=example,dc=org', ldap.SCOPE_SUBTREE, '(&(mail=*)(uid=%(use...
conditional_block
document-data.ts
DefinitionFor(modeId: string, wordDefinition: RegExp | null): void { _modeId2WordDefinition.set(modeId, wordDefinition); } export function getWordDefinitionFor(modeId: string): RegExp { return _modeId2WordDefinition.get(modeId)!; } export class DocumentDataExt { private disposed = false; private dirty...
private getText(): string { return this.lines.join(this.eol); } private validatePosition(position: theia.Position): theia.Position { if (!(position instanceof Position)) { throw new Error('Invalid argument'); } let { line, character } = position; let has...
return range; } return new Range(start.line, start.character, end.line, end.character); }
random_line_split
document-data.ts
DefinitionFor(modeId: string, wordDefinition: RegExp | null): void { _modeId2WordDefinition.set(modeId, wordDefinition); } export function getWordDefinitionFor(modeId: string): RegExp { return _modeId2WordDefinition.get(modeId)!; } export class DocumentDataExt { private disposed = false; private dirty...
() { return that.lines.length; }, lineAt(lineOrPos: number | theia.Position) { return that.lineAt(lineOrPos); }, offsetAt(pos) { return that.offsetAt(pos); }, positionAt(offset) { return that.positionAt(offset); }, validateRange(ran) { return that.validate...
lineCount
identifier_name
document-data.ts
get eol() { return that.eol === '\n' ? EndOfLine.LF : EndOfLine.CRLF; }, get lineCount() { return that.lines.length; }, lineAt(lineOrPos: number | theia.Position) { return that.lineAt(lineOrPos); }, offsetAt(pos) { return that.offsetAt(pos); }, ...
{ return new Range(position.line, wordAtText.startColumn - 1, position.line, wordAtText.endColumn - 1); }
conditional_block
document-data.ts
DefinitionFor(modeId: string, wordDefinition: RegExp | null): void { _modeId2WordDefinition.set(modeId, wordDefinition); } export function getWordDefinitionFor(modeId: string): RegExp { return _modeId2WordDefinition.get(modeId)!; } export class DocumentDataExt { private disposed = false; private dirty...
private validatePosition(position: theia.Position): theia.Position { if (!(position instanceof Position)) { throw new Error('Invalid argument'); } let { line, character } = position; let hasChanged = false; if (line < 0) { line = 0; cha...
{ return this.lines.join(this.eol); }
identifier_body
run_hook.go
/tools/clientcmd" "kmodules.xyz/client-go/meta" appcatalog_cs "kmodules.xyz/custom-resources/client/clientset/versioned" ) type hookOptions struct { masterURL string kubeConfigPath string namespace string hookType string backupSessionName string restoreSessionName string targe...
(hookErr error) error { statusOpt := status.UpdateStatusOptions{ Config: opt.config, KubeClient: opt.kubeClient, StashClient: opt.stashClient, Namespace: opt.namespace, Metrics: opt.metricOpts, TargetRef: v1beta1.TargetRef{ Kind: opt.targetKind, Name: opt.targetName, }, } if opt.hookT...
handlePreTaskHookFailure
identifier_name
run_hook.go
/clientcmd" "kmodules.xyz/client-go/meta" appcatalog_cs "kmodules.xyz/custom-resources/client/clientset/versioned" ) type hookOptions struct { masterURL string kubeConfigPath string namespace string hookType string backupSessionName string restoreSessionName string targetKind ...
} } } return "", fmt.Errorf("no pod found for AppBinding %s/%s", opt.namespace, appbindingName) } func (opt *hookOptions) handlePreTaskHookFailure(hookErr error) error { statusOpt := status.UpdateStatusOptions{ Config: opt.config, KubeClient: opt.kubeClient, StashClient: opt.stashClient, Namespa...
{ return notReadyAddrs.TargetRef.Name, nil }
conditional_block
run_hook.go
/tools/clientcmd" "kmodules.xyz/client-go/meta" appcatalog_cs "kmodules.xyz/custom-resources/client/clientset/versioned" ) type hookOptions struct { masterURL string kubeConfigPath string namespace string hookType string backupSessionName string restoreSessionName string targe...
} } // no pod found in ready addresses. now try in not ready addresses. for _, notReadyAddrs := range subSets.NotReadyAddresses { if notReadyAddrs.TargetRef != nil && notReadyAddrs.TargetRef.Kind == apis.KindPod { return notReadyAddrs.TargetRef.Name, nil } } } } return "", fmt.Errorf("n...
{ // get the AppBinding appbinding, err := opt.appClient.AppcatalogV1alpha1().AppBindings(opt.namespace).Get(context.TODO(), appbindingName, metav1.GetOptions{}) if err != nil { return "", err } // AppBinding should have a Service in ClientConfig field. This service selects the app pod. We will execute the hook...
identifier_body
run_hook.go
/tools/clientcmd" "kmodules.xyz/client-go/meta" appcatalog_cs "kmodules.xyz/custom-resources/client/clientset/versioned" ) type hookOptions struct { masterURL string kubeConfigPath string namespace string hookType string backupSessionName string restoreSessionName string targe...
if err != nil { // For preBackup or preRestore hook failure, we will fail the container so that the task does to proceed to next step. // We will also update the BackupSession/RestoreSession status as the update-status Function will not execute. if opt.hookType == apis.PreBackupHook || opt.hookType == ap...
random_line_split
console.rs
and remove all containers matching PATTERN\n\ update: Run update with provided ressources\n\ versions: Version list of installed applications"; pub async fn init(tx: &EventTx) -> Result<()> { let rx = serve().await?; let tx = tx.clone(); // Spawn a task that handles lines received on the debug por...
.unwrap_or_else(|| "No".to_string()), if app.container().is_resource_container() { "resource" } else { "app" } .to_owned(), ...
{ to_table( vec![vec![ "Name".to_string(), "Version".to_string(), "Running".to_string(), "Type".to_string(), ]] .iter() .cloned() .chain( state .applications() .sorted_by_key(|app| app...
identifier_body
console.rs
and remove all containers matching PATTERN\n\ update: Run update with provided ressources\n\ versions: Version list of installed applications"; pub async fn
(tx: &EventTx) -> Result<()> { let rx = serve().await?; let tx = tx.clone(); // Spawn a task that handles lines received on the debug port. task::spawn(async move { while let Ok((line, tx_reply)) = rx.recv().await { tx.send(Event::Console(line, tx_reply)).await; } }); ...
init
identifier_name
console.rs
and remove all containers matching PATTERN\n\ update: Run update with provided ressources\n\ versions: Version list of installed applications"; pub async fn init(tx: &EventTx) -> Result<()> { let rx = serve().await?; let tx = tx.clone(); // Spawn a task that handles lines received on the debug por...
/// Start applications. If `args` is empty *all* known applications that /// are not in a running state are started. If a argument is supplied it /// is used to construct a Regex and all container (names) matching that /// Regex are attempted to be started. async fn start(state: &mut State, args: &[&str]) -> Result<Str...
}
random_line_split
basic.rs
U> Point2<T, U> { fn mixup<V, W>(self, other: Point2<V, W>) -> Point2<T, W> { Point2 { x: self.x, y: other.y, } } } // traits trait Summarizable { fn summarize_author(&self) -> String; fn summarize(&self) -> String { format!("(Read more from {}...)", s...
None }
random_line_split
basic.rs
V6(String), } fn route(ip_kind: IpAddrKind) {} fn code_holder_4() { let four = IpAddrKind::V4; // are of same type let six = IpAddrKind::V6; route(IpAddrKind::V4); route(IpAddrKind::V6); let home = IpAddr::V4(127, 0, 0, 1); let loopback = IpAddr::V6(String::from("::1")); } enum Message {...
{ Int(i32), Float(f64), Text(String), } let row = vec![ SpreadsheetCell::Int(3), SpreadsheetCell::Text(String::from("blue")), SpreadsheetCell::Float(10.12), ]; } // strings // str is implemented in the core language and String is in the standard library f...
SpreadsheetCell
identifier_name
vechain.go
.Sprintf("%x", sha256.Sum256([]byte(strings.ToLower(str)))) return } //区块链浏览器浏览地址 func BlockChainExploreLink(transactionId string, config *VechainConfig) string { return fmt.Sprintf(config.ExploreLink, transactionId) } //=========================Token====================== //返回Token结构 type Token struct { Token st...
respData := new(ResponseData) respData.Data = new(Token) err = json.Unmarshal(body, respData) if respData.Code != 1 { err = fmt.Errorf("responseCode:%d error,message:%s\n", respData.Code, respData.Message) log.Error(err.Error()) goto Retry } token = respData.Data.(*Token) return } //======================...
goto Retry } log.Debug("toke response :%s \n", body)
random_line_split
vechain.go
> 100 { time.Sleep(1 * time.Minute) } else if retryTimes > 1000 { time.Sleep(1 * time.Hour) } request, err := http.NewRequest("POST", requestUrl, data) if err != nil { log.Error("%s", err.Error()) goto Retry } defer request.Body.Close() request.Header.Set("Content-Type", "application/json") client :=...
or(err.Error())
identifier_name
vechain.go
.Sprintf("%x", sha256.Sum256([]byte(strings.ToLower(str)))) return } //区块链浏览器浏览地址 func BlockChainExploreLink(transactionId string, config *VechainConfig) string { return fmt.Sprintf(config.ExploreLink, transactionId) } //=========================Token====================== //返回Token结构 type Token struct { Token st...
!= nil { log.Error(err.Error()) goto Retry } req.Header.Add("Content-Type", "application/json;charset=utf-8") req.Header.Add("language", "zh_hans") req.Header.Add("x-api-token", token) client := http.DefaultClient resp, err := client.Do(req) if err != nil { log.Error(err.Error()) goto Retry } defer ...
bytes.NewBuffer(data)) if err
conditional_block
vechain.go
.Sprintf("%x", sha256.Sum256([]byte(strings.ToLower(str)))) return } //区块链浏览器浏览地址 func BlockChainExploreLink(transactionId string, config *VechainConfig) string { return fmt.Sprintf(config.ExploreLink, tr
============ //返回Token结构 type Token struct { Token string `json:"token"` Expire int64 `json:"expire"` } var lock int32 = 0 var refreshError = fmt.Errorf("token refreshing") func GetToken(config *VechainConfig) (token *Token, err error) { if atomic.LoadInt32(&lock) == 1 { err = refreshError return } atomic....
ansactionId) } //=========================Token==========
identifier_body
pyvideo_scrape.py
) raise ValueError("{} can't be null".format(mandatory_field)) self.issue = event_data['issue'] if isinstance(event_data['youtube_list'], str): self.youtube_lists = [event_data['youtube_list']] elif isinstance(event_data['youtube_list'], list): self.youtu...
if youtube_video_data: # Valid video self.youtube_videos.append( Video.from_youtube( video_data=youtube_video_data, event=self)) else: logger.warning('Null youtube video') def load_video_data(self): """Load...
youtube_list = sum((scrape_url(url) for url in self.youtube_lists), []) for youtube_video_data in youtube_list:
random_line_split
pyvideo_scrape.py
) raise ValueError("{} can't be null".format(mandatory_field)) self.issue = event_data['issue'] if isinstance(event_data['youtube_list'], str): self.youtube_lists = [event_data['youtube_list']] elif isinstance(event_data['youtube_list'], list): self.youtu...
def save_video_data(self): """Save all event videos in PyVideo format""" if self.overwrite: # Erase old event videos for path in self.video_dir.glob('*.json'): path.unlink() for video in self.videos: video.save() def create_commit(se...
self.videos = self.youtube_videos
conditional_block
pyvideo_scrape.py
'] def create_branch(self): """Create a new branch in pyvideo repository to add a new event""" os.chdir(str(self.repository_path)) sh.git.checkout('master') sh.git.checkout('-b', self.branch) logger.debug('Branch {} created', self.branch) def create_dirs(self): ...
""Create video copy overwriting fields """ merged_video = Video(self.event) merged_video.filename = self.filename for field in self.metadata: if field in set(fields): merged_video.metadata[field] = new_video.metadata.get(field) else: merged...
identifier_body
pyvideo_scrape.py
) raise ValueError("{} can't be null".format(mandatory_field)) self.issue = event_data['issue'] if isinstance(event_data['youtube_list'], str): self.youtube_lists = [event_data['youtube_list']] elif isinstance(event_data['youtube_list'], list): self.youtu...
(self, upload_date_str): """Calculate record date from youtube field and event dates""" upload_date = datetime.date( int(upload_date_str[0:4]), int(upload_date_str[4:6]), int(upload_date_str[6:8])) if self.event.know_date: if not (self.event.date_begin <= upl...
__calculate_date_recorded
identifier_name
verbose.py
end':[]} for start_end in ('start', 'end'): for tmptime in lout.iter(start_end + '-valid-time'): moment = parse_noaa_time_string(tmptime.text) layouts[name][start_end].append(moment) return layouts def combine_days(action, pdata, debug=False): """ Perfor...
def find_max_temp(pdata, day): """ find min temp for the night of <prev_day> to <next_day> """ for ival in range(len(pdata['values'])): start = pdata['time-layout']['start'][ival] end = pdata['time-layout']['end'][ival] if start.day == day and end.day == day: return int(pda...
""" find min temp for the night of <prev_day> to <next_day> """ for ival in range(len(pdata['values'])): start = pdata['time-layout']['start'][ival] end = pdata['time-layout']['end'][ival] if start.day == prev_day and end.day == next_day: return int(pdata['values'][ival]) # r...
identifier_body
verbose.py
end':[]} for start_end in ('start', 'end'): for tmptime in lout.iter(start_end + '-valid-time'): moment = parse_noaa_time_string(tmptime.text) layouts[name][start_end].append(moment) return layouts def combine_days(action, pdata, debug=False): """ Perfor...
(pdata, day): """ find min temp for the night of <prev_day> to <next_day> """ for ival in range(len(pdata['values'])): start = pdata['time-layout']['start'][ival] end = pdata['time-layout']['end'][ival] if start.day == day and end.day == day: return int(pdata['values'][ival])...
find_max_temp
identifier_name
verbose.py
end':[]} for start_end in ('start', 'end'): for tmptime in lout.iter(start_end + '-valid-time'): moment = parse_noaa_time_string(tmptime.text) layouts[name][start_end].append(moment) return layouts def combine_days(action, pdata, debug=False): """ Perfor...
if debug: print ' final:' for key in sorted(dailyvals.keys()): print ' ', key, dailyvals[key] return dailyvals def parse_data(root, time_layouts, debug=False): pars = root.find('data').find('parameters') data = {} for vardata in pars: # first figure out the...
dailyvals[int(starts[ival].day)] = values[ival] if action == 'mean': # if debug: # print 'total', get_time_delta_in_hours(starts[ival], ends[ival]) dailyvals[int(starts[ival].day)] /= weight_sum[ival] #get_time_delta_in_hours(starts[ival], ends[ival])
conditional_block
verbose.py
'sum' or action == 'mean' starts, ends, values, weight_sum = [], [], [], [] def get_time_delta_in_hours(start, end): """ NOTE assumes no overflows or wraps or nothing """ dhour = end.hour - start.hour dmin = end.minute - start.minute dsec = end.second - start.second dt...
if day.day in percent_precip: row += ' %.0f<font size=1>%%</font>' % percent_precip[day.day]
random_line_split
ethereum-block.ts
this block. This * can be calculated from the previous block’s difficulty level and the * timestamp. */ difficulty: bigint; /** * A scalar value equal to the number of ancestor blocks. The genesis block * has a number of zero. */ blockNumber: bigint; /** * A scalar value equal to the curre...
gth > 32) { throw new Error(`s > 32 bytes!`); } const signature = Buffer.alloc(64, 0); r.copy(signature, 32 - r.length); s.copy(signature, 64 - s.length); const chainV = options.chainId * 2 + 35; const verifySignature = options.eip155 ? v[0] === chainV || v[0] === chainV + 1 : false; const rec...
new Error(`r > 32 bytes!`); } if (s.len
conditional_block
ethereum-block.ts
[HEADER_UNCLE_HASH] as Buffer), beneficiary: toBigIntBE(header[HEADER_BENEFICIARY] as Buffer), stateRoot: toBigIntBE(header[HEADER_STATE_ROOT] as Buffer), transactionsRoot: toBigIntBE(header[HEADER_TRANSACTIONS_ROOT] as Buffer), receiptsRoot: toBigIntBE(header[HEADER_RECEIPTS_ROOT] as Buffer), logsB...
header
identifier_name