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
index.js
Updated(config) { let resetConnection = false if (this.config.host != config.host) { resetConnection = true } this.config = config this.updateActions() this.updateFeedbacks() this.updatePresets() this.updateVariables() if (resetConnection === true || this.socket === undefined) { this.initTCP...
} else if (data.startsWith('backlight_compensation')) { data = data.replace('backlight_compensation', '').trim() this.state.backlight_compensation = data this.checkFeedbacks('backlight_compensation') } else if (data.startsWith('blue_gain')) { data = data.replace('blue_gain', '').trim() this.state.blu...
random_line_split
index.js
Updated(config) { let resetConnection = false if (this.config.host != config.host) { resetConnection = true } this.config = config this.updateActions() this.updateFeedbacks() this.updatePresets() this.updateVariables() if (resetConnection === true || this.socket === undefined) { this.initTCP...
() { this.receiveBuffer = '' if (this.socket !== undefined) { this.socket.destroy() delete this.socket } if (this.pollTimer !== undefined) { clearInterval(this.pollTimer) } if (this.config.port === undefined) { this.config.port = 23 } if (this.config.host) { this.socket = new TCPHelpe...
initTCP
identifier_name
index.js
/** * Process an updated configuration array. * * @param {Object} config - the new configuration * @access public * @since 1.0.0 */ async configUpdated(config) { let resetConnection = false if (this.config.host != config.host) { resetConnection = true } this.config = config this.updateAc...
{ super(internal) this.updateActions = updateActions.bind(this) this.updateFeedbacks = updateFeedbacks.bind(this) this.updatePresets = updatePresets.bind(this) this.updateVariables = updateVariables.bind(this) }
identifier_body
court.py
auschen kommt von __sensor_y()) :return float, skalierter Y-Anteil vom Ortsvektor """ return self.__sensor_y() / (self.y_max / 2.0) - 1.0 def scaled_sensor_bat(self, player): """ Gibt die Position des Schlägers von Spieler[Player] skaliert von -1 bis +1 mit Rausche...
er Ball außerhalb des Spielfelds # war, z.B. für out(player) # Ball abprallen lassen, falls: # -> Das infinite true ist, also das Spiel endlos dauern soll ohn
conditional_block
court.py
0] # Der "Einschlagspunkt" des Balles auf der (Toraus-)Linie, wird erst nach einem Aufprall # mit konkreten Werten belegt und dann zur Fehlerberechnung genutzt (supervised learning). self.poi = [None, None] # Initiale Schlägerpositionen der Spieler auf ihren Linien. # [Schlänge...
des Ortsvektors des Balles skaliert von -1 bis +1 mit Rauschen zurück (Rauschen kommt von __sensor_y()) :return float, skalierter Y-Anteil vom Ortsvektor """ return self.__sensor_y() / (self.y_max / 2.0) - 1.0 def scaled_sensor_bat(self, player): """ Gibt die Posit...
1 bis +1 mit Rauschen zurück (Rauschen kommt von __sensor_x()) :return float, skalierter X-Anteil vom Ortsvektor """ return self.__sensor_x() / (self.x_max / 2.0) - 1.0 def scaled_sensor_y(self): """ Gibt den Y-Anteil
identifier_body
court.py
0] # Der "Einschlagspunkt" des Balles auf der (Toraus-)Linie, wird erst nach einem Aufprall # mit konkreten Werten belegt und dann zur Fehlerberechnung genutzt (supervised learning). self.poi = [None, None] # Initiale Schlägerpositionen der Spieler auf ihren Linien. # [Schlänge...
r Ball bewegt, die Überschreitung einer der Torauslinien oder die Kollision mit einem Schläger auf False initialisiert, außerdem die Ballposition zurückgesetzt, falls die Spieler den Ball zu oft hin und her gespielt haben ohne Tor (Endlosspiel verhindern). Ebenso wird überprüft, ob der B...
d de
identifier_name
court.py
0] # Der "Einschlagspunkt" des Balles auf der (Toraus-)Linie, wird erst nach einem Aufprall # mit konkreten Werten belegt und dann zur Fehlerberechnung genutzt (supervised learning). self.poi = [None, None] # Initiale Schlägerpositionen der Spieler auf ihren Linien. # [Schläng...
# Um ein solches "Endlosspiel" zu verhindern, wird der Ball nach 10 Treffern resettet, # das Spielfeld also zurückgesetzt mit einer initialen Ballposition auf der Spielfeldmitte und # neuem, zufallskalkuliertem Winkel. self.bouncecount = 0 # Startvorbereitung # Initialis...
# Die KNNs sollen unterschiedliche Winkel lernen (der Winkel wird immer zufallsinitialisiert), # bei ausreichender Lerndauer bzw. stark minimiertem Fehler jedoch sind die KNNs manchmal auf # einigen Winkeln derart talentiert, dass der Ball nie mehr über die Torlinie gehen würde.
random_line_split
accounts.rs
use nimiq_account::{ Account, Accounts, BlockLogger, BlockState, RevertInfo, TransactionOperationReceipt, }; use nimiq_block::{Block, BlockError, SkipBlockInfo}; use nimiq_blockchain_interface::PushError; use nimiq_database::{traits::Database, TransactionProxy}; use nimiq_keys::Address; use nimiq_primitives::{ ...
block.block_number(), &body.fork_proofs, skip_block_info, Some(txn), ); // Get the revert info for this block. let revert_info = self .chain_store .get_revert_info(block.block_number(), Some(txn)) .expect("Faile...
random_line_split
accounts.rs
use nimiq_account::{ Account, Accounts, BlockLogger, BlockState, RevertInfo, TransactionOperationReceipt, }; use nimiq_block::{Block, BlockError, SkipBlockInfo}; use nimiq_blockchain_interface::PushError; use nimiq_database::{traits::Database, TransactionProxy}; use nimiq_keys::Address; use nimiq_primitives::{ ...
// Macro blocks are final and receipts for the previous batch are no longer necessary // as rebranching across this block is not possible. self.chain_store.clear_revert_infos(txn.raw()); // Store the transactions and the inherents into the History tree. ...
{ // Get the accounts from the state. let accounts = &state.accounts; let block_state = BlockState::new(block.block_number(), block.timestamp()); // Check the type of the block. match block { Block::Macro(ref macro_block) => { // Initialize a vector t...
identifier_body
accounts.rs
use nimiq_account::{ Account, Accounts, BlockLogger, BlockState, RevertInfo, TransactionOperationReceipt, }; use nimiq_block::{Block, BlockError, SkipBlockInfo}; use nimiq_blockchain_interface::PushError; use nimiq_database::{traits::Database, TransactionProxy}; use nimiq_keys::Address; use nimiq_primitives::{ ...
{ /// The end of the chunk. The end key is exclusive. /// When set to None it means that it is the last trie chunk. pub end_key: Option<KeyNibbles>, /// The set of accounts retrieved. pub accounts: Vec<(Address, Account)>, } /// Implements methods to handle the accounts. impl Blockchain { /// ...
AccountsChunk
identifier_name
gen.go
px.svg with an explicit fill="#fff". {"av", "ic_play_circle_filled_white_48px.svg"}: true, } func genFile(fqSVGDirName, dirName, baseName, fileName string, size float32) error { fqFileName := filepath.Join(fqSVGDirName, fileName) svgData, err := os.ReadFile(fqFileName) if err != nil { return err } varName := ...
{ f, err := strconv.ParseFloat(string(s), 32) if err != nil { return 0, fmt.Errorf("could not parse %q as a float32: %v", s, err) } return float32(f), err }
identifier_body
gen.go
} func main() { flag.Parse() out.WriteString("// generated by go run gen.go; DO NOT EDIT\n\npackage icons\n\n") f, err := os.Open(*mdicons) if err != nil { log.Fatalf("%v\n\nDid you override the -mdicons flag in icons.go?\n\n", err) } defer f.Close() infos, err := f.Readdir(-1) if err != nil { log.Fatal(...
fInfo, err := os.Stat(filepath.Join(fqPNGDirName, fmt.Sprintf("ic_%s_black_%ddp.png", baseName, size))) if err != nil { continue } return int(fInfo.Size()) } failures = append(failures, fmt.Sprintf("no PNG found for %s/1x_web/ic_%s_black_{48,24,18}dp.png", dirName, baseName)) return 0 } type SVG str...
random_line_split
gen.go
func
() { flag.Parse() out.WriteString("// generated by go run gen.go; DO NOT EDIT\n\npackage icons\n\n") f, err := os.Open(*mdicons) if err != nil { log.Fatalf("%v\n\nDid you override the -mdicons flag in icons.go?\n\n", err) } defer f.Close() infos, err := f.Readdir(-1) if err != nil { log.Fatal(err) } nam...
main
identifier_name
gen.go
func main() { flag.Parse() out.WriteString("// generated by go run gen.go; DO NOT EDIT\n\npackage icons\n\n") f, err := os.Open(*mdicons) if err != nil
defer f.Close() infos, err := f.Readdir(-1) if err != nil { log.Fatal(err) } names := []string{} for _, info := range infos { if !info.IsDir() { continue } name := info.Name() if name[0] == '.' { continue } names = append(names, name) } sort.Strings(names) for _, name := range names { ge...
{ log.Fatalf("%v\n\nDid you override the -mdicons flag in icons.go?\n\n", err) }
conditional_block
envconfig.go
, ErrInvalidSpecification } s = s.Elem() if s.Kind() != reflect.Struct { return nil, ErrInvalidSpecification } typeOfSpec := s.Type() // over allocate an info array, we will extend if needed later infos := make([]varInfo, 0, s.NumField()) for i := 0; i < s.NumField(); i++ { f := s.Field(i) ftype := typeO...
else { var err error // let's find out how many are defined by the env vars, and gather info of each one of them if l, err = sliceLen(info.Key, env); err != nil { return nil, err } prefixFormat = processPrefix(info.Key) // if no keys, check the alternative keys, unless we're inside of a sl...
{ // it's just for usage so we don't know how many of them can be out there // so we'll print one info with a generic [N] index l = 1 prefixFormat = usagePrefix{info.Key, "[N]"} }
conditional_block
envconfig.go
) } } f.Set(reflect.MakeSlice(f.Type(), l, l)) for i := 0; i < l; i++ { var structPtrValue reflect.Value if arePointers { f.Index(i).Set(reflect.New(f.Type().Elem().Elem())) structPtrValue = f.Index(i) } else { structPtrValue = f.Index(i).Addr() } embeddedInfos, err :=...
isSliceOfStructs
identifier_name
envconfig.go
reflect.Ptr { if f.IsNil() { if f.Type().Elem().Kind() != reflect.Struct { // nil pointer to a non-struct: leave it alone break } // nil pointer to struct: create a zero instance f.Set(reflect.New(f.Type().Elem())) } f = f.Elem() } // Capture information about the config variabl...
sl = reflect.ValueOf([]byte(value)) } else if len(strings.TrimSpace(value)) != 0 { vals := strings.Split(value, ",") sl = reflect.MakeSlice(typ, len(vals), len(vals)) for i, val := range vals {
random_line_split
envconfig.go
func gatherInfoForProcessing(prefix string, spec interface{}, env map[string]string) ([]varInfo, error) { return gatherInfo(prefix, spec, env, false, false) } // gatherInfo gathers information about the specified struct, use gatherInfoForUsage or gatherInfoForProcessing for calling it func gatherInfo(prefix string,...
{ return gatherInfo(prefix, spec, map[string]string{}, false, true) }
identifier_body
scan_nosmooth.py
if self.Asimov: norm_file = work_dir + '/DataFiles/Misc/P8UCVA_norm.npy' f_global.use_template_normalization_file(norm_file,key_suffix='-0') Asimov_data = np.zeros((40,hp.nside2npix(self.nside))) for key in f_global.template_dict.keys(): Asimov_data += n...
n.add_poiss_model('bub', '$A_\mathrm{bub}$', [0,10], False) # # Add PS at halo location # ps_halo_map = np.zeros(hp.nside2npix(self.nside)) # ps_halo_idx = hp.ang2pix(self.nside, np.pi/2. - b*np.pi/180., l*np.pi/180.) # ell and b are in rad # ps_halo_map[...
n.add_poiss_model(self.diff, '$A_\mathrm{dif}$', [0,10], False) n.add_poiss_model('iso', '$A_\mathrm{iso}$', [0,20], False) if (np.sum(bub*np.logical_not(analysis_mask)) != 0):
random_line_split
scan_nosmooth.py
self.floatDM = floatDM # Whether to float the DM in the initial scan self.verbose = verbose # Whether to print tqdm and Minuit output self.noJprof = noJprof # Whether to not do a profile over the J uncertainty self.save_dir = save_dir # Directory to save output files self.load_di...
def __init__(self, perform_scan=0, perform_postprocessing=0, save_dir="", load_dir=None,imc=0, iobj=0, emin=0, emax=39, channel='b', nside=128, eventclass=5, eventtype=0, diff='p7', catalog_file='DarkSky_ALL_200,200,200_v3.csv', Burkert=0, use_boost=0, boost=1, float_ps_together=1, Asimov=0, floatDM=1, verbose=0, noJpr...
identifier_body
scan_nosmooth.py
(self, perform_scan=0, perform_postprocessing=0, save_dir="", load_dir=None,imc=0, iobj=0, emin=0, emax=39, channel='b', nside=128, eventclass=5, eventtype=0, diff='p7', catalog_file='DarkSky_ALL_200,200,200_v3.csv', Burkert=0, use_boost=0, boost=1, float_ps_together=1, Asimov=0, floatDM=1, verbose=0, noJprof=0, mc_dm=...
__init__
identifier_name
scan_nosmooth.py
_poiss_model('DM','DM',False,fixed=True,fixed_norm=1.0) new_n2.configure_for_scan() max_LL = new_n2.ll([]) LL_inten_ary[iebin, iA] = max_LL inten_ary[iebin, iA] = DM_intensity_base*A np.savez(self.save_dir + 'LL_inten_o'+str(self....
rep_angext = np.array([0.02785567,0.12069876,0.21354185,0.30638494,0.39922802,0.49207111,0.5849142,0.67775728,0.77060037,0.86344346,0.95628654,1.04912963,1.14197272,1.2348158,1.32765889,1.42050198,1.51334507,1.60618815,1.69903124,1.79187433]) obj_angext = 2*self.catalog[u'rs'].values[self.iobj] / \ ...
conditional_block
exploratory_analysis.py
def plotHist(column, title, x_label, y_label): # plots a histogram. Note: update bin width as appropriate binwidth = [x for x in range(0,800000, 2000)] ex = plt.hist(column, bins=binwidth) plt.title(title) plt.xlabel(x_label) plt.ylabel(y_label) return plt.show() def plotHistTwo(colA, col...
return 0
identifier_body
exploratory_analysis.py
= train_test_split(X, y, test_size = 0.10) # # # # # # # # train model (could change kernel here) # # # svm = SVC(C=1, gamma=0.3, kernel='rbf') # # # svm.fit(X_train, y_train) # # # # # # # # # # recursive feature selection using cross validation # # # # # rfecv = RFECV(estimator=svm, step=...
main()
conditional_block
exploratory_analysis.py
(column, title, x_label, y_label): # plots a histogram. Note: update bin width as appropriate binwidth = [x for x in range(0,800000, 2000)] ex = plt.hist(column, bins=binwidth) plt.title(title) plt.xlabel(x_label) plt.ylabel(y_label) return plt.show() def plotHistTwo(colA, colB, title="", x...
plotHist
identifier_name
exploratory_analysis.py
B], bins=binwidth, alpha=0.5, label=["Males", "Females"]) plt.legend(loc='upper right', prop={'size': 13}) plt.title(title) plt.xlabel(x_label) plt.ylabel(y_label) # plt.savefig("retweet_count.png") return plt.show() def plotBar(colA, colB, title="", x_label="", y_label="Frequency"): return...
# # svm.gamma = gamma # # this_scores = cross_val_score(svm, X, y, cv=5) # # scores.append(np.mean(this_scores)) # # scores=np.array(scores) # # scores=scores.reshape(C_s.shape) # # fig2, ax2 = plt.subplots(figsize=(12,8)) # # c=ax2.contourf(C_s,gamma_s,scores) # # ax2.set_xl...
random_line_split
Program.ts
sFile; } else if (fileExtension === '.xml') { let xmlFile = new XmlFile(pathAbsolute, pkgPath, this); //add the file to the program this.files[pathAbsolute] = xmlFile; await xmlFile.parse(await getFileContents()); file = xmlFile; //create ...
{ let result = file.transpile(); let filePathObj = fileEntries.find(x => util.standardizePath(x.src) === util.standardizePath(file.pathAbsolute)); if (!filePathObj) { throw new Error(`Cannot find fileMap record in fileMaps for '${file.pathAbsolute}'`);...
conditional_block
Program.ts
Object.keys(this.scopes).find(x => x.toLowerCase() === scopeName.toLowerCase()); return this.scopes[key]; } /** * Load a file into the program. If that file already exists, it is replaced. * If file contents are provided, those are used, Otherwise, the file is loaded from the file system ...
random_line_split
Program.ts
*/ public async getFileContents(pathAbsolute: string) { pathAbsolute = util.standardizePath(pathAbsolute); let reversedResolvers = [...this.fileResolvers].reverse(); for (let fileResolver of reversedResolvers) { let result = await fileResolver(pathAbsolute); if (type...
(pathAbsolute: string) { pathAbsolute = util.standardizePath(pathAbsolute); for (let filePath in this.files) { if (filePath.toLowerCase() === pathAbsolute.toLowerCase()) { return this.files[filePath]; } } } /** * Get a file with the specified...
getFileByPathAbsolute
identifier_name
Program.ts
that are already loaded will be replaced by the latest * contents from the file system. * @param filePaths */ public async addOrReplaceFiles(fileObjects: Array<StandardizedFileEntry>) { return Promise.all( fileObjects.map(async (fileObject) => this.addOrReplaceFile(fileObject)) ...
{ let file = this.getFile(pathAbsolute); if (!file) { return []; } //wait for the file to finish loading await file.isReady(); //find the scopes for this file let scopes = this.getScopesForFile(file); //if there are no scopes, include the pl...
identifier_body
si5324.py
(self, register, startbit, length): self.register = register self.startbit = startbit self.length = length def get_endbit(self): return (self.startbit - (self.length - 1)) class Alarms: """ Alarms Class: Holds a collection of alarms states for the class, including both...
__init__
identifier_name
si5324.py
_Clock_Active = _Field(128,1,2) # CKx_ACTV_REG for clocks 1 and 2 _FIELD_LOS1_INT = _Field(129,1,1) # LOS1_INT Loss of Signal alarm for CLKIN_1 _FIELD_LOS2_INT = _Field(129,2,1) # LOS2_INT Loss of Signal alarm for CLKIN_2 _FIELD_LOSX_INT = _Field(129,0,1) # LOSX_INT Loss...
raise I2CException( "Write of byte to register {} failed.".format(register)) # ICAL-sensitive registers will have been modified during this process self.iCAL_required = True self.calibrate() def export_register_map(self, mapfi...
logger.debug("Verifying value written ({:b}) against re-read: {:b}".format( value,verify_value)) if verify_value != value:
random_line_split
si5324.py
__init__(self, address=0x68, **kwargs): """ Initialise the SI5324 device. :param address: The address of the SI5324 is determined by pins A[2:0] as follows: 0b1101[A2][A1][A0]. """ I2CDevice.__init__(self, address, **kwargs) logger.info("Created ...
time.sleep(0.100) logger.debug("iCAL waiting...") # Check for LOL timeout (not necessarily fatal, since the input # could just be inactive when selected. However, iCAL should be # performed after the input is provided, or the output will be # unstable). ...
conditional_block
si5324.py
_Clock_Active = _Field(128,1,2) # CKx_ACTV_REG for clocks 1 and 2 _FIELD_LOS1_INT = _Field(129,1,1) # LOS1_INT Loss of Signal alarm for CLKIN_1 _FIELD_LOS2_INT = _Field(129,2,1) # LOS2_INT Loss of Signal alarm for CLKIN_2 _FIELD_LOSX_INT = _Field(129,0,1) # LOSX_INT Loss...
# Write register value logger.info("Writing register {} with value {:02X}".format(register,value)) self.write8(register, value) if verify: verify_value = self.readU8(register) logger.debug("...
""" Write configuration from a register map generated with DSPLLsim. Since the map is register rather than value-based, there is no need to make use of the _Field access functions. :param mapfile_location: location of register map file to be read :param verify: Boolean. If true,...
identifier_body
mysql_insert_query_test.go
ord) // true, 检测记录的主键是否零值,不插数据,也不会与db交互. assert.True(t, ok) db.Create(&record) // insert, db生成的id将会写入record assert.NotEqual(t, record.ID, 0) ok = db.NewRecord(record) // false, because record.id already exists in db. assert.False(t, ok) record.ID = 0 record.Age = sql.NullInt64{Valid: true, Int64: 0} record.E...
db.NewRecord(rec
conditional_block
mysql_insert_query_test.go
u_name=x ORDER BY id LIMIT 1; assert.NotEqual(t, user.ID, 0) u := new(User) // Get one record, no specified order (只使用主键查询,其他字段不会使用) // SELECT * FROM `admin_users` WHERE `admin_users`.`deleted_at` IS NULL AND `admin_users`.`id` = 1 LIMIT 1 db.Take(u, "u_name=?", "x") log.Printf("111 %+v", u) // Get last reco...
// SELECT * FROM users WHERE name = 'x'; assert.True(t, len(users) > 1) // IN db.Where("u_name IN (?)", []string{"x", "jinzhu 2"}).Find(&users) // SELECT * FROM users WHERE name in ('x','jinzhu 2'); // LIKE db.Where("u_name LIKE ?", "%x%").Find(&users) // SELECT * FROM users WHERE name LIKE '%jin%'; // AND ...
t all records db.Find(&users) assert.True(t, len(users) > 1) // Get record with primary key (后面参数只会传递给整型主键) db.First(&user, 10) // where可以自定义字符串形式的条件,使用问号占位参数 // 还可以传入带值的struct,其中的值作为条件查询 // 还可以传入map类型,其中的k-v作为条件查询 // 还可以传入slice类型,不过元素只能是整型,作为主键字段参数,执行IN查询(如果主键不是整型,应该会报错) var user1 User // where db.Where(...
identifier_body
mysql_insert_query_test.go
CommonQueryTest(t, db) //QueryNotTest(t, db) //QueryOrTest(t, db) //MoreSimpleQueryTest(t, db) //FirstOrInitQueryTest(t, db) //FirstOrCreateQueryTest(t, db) //SubQueryTest(t, db) //SelectTest(t, db) //LimitTest(t, db) //OffsetTest(t, db) //CountTest(t, db) //JoinTest(t, db) //ScanTest(t, db) UpdateAllFie...
InsertTest(t, db)
random_line_split
mysql_insert_query_test.go
=x ORDER BY id LIMIT 1; assert.NotEqual(t, user.ID, 0) u := new(User) // Get one record, no specified order (只使用主键查询,其他字段不会使用) // SELECT * FROM `admin_users` WHERE `admin_users`.`deleted_at` IS NULL AND `admin_users`.`id` = 1 LIMIT 1 db.Take(u, "u_name=?", "x") log.Printf("111 %+v", u) // Get last record, ord...
&& user.Name == "n
identifier_name
ioWkr.go
// just use fixed cluster number 1, round robin packets if err = ring.SetCluster(1, pfring.ClusterType(pfring.ClusterRoundRobin)); err != nil { log.Errorf("pfring SetCluster error:", err) doneChan <- err return } if err = ring.SetDirection(pfring.ReceiveOnly); err != nil { lo...
{ rxStartDone := make(chan bool) for rxwkr := 0; rxwkr < cfg.NumRXWorkers; rxwkr++ { func(i int) { cfg.Eg.Go(func() error { doneChan := make(chan error, 1) go func() { var profiler Profiler profiler.Init(cfg.Eg, cfg.Ctx, true, fmt.Sprintf("RX Worker %d", i)) cfg.PerfProfilers = append(cfg....
identifier_body
ioWkr.go
filers = append(cfg.PerfProfilers, &profiler) var ring *pfring.Ring var rawIn *inPacket var err error // 1<<24 is PF_RING_DISCARD_INJECTED_PKTS , if you transmit a packet via the ring, doesn't read it back if ring, err = pfring.NewRing(cfg.Iface, 4096, (1<<24)|pfring.FlagPromisc|pfring.FlagHWTi...
txTSworker[workerNum].Tock() } }(j) select { case <-txTSStartDone:
atomic.AddUint64(&txTSBytesReceived, uint64(pktSentLen))
random_line_split
ioWkr.go
ers = append(cfg.PerfProfilers, &profiler) var ring *pfring.Ring var rawIn *inPacket var err error // 1<<24 is PF_RING_DISCARD_INJECTED_PKTS , if you transmit a packet via the ring, doesn't read it back if ring, err = pfring.NewRing(cfg.Iface, 4096, (1<<24)|pfring.FlagPromisc|pfring.FlagHWTimes...
ifInfo, err := net.InterfaceByName(cfg.Iface) if err != nil { log.Errorf("Interface by name failed in start tx worker") doneChan <- err return } var haddr [8]byte copy(haddr[0:7], ifInfo.HardwareAddr[0:7]) addr := syscall.SockaddrLinklayer{ Protocol: syscall.ETH_P...
{ txTSworker[j].Init(cfg.Eg, cfg.Ctx, true, fmt.Sprintf("TX worker %d TSRead worker %d", i, j)) cfg.PerfProfilers = append(cfg.PerfProfilers, &txTSworker[j]) }
conditional_block
ioWkr.go
(cfg *ClientGenConfig) { rxStartDone := make(chan bool) for rxwkr := 0; rxwkr < cfg.NumRXWorkers; rxwkr++ { func(i int) { cfg.Eg.Go(func() error { doneChan := make(chan error, 1) go func() { var profiler Profiler profiler.Init(cfg.Eg, cfg.Ctx, true, fmt.Sprintf("RX Worker %d", i)) cfg.Perf...
startIOWorker
identifier_name
dcrd_test.go
hint cache: %v", err) } return hintCache } // setUpNotifier is a helper function to start a new notifier backed by a dcrd // driver. func
(t *testing.T, h *rpctest.Harness) *DcrdNotifier { hintCache := initHintCache(t) rpcConfig := h.RPCConfig() notifier, err := New(&rpcConfig, netParams, hintCache, hintCache) if err != nil { t.Fatalf("unable to create notifier: %v", err) } if err := notifier.Start(); err != nil { t.Fatalf("unable to start not...
setUpNotifier
identifier_name
dcrd_test.go
hint cache: %v", err) } return hintCache } // setUpNotifier is a helper function to start a new notifier backed by a dcrd // driver. func setUpNotifier(t *testing.T, h *rpctest.Harness) *DcrdNotifier { hintCache := initHintCache(t) rpcConfig := h.RPCConfig() notifier, err := New(&rpcConfig, netParams, hintCach...
_, err = harness.Node.SendRawTransaction(context.TODO(), spenderTx, true) if err != nil { t.Fatalf("unable to publish tx: %v", err)
{ t.Parallel() harness, err := testutils.NewSetupRPCTest( t, 5, netParams, nil, []string{"--txindex"}, true, 25, ) require.NoError(t, err) defer harness.TearDown() notifier := setUpNotifier(t, harness) defer notifier.Stop() // Create an output and subsequently spend it. outpoint, txout, privKey := chainnt...
identifier_body
dcrd_test.go
utils.NewSetupRPCTest( t, 5, netParams, nil, []string{"--txindex"}, true, 25, ) require.NoError(t, err) defer harness.TearDown() notifier := setUpNotifier(t, harness) defer notifier.Stop() // A transaction unknown to the node should not be found within the // txindex even if it is enabled, so we should not p...
{ testTx = tx break }
conditional_block
dcrd_test.go
create hint cache: %v", err) } return hintCache } // setUpNotifier is a helper function to start a new notifier backed by a dcrd // driver. func setUpNotifier(t *testing.T, h *rpctest.Harness) *DcrdNotifier { hintCache := initHintCache(t) rpcConfig := h.RPCConfig() notifier, err := New(&rpcConfig, netParams, h...
if err != nil { t.Fatalf("unable to retrieve historical conf details: %v", err) } // Since the backend node's txindex is enabled and the transaction has // confirmed, we should be able to retrieve it using the txindex. switch txStatus { case chainntnfs.TxFoundIndex: default: t.Fatal("should have found the t...
random_line_split
refcounteddb.rs
/// /// journal format: /// ```text /// [era, 0] => [ id, [insert_0, ...], [remove_0, ...] ] /// [era, 1] => [ id, [insert_0, ...], [remove_0, ...] ] /// [era, n] => [ ... ] /// ``` /// /// when we make a new commit, we journal the inserts and removes. /// for each `end_era` that we journaled that we are no passing by,...
(&self) -> HashMap<H256, i32> { self.forward.keys() } } #[cfg(test)] mod tests { use keccak_hash::keccak; use hash_db::{HashDB, EMPTY_PREFIX}; use super::*; use kvdb_memorydb; use crate::{JournalDB, inject_batch, commit_batch}; fn new_db() -> RefCountedDB { let backing = Arc::new(kvdb_memorydb::create(0));...
keys
identifier_name
refcounteddb.rs
/// /// journal format: /// ```text /// [era, 0] => [ id, [insert_0, ...], [remove_0, ...] ] /// [era, 1] => [ id, [insert_0, ...], [remove_0, ...] ] /// [era, n] => [ ... ] /// ``` /// /// when we make a new commit, we journal the inserts and removes. /// for each `end_era` that we journaled that we are no passing by,...
.expect("rlp read from db; qed"); trace!(target: "rcdb", "delete journal for time #{}.{}=>{}, (canon was {}): deleting {:?}", end_era, db_key.index, our_id, canon_id, to_remove); for i in &to_remove { self.forward.remove(i, EMPTY_PREFIX); } batch.delete(self.column, &last); db_key.index += 1; } ...
{ view.inserts() }
conditional_block
refcounteddb.rs
/// /// journal format: /// ```text /// [era, 0] => [ id, [insert_0, ...], [remove_0, ...] ] /// [era, 1] => [ id, [insert_0, ...], [remove_0, ...] ] /// [era, n] => [ ... ] /// ``` /// /// when we make a new commit, we journal the inserts and removes. /// for each `end_era` that we journaled that we are no passing by,...
fn mem_used(&self) -> usize { let mut ops = new_malloc_size_ops(); self.inserts.size_of(&mut ops) + self.removes.size_of(&mut ops) } fn is_empty(&self) -> bool { self.latest_era.is_none() } fn backing(&self) -> &Arc<dyn KeyValueDB> { &self.backing } fn latest_era(&self) -> Option<u64> { self.latest_e...
}) }
random_line_split
refcounteddb.rs
/// /// journal format: /// ```text /// [era, 0] => [ id, [insert_0, ...], [remove_0, ...] ] /// [era, 1] => [ id, [insert_0, ...], [remove_0, ...] ] /// [era, n] => [ ... ] /// ``` /// /// when we make a new commit, we journal the inserts and removes. /// for each `end_era` that we journaled that we are no passing by,...
#[test] fn long_history() { // history is 3 let mut jdb = new_db(); let h = jdb.insert(EMPTY_PREFIX, b"foo"); commit_batch(&mut jdb, 0, &keccak(b"0"), None).unwrap(); assert!(jdb.contains(&h, EMPTY_PREFIX)); jdb.remove(&h, EMPTY_PREFIX); commit_batch(&mut jdb, 1, &keccak(b"1"), None).unwrap(); asser...
{ let backing = Arc::new(kvdb_memorydb::create(0)); RefCountedDB::new(backing, None) }
identifier_body
main.rs
_fourteen_output = fourteen(test_fourteen_input); println!("14) string '{}' is the isize {}", test_fourteen_input, test_fourteen_output); let test_fifteen_input = "MDCCLXXVI"; let test_fifteen_output = fifteen(test_fifteen_input); println!("15) roman number '{}' equals arabic number {}", test_fifteen_i...
{ let mut i = String::from(i); let is_negative = i.contains('-'); if is_negative { i = i.replace("-", ""); } let mut r = 0; for c in i.chars() { let d = c.to_digit(10).unwrap(); r = d + (r * 10); } let mut r = r as isize; if is_negative { r = r * -1; ...
identifier_body
main.rs
println!("9) the first unrepeated char in '{}' is '{}'", test_nine_input, test_nine_output); let test_ten_input = "best is Rust"; let test_ten_output = ten(test_ten_input); println!("10) reversed sentence '{}' is '{}'", test_ten_input, test_ten_output); let test_eleven_input1 = "this is a test str...
println!("8) '{}' has {} permutations {:?}", test_eight_input, test_eight_output.len(), test_eight_output); let test_nine_input = "uprasupradupra"; let test_nine_output = nine(test_nine_input);
random_line_split
main.rs
!("{}{}", c, r); }); r } fn seven(i1: &str, i2: &str) -> String { let mut r2 = String::from(i2); if i1.len() == 0 { return r2; } r2.push(i1.chars().last().unwrap()); let size_minus_one = i1.len() - 1; let r1 = &i1[..size_minus_one]; return seven(&r1, &r2); } fn eight(i: &st...
{ // we are not the same assume a center "pivot" character center r = r + 1; }
conditional_block
main.rs
test_ten_input, test_ten_output); let test_eleven_input1 = "this is a test string"; let test_eleven_input2 = "tist"; let test_eleven_output = eleven(test_eleven_input1, test_eleven_input2); println!("11) smallest substring '{}' inside of '{}' is '{}'", test_eleven_input2, test_eleven_input1, test_elev...
(input: &str) -> String { let mut r = String::new(); input.chars().for_each( | c | { r = format!("{}{}", c, r); }); r } fn seven(i1: &str, i2: &str) -> String { let mut r2 = String::from(i2); if i1.len() == 0 { return r2; } r2.push(i1.chars().last().unwrap()); let si...
six
identifier_name
sqlite.go
1.starts_at, a1.ends_at, a1.updated_at, a1.timeout FROM alerts AS a1 LEFT OUTER JOIN alerts AS a2 ON a1.fingerprint = a2.fingerprint AND a1.updated_at < a2.updated_at WHERE a2.fingerprint IS NULL; `) if err != nil { return nil, err } var alerts []*types.Alert for rows.Next() { var ( labels [...
defer dbmtx.Unlock()
random_line_split
sqlite.go
done, err) } // GetPending implements the Alerts interface. func (a *Alerts)
() provider.AlertIterator { var ( ch = make(chan *types.Alert, 200) done = make(chan struct{}) ) alerts, err := a.getPending() go func() { defer close(ch) for _, a := range alerts { select { case ch <- a: case <-done: return } } }() return provider.NewAlertIterator(ch, done, err) }...
GetPending
identifier_name
sqlite.go
<-done }() return provider.NewAlertIterator(ch, done, err) } // GetPending implements the Alerts interface. func (a *Alerts) GetPending() provider.AlertIterator { var ( ch = make(chan *types.Alert, 200) done = make(chan struct{}) ) alerts, err := a.getPending() go func() { defer close(ch) for _...
{ select { case ch <- a: case <-done: return } }
conditional_block
sqlite.go
) `) if err != nil { tx.Rollback() return err } defer delOverlap.Close() insert, err := tx.Prepare(` INSERT INTO alerts(fingerprint, labels, annotations, starts_at, ends_at, updated_at, timeout) VALUES ($1, $2, $3, $4, $5, $6, $7) `) if err != nil { tx.Rollback() return err } defer insert.Close()...
{ dbmtx.Lock() defer dbmtx.Unlock() mb, err := json.Marshal(sil.Silence.Matchers) if err != nil { return 0, err } tx, err := s.db.Begin() if err != nil { return 0, err } res, err := tx.Exec(` INSERT INTO silences(matchers, starts_at, ends_at, created_at, created_by, comment) VALUES ($1, $2, $3, $4, ...
identifier_body
main.py
_path)) scope = ['https://spreadsheets.google.com/feeds'] credentials = SignedJwtAssertionCredentials(json_key['client_email'], bytes(json_key['private_key'], "utf-8"), scope) self.gc = gspread.authorize(credentials) logging.info("Authorization with Google successful!") self.za...
else: for event in events: self.zapi.create_event(bucket_id, event) logging.debug("Done!".format(len(events))) def get_raw_table(self, sheetname): start = time.time() sheet = self.ll.worksheet(sheetname) raw_table = sheet.get_all_values() ...
self.zapi.create_events(bucket_id, events)
conditional_block
main.py
_path)) scope = ['https://spreadsheets.google.com/feeds'] credentials = SignedJwtAssertionCredentials(json_key['client_email'], bytes(json_key['private_key'], "utf-8"), scope) self.gc = gspread.authorize(credentials) logging.info("Authorization with Google successful!") self.za...
(category, label): ci = categories.index(category) i = labels.index(label, ci) cells = {} for j, d in enumerate(dates): cell = raw_table[j+2][i] if cell and cell != "#VALUE!": cells[d] = cell return cells ...
get_label_cells
identifier_name
main.py
class Lifelogger_to_Zenobase(): def __init__(self, google_oauth_json_path, zenobase_username, zenobase_password, streaks_bucket_name="Streaks", supplements_bucket_name="Supplements - New"): json_key = json.load(open(google_oauth_json_path)) scope = ['https://spreadsheets.google.c...
return list(map(lambda t: pyzenobase.fmt_datetime(datetime.datetime.combine(d, t)), times))
identifier_body
main.py
_path)) scope = ['https://spreadsheets.google.com/feeds'] credentials = SignedJwtAssertionCredentials(json_key['client_email'], bytes(json_key['private_key'], "utf-8"), scope) self.gc = gspread.authorize(credentials) logging.info("Authorization with Google successful!") self.za...
if not raw_table[j+2][i]: continue try: weight = float(raw_table[j+2][i]) except ValueError: logging.warning("Invalid data '{}' (not a number) in cell: {}. Skipping..." .forma...
random_line_split
PointCode.js
55] ] ); Point.scoreModeListExt[modeIndex].colors[i][1] = Point.scoreModeListExt[modeIndex].colors[i][0]; } break; case 'mellow': for (i = 0; i < randInt(25,35); i++) { // mellow colors Point.scoreModeListExt[modeIndex].colors.push([ fillArray(3,3,85,153), [255,255,255] ]); for (j = 0; j < 3; j++) { ...
random_line_split
PointCode.js
iPad') { width = '60px' } else { width = '40px' } for (var i = 0; i < btns.length; i++)
Point.switch(); } else if(!Point.mainTask.running) { Point.clearTo([0,0,0]); Point.init(); Point.flicker(); } }; Point.stop = function() { Point.mainTask.stop(); Point.metaTask.stop(); Point.clearTo([0,0,0]); Point.flicker('stop'); }; Point.flicker = function(mode) { var interval = 100, tuple = [0,0]; ...
{ btns[i].style.width = width; }
conditional_block
policymap.go
upper limit of entries in the per endpoint policy // table ie the maximum number of peer identities that the endpoint could // send/receive traffic to/from.. It is set by InitMapInfo(), but unit // tests use the initial value below. // The default value of this upper limit is 16384. MaxEntries = 16384 ) type Pol...
sb.WriteString(fmt.Sprintf("%20s: %s\n", entry.Key.String(), entry.PolicyEntry.String())) } return sb.String() } // Less is a function used to sort PolicyEntriesDump by Policy Type // (Deny / Allow), TrafficDirection (Ingress / Egress) and Identity // (ascending order). func (p PolicyEntriesDump) Less(i, j int)...
random_line_split
policymap.go
limit of entries in the per endpoint policy // table ie the maximum number of peer identities that the endpoint could // send/receive traffic to/from.. It is set by InitMapInfo(), but unit // tests use the initial value below. // The default value of this upper limit is 16384. MaxEntries = 16384 ) type PolicyMap...
() bool { return pe.Flags.is(policyFlagDeny) } func (pe *PolicyEntry) String() string { return fmt.Sprintf("%d %d %d", pe.GetProxyPort(), pe.Packets, pe.Bytes) } func (pe *PolicyEntry) New() bpf.MapValue { return &PolicyEntry{} } // PolicyKey represents a key in the BPF policy map for an endpoint. It must // match...
IsDeny
identifier_name
policymap.go
limit of entries in the per endpoint policy // table ie the maximum number of peer identities that the endpoint could // send/receive traffic to/from.. It is set by InitMapInfo(), but unit // tests use the initial value below. // The default value of this upper limit is 16384. MaxEntries = 16384 ) type PolicyMap...
func (k *CallKey) New() bpf.MapKey { return &CallKey{} } // String converts the value into a human readable string format. func (v *CallValue) String() string { return strconv.FormatUint(uint64(v.progID), 10) } func (v *CallValue) New() bpf.MapValue { return &CallValue{} } func (pe *PolicyEntry) Add(oPe PolicyEnt...
{ return strconv.FormatUint(uint64(k.index), 10) }
identifier_body
policymap.go
else { str = append(str, "Allow") } if pef.is(policyFlagWildcardNexthdr) { str = append(str, "WildcardProtocol") } if pef.is(policyFlagWildcardDestPort) { str = append(str, "WildcardPort") } return strings.Join(str, ", ") } var ( // MaxEntries is the upper limit of entries in the per endpoint policy //...
{ str = append(str, "Deny") }
conditional_block
output.rs
} #[derive(Debug, Clone, PartialEq, Eq)] pub enum AsyncClass { Stopped, CmdParamChanged, LibraryLoaded, Thread(ThreadEvent), BreakPoint(BreakPointEvent), Other(String), //? } #[derive(Debug)] pub enum AsyncKind { Exec, Status, Notify, } #[derive(Debug)] pub enum StreamKind { C...
let byte = input[0]; if byte == b'\"' { IResult::Error(::nom::ErrorKind::Custom(1)) //what are we supposed to return here?? } else { IResult::Done(&input[1..], byte) } } named!( escaped_character<u8>, alt!( value!(b'\n', tag!("\\n")) | value!(b'\r', tag!("\\r...
| value!(ResultClass::Exit, tag!("exit")) ) ); fn non_quote_byte(input: &[u8]) -> IResult<&[u8], u8> {
random_line_split
output.rs
#[derive(Debug, Clone, PartialEq, Eq)] pub enum AsyncClass { Stopped, CmdParamChanged, LibraryLoaded, Thread(ThreadEvent), BreakPoint(BreakPointEvent), Other(String), //? } #[derive(Debug)] pub enum AsyncKind { Exec, Status, Notify, } #[derive(Debug)] pub enum StreamKind { Cons...
} result_pipe.send(record).expect("send result to pipe"); } Output::OutOfBand(record) => { if let OutOfBandRecord::AsyncRecord { class: AsyncClass::Stopped, ...
{}
conditional_block
output.rs
} #[derive(Debug, Clone, PartialEq, Eq)] pub enum AsyncClass { Stopped, CmdParamChanged, LibraryLoaded, Thread(ThreadEvent), BreakPoint(BreakPointEvent), Other(String), //? } #[derive(Debug)] pub enum AsyncKind { Exec, Status, Notify, } #[derive(Debug)] pub enum StreamKind { C...
(line: &str) -> Result<Self, String> { match output(line.as_bytes()) { IResult::Done(_, c) => Ok(c), IResult::Incomplete(e) => Err(format!("parsing line: incomplete {:?}", e)), //Is it okay to read the next bytes then? IResult::Error(e) => Err(format!("parse error: {}", e)), ...
parse
identifier_name
runAffEffModSweap.py
plitude in eesAmplitudes: for eesFrequency in eesFrequencies: filName = name+"_amp_"+str(eesAmplitude)+"_freq_"+str(eesFrequency) resultFile = gt.find("*"+filName+".p",pathToResults) if not resultFile: returnCode = None while not returnCode==0: program = ['python','scripts/computeAfferentsEffere...
nActiveCells = {} nActiveCells["MnS"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)]) # nActiveCells["MnFf"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)]) # nActiveCells["MnFr"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)]) nActiveCells["Iaf"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)])...
# populationFr["MnFf"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)]) # populationFr["MnFr"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)]) populationFr["Iaf"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)])
random_line_split
runAffEffModSweap.py
["MnS_MnFf_MnFr"] = nActiveCells["MnS"]+nActiveCells["MnFf"]+nActiveCells["MnFr"] maxFr = {} maxFr["Iaf"] = np.max(populationFr["Iaf"]) maxFr["MnS"] = np.max(populationFr["MnS"]) # maxFr["MnS"] = np.max([populationFr["MnS"],populationFr["MnFf"],populationFr["MnFr"]]) # maxFr["MnFf"] = np.max([populationFr["MnS"],p...
tp = (target, f) current,error = minimize(target, f,x0=150) return current
identifier_body
runAffEffModSweap.py
nActiveCells[cellName][i,j] = _temp_nActiveCells[muscle][cellName] # populationFr["MnS_MnFf_MnFr"] = (populationFr["MnS"]+populationFr["MnFf"]+populationFr["MnFr"])/3 # nActiveCells["MnS_MnFf_MnFr"] = nActiveCells["MnS"]+nActiveCells["MnFf"]+nActiveCells["MnFr"] maxFr = {} maxFr["Iaf"] = np.max(populationFr["Iaf"...
break
conditional_block
runAffEffModSweap.py
in eesAmplitudes: for eesFrequency in eesFrequencies: filName = name+"_amp_"+str(eesAmplitude)+"_freq_"+str(eesFrequency) resultFile = gt.find("*"+filName+".p",pathToResults) if not resultFile: returnCode = None while not returnCode==0: program = ['python','scripts/computeAfferentsEfferentsModu...
(eesAmplitudes,eesFrequencies,simTime,name): populationFr = {} populationFr["MnS"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)]) # populationFr["MnFf"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)]) # populationFr["MnFr"] = np.zeros([len(eesAmplitudes),len(eesFrequencies)]) populationFr["Iaf"] = np.z...
plot_stats
identifier_name
miopoll.rs
(&mut self) { let mut ctrl = self.ctrl.borrow_mut(); if let Err(e) = ctrl.del(self.token, &mut self.source) { // TODO: Report the errors some other way, e.g. logged? ctrl.errors.push(e); } } } impl<S: Source> Deref for MioSource<S> { type Target = S; fn deref...
waker: Arc<Waker>, } impl Control { #[inline] fn del(&mut self, token: Token, handle: &mut impl Source) -> Result<()> { let rv = retry(|| self.poll.registry().deregister(handle)); if self.token_map.contains(token.into()) { self.token_map.remove(token.into()); return ...
// only for 0..=9 queues: [Vec<QueueEvent>; MAX_PRI as usize], max_pri: u32, events: Events, errors: Vec<Error>,
random_line_split
miopoll.rs
mut self) { let mut ctrl = self.ctrl.borrow_mut(); if let Err(e) = ctrl.del(self.token, &mut self.source) { // TODO: Report the errors some other way, e.g. logged? ctrl.errors.push(e); } } } impl<S: Source> Deref for MioSource<S> { type Target = S; fn deref(&...
} self.events.clear(); if !done { for qu in self.queues.iter_mut().rev() { if !qu.is_empty() { for qev in qu.drain(..) { if let Some(ref mut entry) = self.token_map.get_mut(qev.token) { done = tr...
{ // Fast-path for highest priority level present in // registrations, so if user uses only one priority level, // there is no queuing necessary here. let ready = Ready::new(ev); if entry.pri == self.max_pri { done = tru...
conditional_block
miopoll.rs
mut self) { let mut ctrl = self.ctrl.borrow_mut(); if let Err(e) = ctrl.del(self.token, &mut self.source) { // TODO: Report the errors some other way, e.g. logged? ctrl.errors.push(e); } } } impl<S: Source> Deref for MioSource<S> { type Target = S; fn deref(&...
{ token_map: Slab<Entry>, poll: Poll, // Highest priority in use goes on a fast path so we need queues // only for 0..=9 queues: [Vec<QueueEvent>; MAX_PRI as usize], max_pri: u32, events: Events, errors: Vec<Error>, waker: Arc<Waker>, } impl Control { #[inline] fn del(&mut ...
Control
identifier_name
xgboost.go
pred(datasource='''{{.DataSource}}''', select='''{{.Select}}''', result_table='''{{.ResultTable}}''', pred_label_name='''{{.PredLabelName}}''', load='''{{.Load}}''') ` type xgbEvaluateFiller struct { StepIndex int DataSource string Select ...
{ params := map[string]map[string]interface{}{"": {}, "train.": {}} paramPrefix := []string{"train.", ""} // use slice to assure traverse order, this is necessary because all string starts with "" for key, attr := range attrs { for _, pp := range paramPrefix { if strings.HasPrefix(key, pp) { params[pp][key[...
identifier_body
xgboost.go
batch_size") } epochAttr, ok := params["train."]["epoch"] if ok { epoch = epochAttr.(int) delete(params["train."], "epoch") } if _, ok := params["train."]["num_workers"]; ok { delete(params["train."], "num_workers") } if len(trainStmt.Features) > 1 { return "", fmt.Errorf("xgboost only support 0 or 1 fe...
(session *pb.Session) string { if session.Submitter != "" { return session.Submitter } submitter := os.Getenv("SQLFLOW_submitter") if submitter != "" { return submitter } return "local" } func generateFeatureColumnCode(fcMap map[string][]ir.FeatureColumn) string { allFCCodes := make([]string, 0) for targe...
getSubmitter
identifier_name
xgboost.go
: trainStmt.ModelImage, Estimator: trainStmt.Estimator, DataSource: dbConnStr, Select: replaceNewLineRuneAndTrimSpace(trainStmt.Select), ValidationSelect: replaceNewLineRuneAndTrimSpace(trainStmt.ValidationSelect), ModelParamsJSON: string(mp), TrainParamsJSON: string(tp...
The number of rounds for boosting. range: [1, Infinity]`, attribute.IntLowerBoundChecker(1, true)). Int("train.batch_size", -1, `[default=-1]
random_line_split
xgboost.go
batch_size") } epochAttr, ok := params["train."]["epoch"] if ok { epoch = epochAttr.(int) delete(params["train."], "epoch") } if _, ok := params["train."]["num_workers"]; ok { delete(params["train."], "num_workers") } if len(trainStmt.Features) > 1 { return "", fmt.Errorf("xgboost only support 0 or 1 fe...
return "local" } func generateFeatureColumnCode(fcMap map[string][]ir.FeatureColumn) string { allFCCodes := make([]string, 0) for target, fcList := range fcMap { if len(fcList) == 0 { continue } codeList := make([]string, 0) for _, fc := range fcList { codeList = append(codeList, fc.GenPythonCode()) ...
{ return submitter }
conditional_block
internals.rs
<T> where T: Float, { pub frequency: T, pub clarity: T, } /// Data structure to hold any buffers needed for pitch computation. /// For WASM it's best to allocate buffers once rather than allocate and /// free buffers repeatedly, so we use a `BufferPool` object to manage the buffers. pub struct DetectorInte...
Pitch
identifier_name
internals.rs
: usize, pub buffers: BufferPool<T>, } impl<T> DetectorInternals<T> where T: Float, { pub fn new(size: usize, padding: usize) -> Self { let buffers = BufferPool::new(size + padding); DetectorInternals { size, padding, buffers, } } } /// Comp...
// adding this to our sum. square_error .iter_mut() .enumerate() .skip(1) .for_each(|(i, a)| { sum = sum + *a; *a = *a * T::from_usize(i + 1).unwrap() / sum; }); } #[cfg(test)] mod tests { use super::*; #[test] fn windowed_autocorrela...
square_error[0] = T::one(); // square_error[0] should always be zero, so we don't need to worry about
random_line_split
internals.rs
.get_complex_buffer()); let signal_complex = &mut ref1.borrow_mut()[..]; let scratch = &mut ref2.borrow_mut()[..]; let mut planner = FftPlanner::new(); let fft = planner.plan_fft_forward(signal_complex.len()); let inv_fft = planner.plan_fft_inverse(signal_complex.len()); // Compute the autocor...
{ let signal: Vec<f64> = vec![0., 1., 2., 0., -1., -2.]; let window_size: usize = 3; let buffers = &mut BufferPool::new(signal.len()); let result: Vec<f64> = (0..window_size) .map(|i| { signal[..window_size] .iter() .z...
identifier_body
main.rs
sync::{mpsc::Receiver, Arc, Mutex, RwLock}; use chain_impl_mockchain::block::{message::MessageId, Message}; use futures::Future; use bech32::{u5, Bech32, FromBase32, ToBase32}; use blockcfg::{ genesis_data::ConfigGenesisData, genesis_data::GenesisData, mock::Mockchain as Cardano, }; use blockchain::{Blockchain, B...
GenPrivKeyType::Ed25519Extended => gen_priv_key_bech32::<Ed25519Extended>(), GenPrivKeyType::FakeMMM => gen_priv_key_bech32::<FakeMMM>(), GenPrivKeyType::Curve25519_2HashDH => gen_priv_key_bech32::<Curve25519_2HashDH>(), }; println!("{}", priv_key_...
{ let command = match Command::load() { Err(err) => { eprintln!("{}", err); std::process::exit(1); } Ok(v) => v, }; match command { Command::Start(start_settings) => { if let Err(error) = start(start_settings) { eprintln!("...
identifier_body
main.rs
::sync::{mpsc::Receiver, Arc, Mutex, RwLock}; use chain_impl_mockchain::block::{message::MessageId, Message}; use futures::Future; use bech32::{u5, Bech32, FromBase32, ToBase32}; use blockcfg::{ genesis_data::ConfigGenesisData, genesis_data::GenesisData, mock::Mockchain as Cardano, }; use blockchain::{Blockchain,...
match command { Command::Start(start_settings) => { if let Err(error) = start(start_settings) { eprintln!("jormungandr error: {}", error); std::process::exit(1); } } Command::GeneratePrivKey(args) => { let priv_key_bech32 = ...
random_line_split
main.rs
sync::{mpsc::Receiver, Arc, Mutex, RwLock}; use chain_impl_mockchain::block::{message::MessageId, Message}; use futures::Future; use bech32::{u5, Bech32, FromBase32, ToBase32}; use blockcfg::{ genesis_data::ConfigGenesisData, genesis_data::GenesisData, mock::Mockchain as Cardano, }; use blockchain::{Blockchain, B...
Ok(v) => v, }; match command { Command::Start(start_settings) => { if let Err(error) = start(start_settings) { eprintln!("jormungandr error: {}", error); std::process::exit(1); } } Command::GeneratePrivKey(args) => { ...
{ eprintln!("{}", err); std::process::exit(1); }
conditional_block
main.rs
sync::{mpsc::Receiver, Arc, Mutex, RwLock}; use chain_impl_mockchain::block::{message::MessageId, Message}; use futures::Future; use bech32::{u5, Bech32, FromBase32, ToBase32}; use blockcfg::{ genesis_data::ConfigGenesisData, genesis_data::GenesisData, mock::Mockchain as Cardano, }; use blockchain::{Blockchain, B...
( gd: &GenesisData, blockchain: &Blockchain<Cardano>, _settings: &settings::start::Settings, ) { println!( "k={} tip={}", gd.epoch_stability_depth, blockchain.get_tip() ); } // Expand the type with more variants // when it becomes necessary to represent different error cases...
startup_info
identifier_name
qualify_textgrid.py
text' TEXT_CATEGORY_PARSER = re.compile('^(?P<category>[1-4])\D.*', flags=re.UNICODE) MARKS_MEANING = { '1': '1-', '2': '2-', '3': '3-', '4': '4-' } logger = None time_logger = None def setup(target): global logger global time_logger if os.path.isdir(target): if target.endswith('\\'): target = target[:...
PATTERN_KEYS = ('pattern', 'key', 'type') def __init__(self, coding='utf-8'): super(TextgridParser, self).__init__() self.default_coding = coding self.intervals = [] self.original_duration_sum = 0 def reset(self): self.intervals = [] def read(self, filename): self.filename = filename with open(fil...
(re.compile('^(?P<text>.*)$'), 'text', str), # to adapt the new line (re.compile('^(?P<text>.*)"\s*$'), 'text', str), )
random_line_split
qualify_textgrid.py
= None time_logger = None def setup(target): global logger global time_logger if os.path.isdir(target): if target.endswith('\\'): target = target[:-1] logfile = os.path.join(target, os.path.basename(target)+'.log') timelog = os.path.join(target, 'duration.log') elif os.path.isfile(target): logfile = ta...
False if legal: validated.append(interval) if not quiet: print(u'验证完成,检测到%d个错误' % error_no) if error_no == 0: loginfo(u'Succeed') else: loginfo(u'共%d个错误被检测到' % error_no) loginfo('') # extra space line return validated def timeit(intervals, title=None): assoeted_intervals = {} for interval in in...
conditional_block
qualify_textgrid.py
text' TEXT_CATEGORY_PARSER = re.compile('^(?P<category>[1-4])\D.*', flags=re.UNICODE) MARKS_MEANING = { '1': '1-', '2': '2-', '3': '3-', '4': '4-' } logger = None time_logger = None def setup(target): global logger global time_logger if os.path.isdir(target): if target.endswith('\\'): target = target[:...
odecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)), ) # for textgrid header HEADER_PATTERN = ( re.compile('xmin = (?P<start>[\d\.]+)\s*xmax = (?P<end>[\d\.]+)\s*tiers\? <exists>'), lambda x: float(x.group('end')) - float(x.group('start')), ) BLOCK_PATTERNS = ( (re.compile('^\s*intervals \[(?P<slice>\d+)\]:'), 'sl...
', (c
identifier_name
qualify_textgrid.py
' TEXT_CATEGORY_PARSER = re.compile('^(?P<category>[1-4])\D.*', flags=re.UNICODE) MARKS_MEANING = { '1': '1-', '2': '2-', '3': '3-', '4': '4-' } logger = None time_logger = None def setup(target): global logger global time_logger if os.path.isdir(target): if target.endswith('\\'): target = target[:-1] ...
urn interval def match(self, item_pattern, line): return item_pattern['pattern'].match(line) def search(self, parser, fn): return fn(parser.search(self.content)) def parse(self): print(u'正在解析{filename}...'.format(filename=self.filename)) loginfo(u'>>文件:%s' % self.filename) original_duration = self.searc...
ip['key'])) else: interval.update({ ip['key']: ip['type'](ip['pattern'].match(line).group(ip['key'])) }) ret
identifier_body
table.rs
table.len()).expect("write error"); } // Reduce the table to prime, essential implicants pub fn reduce_to_prime_implicants (table: Table) -> Vec<Row> { // imps contains a vector of the found implicants; primed with the last row, last column let mut imps: Vec<u32> = Vec::new(); // Get the last column ...
// Put together the base implicants of the candidate new implicant temp_implicants = [work_set[i].implicants.clone(), work_set[a].implicants.clone()].concat(); // LOgic not right!!!!!! // Test to see if the i...
{ continue; }
conditional_block
table.rs
the last column, minus the already primed imps. let mut end_row: usize = table.entries.last().unwrap().len() -1; // Vector of the Rows that are prime implicants, primed with the first one let mut prime_imps: Vec<Row> = Vec::new(); // Loop until all of the imps have been found. loop { // C...
{ // If the array has a length less than or equal to one then it is already sorted if & table.len() <= & 1 { return table } // delare the three vectors let mut smaller: Vec<Row> = Vec::new(); let mut equal: Vec<Row> = Vec::new(); let mut larger: Vec<Row> = Vec::new(); // Get ...
identifier_body
table.rs
ps.contains(& table.entries[end_column][end_row].implicants[i]) { imps.extend(table.entries[end_column][end_row].implicants.clone()); prime_imps.push(table.entries[end_column][end_row].clone()); } } // Check to see if we are done if vec_in( & imps, & ...
bin: vec![0,0,0,0], ones: 0, implicants: vec![0],
random_line_split
table.rs
table.len()).expect("write error"); } // Reduce the table to prime, essential implicants pub fn reduce_to_prime_implicants (table: Table) -> Vec<Row> { // imps contains a vector of the found implicants; primed with the last row, last column let mut imps: Vec<u32> = Vec::new(); // Get the last column ...
(mut table: Table) -> Table { // imps is a vector of rows that houses the new column of implicants let mut imps: Vec<Row> = Vec::new(); // num_dashes is a u32 that contains the number of dashes (don't cares) in a row. If // there is more or less than one then the rows cannot be combined. let mut ...
initial_comparison
identifier_name
gobuild.go
Dir + pack.OutputFile + objExt argvFilled++ logger.Info("Linking %s...\n", argv[2]) logger.Info(" %s\n\n", getCommandline(argv)) cmd, err := exec.Run(linkerBin, argv[0:argvFilled], os.Environ(), rootPath, exec.DevNull, exec.PassThrough, exec.PassThrough) if err != nil { logger.Error("%s\n", err) os.Exit...
{ logger.Error("Can't create library because of compile errors.\n") compileErrors = true }
conditional_block
gobuild.go
} else { localPackName = pack.Name } testFileSource += "import \"" + pack.Name + "\"\n" tmpStr = "var test_" + localPackVarName + " = []testing.InternalTest {\n" for _, igf := range *pack.Files { logger.Debug("Test* from %s: \n", (igf.(*godata.GoFile)).Filename) if (igf.(*godata.GoFile)).IsTestFile...
{ var argc int var argv []string var argvFilled int var objDir string = "" //outputDirPrefix + getObjDir(); // build the command line for the linker argc = 4 if *flagIncludePaths != "" { argc += 2 } if pack.NeedsLocalSearchPath() { argc += 2 } if pack.Name == "main" { argc += 2 } argv = make([]stri...
identifier_body
gobuild.go
0:argvFilled], os.Environ(), rootPath, exec.DevNull, exec.PassThrough, exec.PassThrough) if err != nil { logger.Error("%s\n", err) os.Exit(1) } waitmsg, err := cmd.Wait(0) if err != nil { logger.Error("Linker execution error (%s), aborting compilation.\n", err) os.Exit(1) } if waitmsg.ExitStatus() != 0...
/* Creates a new file called _testmain.go and compiles/links it to _testmain. If the -run command line option is given it will also run the tests. In this
random_line_split