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
sandbox.ts
{Map} $instances Running instances storage * @returns {Sandbox} */ export class Sandbox<S = {}> extends Component<S, ISandboxOptions> { public static SB_DATA_ATTR = 'data-yuzu-sb'; public defaultOptions(): ISandboxOptions { return { components: [], context: createContext(), id: '', r...
{ this.emit('beforeStop'); await this.beforeDestroy(); this.removeListeners(); try { if (this.$el) { this.$el.removeAttribute(Sandbox.SB_DATA_ATTR); } await this.destroyRefs(); this.$active = false; } catch (e) { this.emit('error', e); return Promise.rejec...
identifier_body
sandbox.ts
const nextSbUid = createSequence(); const nextChildUid = createSequence(); /** * A sandbox can be used to initialize a set of components based on an element's innerHTML. * * Lets say we have the following component: * * ```js * class Counter extends Component { * static root = '.Counter'; * * // other stu...
( selector: string | entrySelectorFn, ): HTMLElement[] | boolean { let targets = evaluate(selector, this); if (typeof targets === 'string') { targets = this.findNodes(targets) as HTMLElement[]; } return targets; } /** * Creates a component instance. * Reads inline components from ...
resolveSelector
identifier_name
HexSnake.py
,0) colorApple=(250,0,0) colorMouth=(250,200,200) colorBonus=(40,0,240) colorText=(240,240,10) if True: s=int(raw_input("What is field size? (more than 2) : ")) loop={'y':False,'n':True}[raw_input("Do borders kill? ('y' or 'n') : ")[0]] # read params difficulty=int(raw_input(""" 0 - "pe...
def crawl(self): f=self.field x,y=self.body[-1] if f[x][y]==BODY: f[x][y],t=TAIL,[(x,y)] else : f[x][y],t=EMPTY,[] x,y=self.body[0] if f[x][y]!=BODY: f[x][y]=TAIL x,y=self.next(x,y,self.cdir)
rx, ry= further(x,y,d) if self.out(rx,ry): while (not self.out(x,y) ) : x,y= further(x,y,(d+3)%6) rx, ry= further(x,y,d) if not loop: self.field[rx][ry]=KILLER return rx,ry
identifier_body
HexSnake.py
0) colorApple=(250,0,0) colorMouth=(250,200,200) colorBonus=(40,0,240) colorText=(240,240,10) if True: s=int(raw_input("What is field size? (more than 2) : ")) loop={'y':False,'n':True}[raw_input("Do borders kill? ('y' or 'n') : ")[0]] # read params difficulty=int(raw_input(""" 0 - "pea...
if l==BONUS or l==EXTRASCORE: pygame.draw.circle(screen, colorBonus, crds, dh/2, 0) return def drawfield(self): n=self.field_dimension s=self.field_size ds=self.drawsymbol screen.fill((0,0,0)) pygame.draw.polygon(screen, colorGrass, [ ...
cx,cy=crds pygame.draw.line(screen,colorBonus,(cx-dh/3,cy-dh/3),(cx+dh/3,cy+dh/3),2) pygame.draw.line(screen,colorBonus,(cx+dh/3,cy-dh/3),(cx-dh/3,cy+dh/3),2)
conditional_block
HexSnake.py
,0) colorApple=(250,0,0) colorMouth=(250,200,200) colorBonus=(40,0,240) colorText=(240,240,10) if True: s=int(raw_input("What is field size? (more than 2) : ")) loop={'y':False,'n':True}[raw_input("Do borders kill? ('y' or 'n') : ")[0]] # read params difficulty=int(raw_input(""" 0 - "pe...
dh=self.display_height_step if l==TAIL: pygame.draw.circle(screen, colorSnake, crds, dh/2, 0) if l==BODY: pygame.draw.circle(screen, colorSnake, crds, dw/2, 0) if l==HEAD: x,y=further(i,j,self.cdir) x,y=self.display_crds(x,y) mc...
random_line_split
HexSnake.py
(x,y,i,j): d=3 if abs(x-i)>1 or abs(y-j)>1 else 0 v=(x-i)/abs(x-i) if x!=i else 0 h=(y-j)/abs(y-j) if y!=j else 0 return (d+{ (0,-1):0, (-1,-1):1, (-1,0):2, (0,1):3, (1,1):4, (1,0):5 }[(v,h)])%6 if True: # objects HEAD=-3 BODY=-2 ...
dir
identifier_name
helpers.ts
, functions: []}, }; static functionRegex: any = null; static relationMethods = ['has', 'orHas', 'whereHas', 'orWhereHas', 'whereDoesntHave', 'orWhereDoesntHave', 'doesntHave', 'orDoesntHave', 'hasMorph', 'orHasMorph', 'doesntHaveMorph', 'orDoesntHaveMorph', 'whereHasMorph', 'orWhereHasMorph', ...
} let basePathForCode = vscode.workspace.getConfiguration("LaravelExtraIntellisense").get<string>('basePathForCode'); if (forCode && basePathForCode && basePathForCode.length > 0) { if (basePathForCode.startsWith('.') && vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) { ...
return basePath + path;
random_line_split
helpers.ts
functions: []}, }; static functionRegex: any = null; static relationMethods = ['has', 'orHas', 'whereHas', 'orWhereHas', 'whereDoesntHave', 'orWhereDoesntHave', 'doesntHave', 'orDoesntHave', 'hasMorph', 'orHasMorph', 'doesntHaveMorph', 'orDoesntHaveMorph', 'whereHasMorph', 'orWhereHasMorph', '...
(path:string, forCode: boolean = false) : string { if (path[0] !== '/') { path = '/' + path; } let basePath = vscode.workspace.getConfiguration("LaravelExtraIntellisense").get<string>('basePath'); if (forCode === false && basePath && basePath.length > 0) { if (basePath.startsWith('.') && vscode.workspace...
projectPath
identifier_name
helpers.ts
functions: []}, }; static functionRegex: any = null; static relationMethods = ['has', 'orHas', 'whereHas', 'orWhereHas', 'whereDoesntHave', 'orWhereDoesntHave', 'doesntHave', 'orDoesntHave', 'hasMorph', 'orHasMorph', 'doesntHaveMorph', 'orDoesntHaveMorph', 'whereHasMorph', 'orWhereHasMorph', '...
} } ); }); return out; } /** * Parse php code with 'php-parser' package. * @param code */ static parsePhp(code: string): any { if (! Helpers.phpParser) { var PhpEngine = require('php-parser'); Helpers.phpParser = new PhpEngine({ parser: { extractDoc: true, php7: true ...
{ code = code.replace(/\"/g, "\\\""); if (['linux', 'openbsd', 'sunos', 'darwin'].some(unixPlatforms => os.platform().includes(unixPlatforms))) { code = code.replace(/\$/g, "\\$"); code = code.replace(/\\\\'/g, '\\\\\\\\\''); code = code.replace(/\\\\"/g, '\\\\\\\\\"'); } let command = vscode.workspace...
identifier_body
httpProcess.go
iyor. broker.clientIpAdress =append(broker.clientIpAdress,ipAddress) index = len(broker.clientIpAdress)-1 return } func (broker *Broker) findIpPosition(ipAddress string) (pos int) {//verilen ip'nin dizideki pozisyonunu buluyor. for i,ip := range broker.clientIpAdress{ if ip == ipAddress{ pos = i return ...
err := db.Prepare("SELECT app_id FROM app where pub_key = ? AND sub_key = ?") check(err,"") err = stmtOut.QueryRow(pubkey,subkey).Scan(&appId) if appId > 0{ isCheck =appId }else{ isCheck = -1 } defer stmtOut.Close() return } func (broker *Broker)subscribeHttpToRedis(w http.ResponseWriter, r *http.Requ...
check(err,"") err = stmtOut.QueryRow(subkey).Scan(&appId) if appId > 0{ isCheck =appId }else{ isCheck = -1 } defer stmtOut.Close() return } func checkPupKeySubKey(pubkey string,subkey string) (isCheck int) {//handchake yaparken gelen datamızı mysql ile kontrol ediyoruz var appId int stmtOut,
identifier_body
httpProcess.go
. broker.clientIpAdress =append(broker.clientIpAdress,ipAddress) index = len(broker.clientIpAdress)-1 return } func (broker *Broker) findIpPosition(ipAddress string) (pos int) {//verilen ip'nin dizideki pozisyonunu buluyor. for i,ip := range broker.clientIpAdress{ if ip == ipAddress{ pos = i return } ...
} } func check(err error, message string) {//genel hata yönetimi mekanizması if err != nil { panic(err) } fmt.Printf("%s\n", message) } func J sonStatus(message string, status int, jw http.ResponseWriter) {//Genel Response metodumuz jw.Header().Set("Content-Type", "application/json") return_message := &Statu...
"onlineUserTokens") fmt.Println("online Users:",onlieUsers) onlineUsersCount := client.SCard("onlineUserTokens") fmt.Println("online users count:",onlineUsersCount) case s := <-broker.closingClients://Bir client ayrıldı ve mesaj göndermeyi bırakmak istiyoruz onlieUsers := client.SMembers("onlineUserToke...
conditional_block
httpProcess.go
. broker.clientIpAdress =append(broker.clientIpAdress,ipAddress) index = len(broker.clientIpAdress)-1 return } func (broker *Broker) findIpPosition(ipAddress string) (pos int) {//verilen ip'nin dizideki pozisyonunu buluyor. for i,ip := range broker.clientIpAdress{ if ip == ipAddress{ pos = i return } ...
:= &StatusMessage{Message: message, StatusCode: status} jw.WriteHeader(http.StatusCreated) json.NewEncoder(jw).Encode(return_message) } func ByteToStr(data []byte) string{//byte to str d :=string(data[8:]) d = d[:len(d)-1] return d } func randToken() string {//random token üreten fonksiyon b := make([]byte, 8)...
rn_message
identifier_name
httpProcess.go
iyor. broker.clientIpAdress =append(broker.clientIpAdress,ipAddress) index = len(broker.clientIpAdress)-1 return } func (broker *Broker) findIpPosition(ipAddress string) (pos int) {//verilen ip'nin dizideki pozisyonunu buluyor. for i,ip := range broker.clientIpAdress{ if ip == ipAddress{ pos = i return ...
check(err,"") err = stmtOut.QueryRow(userId,c.PubKey,c.SubKey).Scan(&appId) if appId > 0 { isCheck = appId token = randToken() client.SAdd(c.SubKey[:8],token) } } defer stmtOut.Close() return } func checkSubKey(subkey string) (isCheck int) {//handchake yaparken gelen datamızı mysql ile kontrol ediy...
stmtOut, err := db.Prepare("SELECT app_id FROM app where user_id = ? AND pub_key = ? AND sub_key = ?")
random_line_split
blocks.go
"blocks" case "lz4", "gzip", "blocks", "uncompressed": break default: err = fmt.Errorf(`compression must be "lz4" (default), "gzip", "blocks" or "uncompressed"`) return } w.Header().Set("Content-type", "application/octet-stream") // extract querey string if blockstring == "" { return } coordarray := ...
{ store, err := datastore.GetOrderedKeyValueDB(d) if err != nil { return nil, err } // Retrieve the block of labels ctx := datastore.NewVersionedCtx(d, v) index := dvid.IndexZYX(bcoord) serialization, err := store.Get(ctx, NewBlockTKey(scale, &index)) if err != nil { return nil, fmt.Errorf("error getting '...
identifier_body
blocks.go
() string { var readAvgT, transcodeAvgT, writeAvgT time.Duration if bt.readN == 0 { readAvgT = 0 } else { readAvgT = bt.readT / time.Duration(bt.readN) } if bt.transcodeN == 0 { transcodeAvgT = 0 } else { transcodeAvgT = bt.transcodeT / time.Duration(bt.transcodeN) } if bt.readN == 0 { writeAvgT = 0 ...
String
identifier_name
blocks.go
fmt.Errorf("unknown compression %q requested for blocks", b.compression) return } var doMapping bool var mapping *VCache if !b.supervoxels { if mapping, err = getMapping(d, b.v); err != nil { return } if mapping != nil && mapping.mapUsed { doMapping = true } } // Need to do uncompression/recomp...
// Can only handle 3d requests. blockSize, okBlockSize := d.BlockSize().(dvid.Point3d) subvolSize, okSubvolSize := subvol.Size().(dvid.Point3d) startPt, okStartPt := subvol.StartPoint().(dvid.Point3d) if !okBlockSize || !okSubvolSize || !okStartPt { return } // Can only handle single block for now. if subv...
{ return }
conditional_block
blocks.go
= fmt.Errorf("unknown compression %q requested for blocks", b.compression) return } var doMapping bool var mapping *VCache if !b.supervoxels { if mapping, err = getMapping(d, b.v); err != nil { return } if mapping != nil && mapping.mapUsed { doMapping = true } } // Need to do uncompression/reco...
bcoordStr := bcoord.ToIZYXString() block, err := d.getLabelBlock(ctx, scale, bcoordStr) if err != nil { return err } if !supervoxels { mapping, err := getMapping(d, ctx.VersionID()) if err != nil { return err } modifyBlockMapping(ctx.VersionID(), block, mapping) } if err := block.WriteLabelVolume(w)...
} // writes a block of data as uncompressed ZYX uint64 to the writer in streaming fashion, allowing // for possible termination / error at any point. func (d *Data) streamRawBlock(ctx *datastore.VersionedCtx, w http.ResponseWriter, bcoord dvid.ChunkPoint3d, scale uint8, supervoxels bool) error {
random_line_split
external_accounts.go
AndSave for that. func (s *userExternalAccounts) LookupUserAndSave(ctx context.Context, spec extsvc.ExternalAccountSpec, data extsvc.ExternalAccountData) (userID int32, err error) { if Mocks.ExternalAccounts.LookupUserAndSave != nil { return Mocks.ExternalAccounts.LookupUserAndSave(spec, data) } err = dbconn.Glob...
res, err := dbconn.Global.ExecContext(ctx, "UPDATE user_external_accounts SET deleted_at=now() WHERE id=$1 AND deleted_at IS NULL", id) if err != nil { return err } nrows, err := res.RowsAffected() if err != nil { return err } if nrows == 0 { return userExternalAccountNotFoundError{[]interface{}{id}} } ...
{ return Mocks.ExternalAccounts.Delete(id) }
conditional_block
external_accounts.go
AndSave for that. func (s *userExternalAccounts) LookupUserAndSave(ctx context.Context, spec extsvc.ExternalAccountSpec, data extsvc.ExternalAccountData) (userID int32, err error) { if Mocks.ExternalAccounts.LookupUserAndSave != nil { return Mocks.ExternalAccounts.LookupUserAndSave(spec, data) } err = dbconn.Glob...
(ctx context.Context, serviceType string) error { // TEMP: Delete all external accounts associated with deleted users. Due to a bug in this // migration code, it was possible for deleted users to be associated with non-deleted external // accounts. This caused unexpected behavior in the UI (although did not pose a s...
TmpMigrate
identifier_name
external_accounts.go
// It creates a user external account and associates it with the specified user. If the external // account already exists and is associated with: // // - the same user: it updates the data and returns a nil error; or // - a different user: it performs no update and returns a non-nil error func (s *userExternalAccounts...
random_line_split
external_accounts.go
returns a nil error; or // - a different user: it performs no update and returns a non-nil error func (s *userExternalAccounts) AssociateUserAndSave(ctx context.Context, userID int32, spec extsvc.ExternalAccountSpec, data extsvc.ExternalAccountData) (err error) { if Mocks.ExternalAccounts.AssociateUserAndSave != nil ...
{ results, err := s.listBySQL(ctx, querySuffix) if err != nil { return nil, err } if len(results) != 1 { return nil, userExternalAccountNotFoundError{querySuffix.Args()} } return results[0], nil }
identifier_body
smt.rs
3.0-rc1/meta-contract-generator"; const META_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [1u8; 32]; // sudt contract const SUDT_GENERATOR_PATH: &str = "../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/sudt-generator"; const SUDT_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [2u8; 32]; // always success lock const ALWAYS...
(c: &mut Criterion) { let config = StoreConfig { path: "./smt_data/db".parse().unwrap(), options_file: Some("./smt_data/db.toml".parse().unwrap()), cache_size: Some(1073741824), }; let store = Store::open(&config, COLUMNS).unwrap(); let ee = BenchExecutionEnvironment::new_with_ac...
bench_ckb_transfer
identifier_name
smt.rs
// meta contract const META_GENERATOR_PATH: &str = "../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/meta-contract-generator"; const META_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [1u8; 32]; // sudt contract const SUDT_GENERATOR_PATH: &str = "../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/sudt-generat...
random_line_split
smt.rs
3.0-rc1/meta-contract-generator"; const META_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [1u8; 32]; // sudt contract const SUDT_GENERATOR_PATH: &str = "../../crates/builtin-binaries/builtin/gwos-v1.3.0-rc1/sudt-generator"; const SUDT_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [2u8; 32]; // always success lock const ALWAYS...
} struct BenchExecutionEnvironment { generator: Generator, chain: BenchChain, mem_pool_state: MemPoolState, } impl BenchExecutionEnvironment { fn new_with_accounts(store: Store, accounts: u32) -> Self { let genesis_config = GenesisConfig { meta_contract_validator_type_hash: META_V...
{ unreachable!("bench chain store") }
identifier_body
smt.rs
rc1/sudt-generator"; const SUDT_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [2u8; 32]; // always success lock const ALWAYS_SUCCESS_LOCK_HASH: [u8; 32] = [3u8; 32]; // rollup type hash const ROLLUP_TYPE_HASH: [u8; 32] = [4u8; 32]; const CKB_BALANCE: u128 = 100_000_000; criterion_group! { name = smt; config = Crit...
{ panic!("store genesis already initialized"); }
conditional_block
run.py
for s in ltm: m.absorb(s, timesteps=asteps) set_global_param('punishing', pun) set_global_param('painter_clarity', pcl) set_global_param('cell_clarity', ccl) set_log_level(llr) lo(1, 'LTS\n' + m.lts.state_str()) #lo(1, 'LTS\n' + m.lts.state_str_with_authors()) if rsteps: ...
def runab13_ajaqb(seed='a '): run(seed, ltm=['ajaqb'], ab=[ab1, ab3]) def runabs3(): # abs painters with more LTM run(seed='a ', ltm=['abcde', 'ggggg'], ab=[ab1]) # problem: many sames => many nonadjacent 'same' painters # therefore 'aaaaa' wins def runrel(): kw = dict( seed=...
run(seed='a ', ltm=['ajaqb'], ab=[ab1]) # no reln with j or q
identifier_body
run.py
set_global_param('punishing', pun) set_global_param('painter_clarity', pcl) set_global_param('cell_clarity', ccl) set_log_level(llr) lo(1, 'LTS\n' + m.lts.state_str()) #lo(1, 'LTS\n' + m.lts.state_str_with_authors()) if rsteps: set_global_param('allow_ab_initio_painters', abr) ...
for s in ltm: m.absorb(s, timesteps=asteps)
conditional_block
run.py
for s in ltm: m.absorb(s, timesteps=asteps) set_global_param('punishing', pun) set_global_param('painter_clarity', pcl) set_global_param('cell_clarity', ccl) set_log_level(llr) lo(1, 'LTS\n' + m.lts.state_str()) #lo(1, 'LTS\n' + m.lts.state_str_with_authors()) if rsteps: ...
(): # abs painters with a different seed run(seed='m ', ltm=['abcde'], ab=[ab1]) def runabs_ajaqb(**kwargs): run(seed='a ', ltm=['ajaqb'], ab=[ab1]) # no reln with j or q def runab13_ajaqb(seed='a '): run(seed, ltm=['ajaqb'], ab=[ab1, ab3]) def runabs3(): # abs painters with more LTM...
runabs2
identifier_name
run.py
6, llr=6, seed='m ' ) run(**(d | kwargs)) def run_pons(**kwargs) -> None: '''Runs the pons asinorum.''' lo(0, "pons asinorum") d = dict( ltm=[], asteps=0, seed='abcabdijk ', rsteps=200, #500, #llr=4, auto_annotate=[] ) ru...
ab=[ab1a], asteps=30,
random_line_split
rfc7539_test.go
, 0x9e, 0x96, 0xd6, 0x47, 0xb7, 0xc3, 0x9f, 0x56, 0xe0, 0x31, 0xca, 0x5e, 0xb6, 0x25, 0x0d, 0x40, 0x42, 0xe0, 0x27, 0x85, 0xec, 0xec, 0xfa, 0x4b, 0x4b, 0xb5, 0xe8, 0xea, 0xd0, 0x44, 0x0e, 0x20, 0xb6, 0xe8, 0xdb, 0x09, 0xd8, 0x81, 0xa7, 0xc6, 0x13, 0x2f, 0x42, 0x0e, 0x52, 0x79, 0x50, 0x42, 0xbd, 0xfa, 0x...
"wabe:\nAll mimsy were the borogoves,\nAnd the mome raths outgrabe.", [32]uint8{0x1c, 0x92, 0x40, 0xa5, 0xeb, 0x55, 0xd3, 0x8a, 0xf3, 0x33, 0x88, 0x86, 0x04, 0xf6, 0xb5, 0xf0, 0x47, 0x39, 0x17, 0xc1, 0x40, 0x2b, 0x80, 0x09, 0x9d, 0xca, 0x5c, 0xbc, 0x20, 0x70, 0x75, 0xc0},
random_line_split
rfc7539_test.go
x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, uint32(2), [12]uint8{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x72, 0xd5, 0x4d, 0xfb, 0xf1, 0x2e, 0xc4, 0x4b, 0x36, 0x26, 0x9...
{ type testCase struct { plaintext string key [32]uint8 counter uint32 nonce [12]uint8 ciphertext []byte } testCases := [...]testCase{{"Ladies and Gentlemen of the class of '99: " + "If I could offer you only one tip for the future, sunscreen would be it.", [32]uint8{0x00, 0x01, 0x02, ...
identifier_body
rfc7539_test.go
0x81, 0x60, 0xb8, 0x22, 0x84, 0xf3, 0xc9, 0x49, 0xaa, 0x5a, 0x8e, 0xca, 0x00, 0xbb, 0xb4, 0xa7, 0x3b, 0xda, 0xd1, 0x92, 0xb5, 0xc4, 0x2f, 0x73, 0xf2, 0xfd, 0x4e, 0x27, 0x36, 0x44, 0xc8, 0xb3, 0x61, 0x25, 0xa6, 0x4a, 0xdd, 0xeb, 0x00, 0x6c, 0x13, 0xa0}}, {[32]uint8{0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,...
} } func TestChaCha20Encryption(t *testing.T) { type testCase struct { plaintext string key [32]uint8 counter uint32 nonce [12]uint8 ciphertext []byte } testCases := [...]testCase{{"Ladies and Gentlemen of the class of '99: " + "If I could offer you only one tip for the future, sunscre...
{ t.Errorf("key: % x\n nonce: % x\n block counter: %d\n "+ "keystream: % x\nexpected: % x", test.key, test.nonce, test.counter, encrypt, test.ciphertext) }
conditional_block
rfc7539_test.go
0x81, 0x60, 0xb8, 0x22, 0x84, 0xf3, 0xc9, 0x49, 0xaa, 0x5a, 0x8e, 0xca, 0x00, 0xbb, 0xb4, 0xa7, 0x3b, 0xda, 0xd1, 0x92, 0xb5, 0xc4, 0x2f, 0x73, 0xf2, 0xfd, 0x4e, 0x27, 0x36, 0x44, 0xc8, 0xb3, 0x61, 0x25, 0xa6, 0x4a, 0xdd, 0xeb, 0x00, 0x6c, 0x13, 0xa0}}, {[32]uint8{0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,...
(t *testing.T) { type testCase struct { plaintext string key [32]uint8 counter uint32 nonce [12]uint8 ciphertext []byte } testCases := [...]testCase{{"Ladies and Gentlemen of the class of '99: " + "If I could offer you only one tip for the future, sunscreen would be it.", [32]uint8{0x0...
TestChaCha20Encryption
identifier_name
stream.rs
], } impl ChaChaKnN { /// Initalize an IETF ChaCha20 stream cipher with our key material /// and use it to generate the poly1305 key for our MAC gamma, and /// the packet's name for SURB unwinding. /// /// Notes: We could improve performance by using the curve25519 point /// derived in the key ...
(&self, beta: &[u8]) -> SphinxResult<Gamma> { if beta.len() != P::BETA_LENGTH as usize { return Err( SphinxError::InternalError("Beta has the incorrect length for MAC!") ); } // According to the current API gamma_out lies in a buffer supplied // by our caller, so no need for...
create_gamma
identifier_name
stream.rs
(r); sha.reset(); let (nonce,_,key) = array_refs![r,12,4,32]; SphinxKey { params: PhantomData, chacha: ChaChaKnN { nonce: *nonce, key: *key }, } } /// Initalize our IETF ChaCha20 stream cipher by invoking /// `ChaChaKnN::header_cipher` with our para...
{ return Err( SphinxError::InternalError("SURB log too long!") ); }
conditional_block
stream.rs
], } impl ChaChaKnN { /// Initalize an IETF ChaCha20 stream cipher with our key material /// and use it to generate the poly1305 key for our MAC gamma, and /// the packet's name for SURB unwinding. /// /// Notes: We could improve performance by using the curve25519 point /// derived in the key ...
/// Verify the poly1305 MAC `Gamma` given in a Sphinx packet. /// /// Returns an InvalidMac error if the check fails. Does not /// verify the lengths of Beta or the SURB. pub fn verify_gamma(&self, beta: &[u8], gamma_given: &Gamma) -> SphinxResult<()> { let gamma_found = self.create...
{ if beta.len() != P::BETA_LENGTH as usize { return Err( SphinxError::InternalError("Beta has the incorrect length for MAC!") ); } // According to the current API gamma_out lies in a buffer supplied // by our caller, so no need for games to zero it here. let mut gamm...
identifier_body
stream.rs
2], } impl ChaChaKnN { /// Initalize an IETF ChaCha20 stream cipher with our key material /// and use it to generate the poly1305 key for our MAC gamma, and /// the packet's name for SURB unwinding. /// /// Notes: We could improve performance by using the curve25519 point /// derived in the key...
/// Initalize our IETF ChaCha20 stream cipher by invoking /// `ChaChaKnN::header_cipher` with our paramaters `P: Params`. pub fn header_cipher(&self) -> SphinxResult<HeaderCipher<P>> { self.chacha.header_cipher::<P>() } } /// Amount of key stream consumed by `hop()` itself const HOP_EATS : usi...
} }
random_line_split
client_darwin.go
;thread:%x;", data, threadID) if err := c.send(command); err != nil { return err } return c.receiveAndCheck() } // ReadMemory reads the specified memory region. func (c *Client) ReadMemory(addr uint64, out []byte) error { command := fmt.Sprintf("m%x,%x", addr, len(out)) if err := c.send(command); err != nil { ...
{ log.Debugf("bad memory access: %s", packet) return Event{}, fmt.Errorf("bad memory access") }
conditional_block
client_darwin.go
nil { return Event{}, fmt.Errorf("send error: %v", err) } return c.wait() } func (c *Client) wait() (Event, error) { var data string var err error for { data, err = c.receiveWithTimeout(10 * time.Second) if netErr, ok := err.(net.Error); ok && netErr.Timeout() { // debugserver sometimes does not send a...
} else if c.buffer[0] != '+' { return errors.New("failed to receive ack") }
random_line_split
client_darwin.go
x;", threadID) if err := c.send(command); err != nil { return "", err } data, err := c.receive() if err != nil { return "", err } else if strings.HasPrefix(data, "E") { return data, fmt.Errorf("error response: %s", data) } return data, nil } func (c *Client) parseRegisterData(data string) (Registers, err...
buildStopReplies
identifier_name
client_darwin.go
.StepAndWait(threadID); err != nil { return 0, err } modifiedRegs, err = c.ReadRegisters(threadID) return modifiedRegs.Rcx, err } func (c *Client) updateReadTLSFunction(offset uint32) error { if c.currentTLSOffset == offset { return nil } readTLSFunction := c.buildReadTLSFunction(offset) if err := c.Write...
{ command := fmt.Sprintf("qThreadStopInfo%02x", threadID) if err := c.send(command); err != nil { return "", err } data, err := c.receive() if err != nil { return "", err } else if strings.HasPrefix(data, "E") { return data, fmt.Errorf("error response: %s", data) } return data, nil }
identifier_body
router.go
(v bool) { if v != r.routerMutable { r.routerMutable = v r.router.Mutable(v) } } func (r *Router) buildMiddlewares(m Middlewares) Middlewares { m2 := Middlewares{} m2.Before = append(m2.Before, r.middlewares.Before...) m2.Before = append(m2.Before, m.Before...) m2.After = append(m2.After, m.After...) m2.Aft...
return path } func (r *Router) handler(fn View, middle Middlewares) fasthttp.RequestHandler { middle = r.buildMiddlewares(middle) chain := make([]Middleware, 0) chain = append(chain, middle.Before...) chain = append(chain, func(ctx *RequestCtx) error { if !ctx.skipView { if err := fn(ctx); err != nil { ...
{ path = r.parent.getGroupFullPath(r.prefix + path) }
conditional_block
router.go
(v bool) { if v != r.routerMutable { r.routerMutable = v r.router.Mutable(v) } } func (r *Router) buildMiddlewares(m Middlewares) Middlewares { m2 := Middlewares{} m2.Before = append(m2.Before, r.middlewares.Before...) m2.Before = append(m2.Before, m.Before...) m2.After = append(m2.After, m.After...) m2.Aft...
(path string) *Router { groupFunc := r.router.Group if r.group != nil { groupFunc = r.group.Group } return &Router{ parent: r, router: r.router, routerMutable: r.routerMutable, errorView: r.errorView, prefix: path, group: groupFunc(path), handleOPTIONS: r.handleOPTI...
NewGroupPath
identifier_name
router.go
mutable(v bool) { if v != r.routerMutable { r.routerMutable = v r.router.Mutable(v) } } func (r *Router) buildMiddlewares(m Middlewares) Middlewares { m2 := Middlewares{} m2.Before = append(m2.Before, r.middlewares.Before...) m2.Before = append(m2.Before, m.Before...) m2.After = append(m2.After, m.After...)...
// Middlewares defines the middlewares (before, after and skip) in the order in which you want to execute them // for the view or group // // WARNING: The previous middlewares configuration could be overridden. func (r *Router) Middlewares(middlewares Middlewares) *Router { r.middlewares = middlewares return r } //...
}
random_line_split
router.go
(v bool)
func (r *Router) buildMiddlewares(m Middlewares) Middlewares { m2 := Middlewares{} m2.Before = append(m2.Before, r.middlewares.Before...) m2.Before = append(m2.Before, m.Before...) m2.After = append(m2.After, m.After...) m2.After = append(m2.After, r.middlewares.After...) m2.Skip = append(m2.Skip, m.Skip...) ...
{ if v != r.routerMutable { r.routerMutable = v r.router.Mutable(v) } }
identifier_body
ciao-vendor.go
r.Version, r.License) } w.Flush() return nil } func uses(pkg string, projectRoot string, direct bool) error { deps, err := calcDeps(projectRoot, []string{"./..."}) if err != nil { return err } var output bytes.Buffer cmd := exec.Command("go", "list", "./...") cmd.Stdout = &output err = cmd.Run() if err...
{ if !os.IsNotExist(err) { return fmt.Errorf("Unable to read %s : %v", packageFile, err) } return nil }
conditional_block
ciao-vendor.go
{ return err } vendorRoot := path.Join(projectRoot, "vendor") missing, uninstalled, notVendored, notUsed := verify(deps, vendorRoot) ok := checkKnown(missing, deps) ok = checkUninstalled(uninstalled) && ok ok = checkVendored(notVendored) && ok ok = checkNotUsed(notUsed) && ok if !ok { return fmt.Errorf("...
vendorNew
identifier_name
ciao-vendor.go
} err = cmd.Start() if err != nil { return err } scanner := bufio.NewScanner(stdout) for scanner.Scan() { fmt.Println(scanner.Text()) } err = cmd.Wait() if err != nil { return err } goGot[repoFound] = struct{}{} } return nil } func getCurrentBranch(repo string) (string, error) { ...
} return clientMap } func verify(deps piList, vendorRoot string) ([]string, []string, []string, []string) { uninstalled := make([]string, 0, 128) missing := make([]string, 0, 128) notVendored := make([]string, 0, 128) notUsed := make([]string, 0, 128) reposUsed := make(map[string]struct{}) depLoop: for _, d :...
for _, p := range packages { clientMap[p.name] = usedBy(p.name, packages, depsMap)
random_line_split
ciao-vendor.go
} err = cmd.Start() if err != nil { return err } scanner := bufio.NewScanner(stdout) for scanner.Scan() { fmt.Println(scanner.Text()) } err = cmd.Wait() if err != nil { return err } goGot[repoFound] = struct{}{} } return nil } func getCurrentBranch(repo string) (string, error) { ...
}(p.name) } for range packages { pkgDeps := <-depsCh depsMap[pkgDeps.p] = pkgDeps.deps } return depsMap } func computeClients(packages piList) map[string]string { depsMap := depsByPackage(packages) clientMap := make(map[string]string) for _, p := range packages { clientMap[p.name] = usedBy(p.name, pa...
{ depsMap := make(map[string][]string) depsCh := make(chan packageDeps) for _, p := range packages { go func(p string) { var output bytes.Buffer cmd := exec.Command("go", "list", "-f", listTemplate, p) cmd.Stdout = &output err := cmd.Run() if err != nil { fmt.Fprintf(os.Stderr, "Unable to call g...
identifier_body
newtoon.py
(error: Type[Exception], message: Optional[str] = None): def decorator(func: Callable) -> Coroutine: @wraps(func) async def wrapper(*args, **kwargs) -> Optional[Any]: try: return await func(*args, **kwargs) except error: if message: ...
filename = f'{index:03}.jpg' yield filename, url def _progress(self) -> None: self.log('.', end='') def _start_pull(self) -> None: self.log(f'{self.name}: ', end='') def _no_content(self) -> None: self.log('No content') def log(self, *args, **kwargs) -...
random_line_split
newtoon.py
: @wraps(func) async def wrapper(*args, **kwargs) -> Optional[Any]: try: return await func(*args, **kwargs) except error: if message: print(message) return None return wrapper return decorator class...
return self.episode > other.episode
identifier_body
newtoon.py
: Type[Exception], message: Optional[str] = None): def decorator(func: Callable) -> Coroutine: @wraps(func) async def wrapper(*args, **kwargs) -> Optional[Any]: try: return await func(*args, **kwargs) except error: if message: ...
options.add_argument('--disable-gpu') options.add_argument('--no-first-run --no-service-autorun --password-store=basic') extenssions_paths = [ '/usr/lib/ublock-origin' ] for extenssion in extenssions_paths: options.add_argument(f'--load-extension={extenss...
options.headless = True options.add_argument('--headless')
conditional_block
newtoon.py
decorator class InMemoryZipFile: def __init__(self, filename: str): self.io = BytesIO() self.cbz = zipfile.ZipFile(self.io, 'w', zipfile.ZIP_DEFLATED) self.filename = filename def __str__(self) -> str: return self.filename def exists(self) -> bool: return os.path...
ToonManager
identifier_name
overlay.js
go2.pl' : 'o2pl', 'tlen.pl' : 'o2pl', 'o2.pl' : 'o2pl', 'google.com' : 'google', 'twitter.com' : 'twitter', 'facebook.com' : 'facebook', 'mailgun.us' : 'rackspace', 'mailgun.org' : 'rackspace', 'emailsrvr.com' : 'rackspace', 'rackspace.com' : 'rackspace', 'dreamhost.com' : 'dream...
}, init: function() { // http://stackoverflow.com/questions/5089405/thunderbird-extension-add-field-to-messagepane-how-to-deal-with-windows-instan
random_line_split
cassandraMetadataPersistence.go
?, ` + `emit_metric: ?, ` + `archival_bucket: ?, ` + `archival_status: ?,` + `history_archival_status: ?, ` + `history_archival_uri: ?, ` + `visibility_archival_status: ?, ` + `visibility_archival_uri: ?, ` + `bad_binaries: ?,` + `bad_binaries_encoding: ?` + `}` templateDomainReplicationConfigTyp...
`config.archival_bucket, config.archival_status, ` + `config.history_archival_status, config.history_archival_uri, ` + `config.visibility_archival_status, config.visibility_archival_uri, ` + `config.bad_binaries, config.bad_binaries_encoding, ` + `replication_config.active_cluster_name, replication_config.clu...
templateGetDomainByNameQuery = `SELECT domain.id, domain.name, domain.status, domain.description, ` + `domain.owner_email, domain.data, config.retention, config.emit_metric, ` +
random_line_split
cassandraMetadataPersistence.go
return nil, err } return &cassandraMetadataPersistence{ cassandraStore: cassandraStore{session: session, logger: logger}, currentClusterName: clusterName, }, nil } // Close releases the resources held by this object func (m *cassandraMetadataPersistence) Close() { if m.session != nil { m.session.Close...
ListDomains
identifier_name
cassandraMetadataPersistence.go
gocql.LocalSerial cluster.Timeout = defaultSessionTimeout session, err := cluster.CreateSession() if err != nil { return nil, err } return &cassandraMetadataPersistence{ cassandraStore: cassandraStore{session: session, logger: logger}, currentClusterName: clusterName, }, nil } // Close releases the ...
{ return nil }
conditional_block
cassandraMetadataPersistence.go
aries, config.bad_binaries_encoding, ` + `replication_config.active_cluster_name, replication_config.clusters, ` + `is_global_domain, ` + `config_version, ` + `failover_version, ` + `db_version ` + `FROM domains_by_name ` + `WHERE name = ?` templateUpdateDomainByNameQuery = `UPDATE domains_by_name ` + ...
{ var nextVersion int64 = 1 var currentVersion *int64 if request.NotificationVersion > 0 { nextVersion = request.NotificationVersion + 1 currentVersion = &request.NotificationVersion } query := m.session.Query(templateUpdateDomainByNameQuery, request.Info.ID, request.Info.Name, request.Info.Status, req...
identifier_body
bikeshareproject.py
Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('H...
(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "a...
load_data
identifier_name
bikeshareproject.py
Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('H...
def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\n******************** Calculating Trip Duration... *********************\n') start_time = time.time() # display total travel time total_travel_time = df['Trip Duration'].sum() time1...
print('-'*40)
random_line_split
bikeshareproject.py
Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('H...
else: city = input('Sorry, I do not understand your input. Please input either ' 'Chicago, New York, or Washington.\n(Enter Correct city):\t ').lower() #lower() command is used to take input of any type formate # TO DO: get user input for month (all, januar...
break
conditional_block
bikeshareproject.py
(str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!') # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs city = input('\nWould you like to see...
"""Displays statistics on bikeshare users.""" print('\n******************** Calculating User Stats... *********************\n') start_time = time.time() # Display counts of user types no_of_subscribing_user = df['User Type'].str.count('Subscriber').sum() no_of_customers_using = df['User T...
identifier_body
bparser.py
(object): """ A parser for reading BibTeX bibliographic data files. Example:: from bibtexparser.bparser import BibTexParser bibtex_str = ... parser = BibTexParser() parser.ignore_nonstandard_types = False parser.homogenise_fields = False bib_database = bib...
BibTexParser
identifier_name
bparser.py
ex_str[3:] return StringIO(bibtex_str) def parse(self, bibtex_str): """Parse a BibTeX string into an object :param bibtex_str: BibTeX string :type: str or unicode :return: bibliographic database :rtype: BibDatabase """ self.bibtex_file_obj = self._bi...
cnt = 0 for i in range(0, len(val)): if val[i] == '{': cnt += 1 elif val[i] == '}': cnt -= 1 if cnt == 0: break if i == len(val) - 1: return True else: ...
identifier_body
bparser.py
ignore') if bibtex_str[:3] == byte: bibtex_str = bibtex_str[3:] return StringIO(bibtex_str) def parse(self, bibtex_str): """Parse a BibTeX string into an object :param bibtex_str: BibTeX string :type: str or unicode :return: bibliographic database ...
if val[i] == '{': cnt += 1 elif val[i] == '}': cnt -= 1 if cnt == 0: break
conditional_block
bparser.py
Parser` """ self.bib_database = BibDatabase() #: Callback function to process BibTeX entries after parsing, for example to create a list from a string with #: multiple values. By default all BibTeX values are treated as simple strings. Default: `None`. self.customization = None ...
elif inkey: logger.debug('Continues the previous line to complete the key pair value...') # if this line continues the value from a previous line, append inval += ', ' + kv # if it looks like this line finishes the value, store it and clear for...
else: logger.debug('The line is the end of the record.') d[key] = self._add_val(val)
random_line_split
fill_data.py
(file_data, ntts=[]): ''' Inicializa el diccionario de datos del archivo ''' content_fixes(file_data) file_data["id"]=mid2url(file_data['_id']) file_data['name']=file_data['src'].itervalues().next()['url'] file_se = file_data["se"] if "se" in file_data else None ntt = ntts[int(float(fil...
init_data
identifier_name
fill_data.py
# agrupación de origenes source_groups = {} file_sources = f['file']['src'].items() file_sources.sort(key=lambda x:x[1]["t"]) for hexuri,src in file_sources: if not src.get('bl',None) in (0, None): continue url_pattern=downloader=join=False count=0 part=...
'' Construye los enlaces correctamente ''' def get_domain(src): ''' Devuelve el dominio de una URL ''' url_parts=urlparse(src).netloc.split('.') i=len(url_parts)-1 if len(url_parts[i])<=2 and len(url_parts[i-1])<=3: return url_parts[i-2]+'.'+url_pa...
identifier_body
fill_data.py
_data["url_pattern"]%url] f['view']['source_id']=url view_source["pattern_used"]=True elif not "pattern_used" in view_source: view_source['urls'].append(url) if source_data["d"]!="eD2k": view_source['count']+=1 if link_wei...
s = {} for path, size in izip_longest(u(file_md["filepaths"]).split("///"), u(file_md.get("filesizes","")).split(" "), fillvalue=None): # no permite tamaños sin fichero if not path: break parts = path.strip("/").split("/") # crea subdirectorio...
conditional_block
fill_data.py
icon] = tip source=get_domain(src['url']) if "f" in source_data["g"] else source_data["d"] url=src['url'] if "url_pattern" in source_data and not url.startswith(("https://","http://","ftp://")): url_pattern=True #en caso de duda se prefiere streaming ...
value = adict[key] if isinstance(value, (int,long)): return value elif isinstance(value, float): return int(value) elif isinstance(value, basestring): result = None for c in value: digit = ord(c)-48 if 0<=digit<=9: if result: ...
random_line_split
main.rs
Message}; use rdkafka::producer::{BaseProducer, BaseRecord, DeliveryResult, ProducerContext}; use rdkafka::producer::{FutureProducer, FutureRecord}; use rdkafka::topic_partition_list::TopicPartitionList; use rdkafka::util::get_rdkafka_version; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std...
]))), ), ]); //add header info: '01111' // required for https://github.com/MaterializeInc/materialize/blob/master/src/interchange/avro.rs#L394 let mut body = [b'O', b'1', b'1', b'1', b'1'].to_vec(); encode(&record, &schema, &mut body); Ok(body) } fn deserialize(bytes: &Ve...
{ let schema = get_schema(); let mut writer = Writer::new(&schema, Vec::new()); let record = Value::Record(vec![ ( "before".to_string(), Value::Union(Box::new(Value::Record(vec![ ("FirstName".to_string(), Value::String("Greg".to_string())), ("...
identifier_body
main.rs
Message}; use rdkafka::producer::{BaseProducer, BaseRecord, DeliveryResult, ProducerContext}; use rdkafka::producer::{FutureProducer, FutureRecord}; use rdkafka::topic_partition_list::TopicPartitionList; use rdkafka::util::get_rdkafka_version; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std...
() { let matches = App::new("consumer example") .version(option_env!("CARGO_PKG_VERSION").unwrap_or("")) .about("Simple command line consumer") .arg( Arg::with_name("brokers") .short("b") .long("brokers") .help("Broker list in kafka...
main
identifier_name
main.rs
, Message}; use rdkafka::producer::{BaseProducer, BaseRecord, DeliveryResult, ProducerContext}; use rdkafka::producer::{FutureProducer, FutureRecord}; use rdkafka::topic_partition_list::TopicPartitionList; use rdkafka::util::get_rdkafka_version; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use st...
let input = writer.into_inner(); //add header info: '01111' // required for https://github.com/MaterializeInc/materialize/blob/master/src/interchange/avro.rs#L394 let body = [b'O', b'1', b'1', b'1', b'1'].to_vec(); let output = [&body[..], &input[..]].concat(); Ok(output) } fn serialize2() -...
random_line_split
logg.go
highlightMx.Lock() highlighted[hl] = struct{}{} highlightMx.Unlock() return struct{}{} } // _isSubsystemFiltered returns true if the subsystem should not pr logs func _isSubsystemFiltered(subsystem string) (found bool) { _logFilterMx.Lock() _, found = logFilter[subsystem] _logFilterMx.Unlock() return } // Add...
return e == nil }
random_line_split
logg.go
, false).Sprintf}, {logLevels.Error, "error", color.Bit24(255, 0, 0, false).Sprintf}, {logLevels.Check, "check", color.Bit24(255, 255, 0, false).Sprintf}, {logLevels.Warn, "warn ", color.Bit24(0, 255, 0, false).Sprintf}, {logLevels.Info, "info ", color.Bit24(255, 255, 0, false).Sprintf}, {logLevels.Debug, "de...
(hl string) struct{} { _logFilterMx.Lock() logFilter[hl] = struct{}{} _logFilterMx.Unlock() return struct{}{} } func getTimeText(level int32) string { // since := time.Now().Sub(logger_started).Round(time.Millisecond).String() // diff := 12 - len(since) // if diff > 0 { // since = strings.Repeat(" ", diff) + ...
AddFilteredSubsystem
identifier_name
logg.go
Writer(mw) return } // SortSubsystemsList sorts the list of subsystems, to keep the data read-only, // call this function right at the top of the main, which runs after // declarations and main/init. Really this is just here to alert the reader. func SortSubsystemsList() { sort.Strings(allSubsystems) // fmt.Fprintl...
{ return func(e error) bool { if level <= currentLevel.Load() && !_isSubsystemFiltered(subsystem) { if e != nil { printer := fmt.Sprintf if _isHighlighted(subsystem) { printer = color.Bold.Sprintf } fmt.Fprintf( writer, printer( "%-58v%s%s%-6v %s\n", getLoc(2, level, sub...
identifier_body
logg.go
, false).Sprintf}, {logLevels.Error, "error", color.Bit24(255, 0, 0, false).Sprintf}, {logLevels.Check, "check", color.Bit24(255, 255, 0, false).Sprintf}, {logLevels.Warn, "warn ", color.Bit24(0, 255, 0, false).Sprintf}, {logLevels.Info, "info ", color.Bit24(255, 255, 0, false).Sprintf}, {logLevels.Debug, "de...
var fileWriter *os.File if fileWriter, e = os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600); e != nil { fmt.Fprintln(os.Stderr, "unable to write log to", path, "error:", e) return } mw := io.MultiWriter(os.Stderr, fileWriter) fileWriter.Write([]byte("logging to file '" + path + "'\n")) mw.Write([]...
{ var b []byte b, e = ioutil.ReadFile(path) if e == nil { ioutil.WriteFile(path+fmt.Sprint(time.Now().Unix()), b, 0600) } }
conditional_block
cogroup.rs
) in vals { //! if wgt > max_wgt { //! max_wgt = wgt; //! max_val = val; //! } //! } //! output.push((max_val.clone(), max_wgt)); //! }) //! ``` use std::rc::Rc; use std::default::Default; use std::hash::Hasher; use std::ops::DerefMut; use itertools::Itertools; use ::{...
{ for key in &compact.keys { stash.push(index.clone()); source2.interesting_times(key, &index, &mut stash); for time in &stash { let mut queue = to_do.entry_or_insert((*time).clon...
conditional_block
cogroup.rs
for each key. //! //! ```ignore //! stream.group(|key, vals, output| { //! let (mut max_val, mut max_wgt) = vals.peek().unwrap(); //! for (val, wgt) in vals { //! if wgt > max_wgt { //! max_wgt = wgt; //! max_val = val; //! } //! } //! output.push((max_val.clone(...
if let Some(compact) = compact { for key in &compact.keys { stash.push(index.clone()); source2.interesting_times(key, &index, &mut stash); for time in &stash { ...
vec.sort_by(|x,y| key_h(&(x.0).0).cmp(&key_h((&(y.0).0)))); Compact::from_radix(&mut vec![vec], &|k| key_h(k)) };
random_line_split
cogroup.rs
for each key. //! //! ```ignore //! stream.group(|key, vals, output| { //! let (mut max_val, mut max_wgt) = vals.peek().unwrap(); //! for (val, wgt) in vals { //! if wgt > max_wgt { //! max_wgt = wgt; //! max_val = val; //! } //! } //! output.push((max_val.clone(...
< D: Data, V2: Data+Default, V3: Data+Default, U: Unsigned+Default, KH: Fn(&K)->U+'static, Look: Lookup<K, Offset>+'static, LookG: Fn(u64)->Look, Logic: Fn(&K, &mut CollectionIterator<V1>, &mut CollectionIterator<V2>, &mut Vec<(V3, i32)>)...
cogroup_by_inner
identifier_name
cogroup.rs
for each key. //! //! ```ignore //! stream.group(|key, vals, output| { //! let (mut max_val, mut max_wgt) = vals.peek().unwrap(); //! for (val, wgt) in vals { //! if wgt > max_wgt { //! max_wgt = wgt; //! max_val = val; //! } //! } //! output.push((max_val.clone(...
// create an exchange channel based on the supplied Fn(&D1)->u64. let exch1 = Exchange::new(move |&((ref k, _),_)| key_1(k).as_u64()); let exch2 = Exchange::new(move |&((ref k, _),_)| key_2(k).as_u64()); let mut sorter1 = LSBRadixSorter::new(); let mut sorter2 = LSBRadixSorter::...
{ let mut source1 = Trace::new(look(0)); let mut source2 = Trace::new(look(0)); let mut result = Trace::new(look(0)); // A map from times to received (key, val, wgt) triples. let mut inputs1 = Vec::new(); let mut inputs2 = Vec::new(); // A map from times to a l...
identifier_body
create-cp-input.py
_SSH_KEY = 'ssh_key' CONST_KSQL_DEST_DIR = '/var/lib/kafka/ksql' CONST_SOURCE_PATH = 'source_path' CONST_DEST_PATH = 'destination_path' CONST_BOOTSTRAP_SERVERS = 'bootstrap_servers' CONST_API_KEY = 'api_key' CONST_API_SECRET = 'api_secret' CONST_ADMIN = 'admin' CONST_CONSUMER = 'consumer' CONST_PRODUCER = 'producer' C...
(docs, config_type, override_apikey, override_apisecret): newdocs = {} if config_type in docs and CONST_API_KEY in docs[config_type]: newdocs[CONST_API_KEY] = docs[config_type][CONST_API_KEY] newdocs[CONST_API_SECRET] = docs[config_type][CONST_API_SECRET] else: newdocs[CONST_API_KEY]...
get_api_config
identifier_name
create-cp-input.py
import os CONST_TIMESTAMP = 'timestamp' CONST_NAME = 'name' CONST_PARTITIONS = 'partitions' CONST_REPLICATION = 'replication' CONST_OVERRIDE = 'override' CONST_DEPENDENCIES = 'dependencies' CONST_KSQL = 'ksql' CONST_CONNECT = 'connect' CONST_TOPIC = 'topic' CONST_TOPICS = 'topics' CONST_BROKER = 'broker' CONST_PROVISI...
from jinja2 import Template import yaml import json import logging import requests
random_line_split
create-cp-input.py
_SSH_KEY = 'ssh_key' CONST_KSQL_DEST_DIR = '/var/lib/kafka/ksql' CONST_SOURCE_PATH = 'source_path' CONST_DEST_PATH = 'destination_path' CONST_BOOTSTRAP_SERVERS = 'bootstrap_servers' CONST_API_KEY = 'api_key' CONST_API_SECRET = 'api_secret' CONST_ADMIN = 'admin' CONST_CONSUMER = 'consumer' CONST_PRODUCER = 'producer' C...
# Create cp-ansible yaml with ksql section def process_ksql (feid, doc): logging.debug ('-------') if CONST_PROVISION in doc and doc[CONST_PROVISION] == True: provision_ksql_hosts (feid, doc[CONST_HOSTS]) provision_ksql_query (feid, doc[CONST_QUERIES]) logging.debug ('-------') def provi...
hosts = [] for host in doc: logging.info ('ksql host is ' + host) hosts.append(host) inputs_map[CONST_KSQL + '_' + CONST_HOSTS] = hosts
identifier_body
create-cp-input.py
_SSH_KEY = 'ssh_key' CONST_KSQL_DEST_DIR = '/var/lib/kafka/ksql' CONST_SOURCE_PATH = 'source_path' CONST_DEST_PATH = 'destination_path' CONST_BOOTSTRAP_SERVERS = 'bootstrap_servers' CONST_API_KEY = 'api_key' CONST_API_SECRET = 'api_secret' CONST_ADMIN = 'admin' CONST_CONSUMER = 'consumer' CONST_PRODUCER = 'producer' C...
return newdocs def process_ccloud_config (docs): override_apikey = "" override_apisecret = "" if CONST_OVERRIDE in docs[CONST_CREDENTIALS]: override = docs[CONST_CREDENTIALS][CONST_OVERRIDE] if CONST_API_KEY in override: override_apikey = override[CONST_API_KEY] ...
newdocs[CONST_API_KEY] = override_apikey newdocs[CONST_API_SECRET] = override_apisecret
conditional_block
mod.rs
This typedef is generally used to avoid writing out io::Error directly and /// is otherwise a direct mapping to Result. pub type Result<T> = result::Result<T, io::Error>; // Returns a `Vec<T>` with a size in bytes at least as large as `size_in_bytes`. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fn vec_wi...
(&self) -> *const kvm_cpuid2 { &self.kvm_cpuid[0] } /// Get a mutable pointer so it can be passed to the kernel. Using this pointer is unsafe. /// pub fn as_mut_ptr(&mut self) -> *mut kvm_cpuid2 { &mut self.kvm_cpuid[0] } } /// Safe wrapper over the `kvm_run` struct. /// /// The wr...
as_ptr
identifier_name
mod.rs
Vec::with_capacity(rounded_size); for _ in 0..rounded_size { v.push(T::default()) } v } // The kvm API has many structs that resemble the following `Foo` structure: // // ``` // #[repr(C)] // struct Foo { // some_data: u32 // entries: __IncompleteArrayField<__u32>, // } // ``` // // In order...
{ return Err(io::Error::last_os_error()); }
conditional_block
mod.rs
This typedef is generally used to avoid writing out io::Error directly and /// is otherwise a direct mapping to Result. pub type Result<T> = result::Result<T, io::Error>; // Returns a `Vec<T>` with a size in bytes at least as large as `size_in_bytes`. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fn vec_wi...
/// Get a pointer so it can be passed to the kernel. Using this pointer is unsafe. /// pub fn as_ptr(&self) -> *const kvm_cpuid2 { &self.kvm_cpuid[0] } /// Get a mutable pointer so it can be passed to the kernel. Using this pointer is unsafe. /// pub fn as_mut_ptr(&mut self) -> *...
{ // Mapping the unsized array to a slice is unsafe because the length isn't known. Using // the length we originally allocated with eliminates the possibility of overflow. if self.kvm_cpuid[0].nent as usize > self.allocated_len { self.kvm_cpuid[0].nent = self.allocated_len as u32; ...
identifier_body
mod.rs
This typedef is generally used to avoid writing out io::Error directly and /// is otherwise a direct mapping to Result. pub type Result<T> = result::Result<T, io::Error>; // Returns a `Vec<T>` with a size in bytes at least as large as `size_in_bytes`. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fn vec_wi...
CpuId { kvm_cpuid, allocated_len: entries.len(), } } /// Returns the mutable entries slice so they can be modified before passing to the VCPU. /// /// # Example /// ```rust /// use kvm_ioctls::{CpuId, Kvm, MAX_KVM_CPUID_ENTRIES}; /// let kvm = Kvm::n...
random_line_split
file_server.rs
use crate::file_watcher::FileWatcher; use bytes::Bytes; use futures::{stream, Future, Sink, Stream}; use glob::{glob, Pattern}; use std::collections::HashMap; use std::fs; use std::io::{Read, Seek, SeekFrom}; use std::path::PathBuf; use std::sync::mpsc::RecvTimeoutError; use std::time; use tracing::field; /// `FileSer...
( &self, path: &PathBuf, buffer: &mut Vec<u8>, ) -> Option<FileFingerprint> { let i = self.ignored_header_bytes as u64; let b = self.fingerprint_bytes; buffer.resize(b, 0u8); if let Ok(mut fp) = fs::File::open(path) { if fp.seek(SeekFrom::Start(i))...
get_fingerprint_of_file
identifier_name
file_server.rs
use crate::file_watcher::FileWatcher; use bytes::Bytes; use futures::{stream, Future, Sink, Stream}; use glob::{glob, Pattern}; use std::collections::HashMap; use std::fs; use std::io::{Read, Seek, SeekFrom}; use std::path::PathBuf; use std::sync::mpsc::RecvTimeoutError; use std::time; use tracing::field; /// `FileSer...
.exclude .iter() .map(|e| Pattern::new(e.to_str().expect("no ability to glob")).unwrap()) .collect::<Vec<_>>(); for (_file_id, watcher) in &mut fp_map { watcher.set_file_findable(false); // assume not findable until found ...
{ let mut line_buffer = Vec::new(); let mut fingerprint_buffer = Vec::new(); let mut fp_map: HashMap<FileFingerprint, FileWatcher> = Default::default(); let mut backoff_cap: usize = 1; let mut lines = Vec::new(); let mut start_of_run = true; // Alright friends, ...
identifier_body
file_server.rs
use crate::file_watcher::FileWatcher; use bytes::Bytes; use futures::{stream, Future, Sink, Stream}; use glob::{glob, Pattern}; use std::collections::HashMap; use std::fs; use std::io::{Read, Seek, SeekFrom}; use std::path::PathBuf; use std::sync::mpsc::RecvTimeoutError; use std::time; use tracing::field; /// `FileSer...
if old_modified_time < new_modified_time { info!( message = "Switching to watch most recently modified file.", new_modified_...
{ // matches a file with a different path if !was_found_this_cycle { info!( message = "Watched file has been renamed.", ...
conditional_block
file_server.rs
use crate::file_watcher::FileWatcher; use bytes::Bytes; use futures::{stream, Future, Sink, Stream}; use glob::{glob, Pattern}; use std::collections::HashMap; use std::fs; use std::io::{Read, Seek, SeekFrom}; use std::path::PathBuf; use std::sync::mpsc::RecvTimeoutError; use std::time; use tracing::field; /// `FileSer...
let mut start_of_run = true; // Alright friends, how does this work? // // We want to avoid burning up users' CPUs. To do this we sleep after // reading lines out of files. But! We want to be responsive as well. We // keep track of a 'backoff_cap' to decide how long we'll...
let mut backoff_cap: usize = 1; let mut lines = Vec::new();
random_line_split
BAT.py
_a3, key=atom_mass, reverse=True): # Find the last atom attached_to_a4 = sorted([a for a in a3.bondedTo() \ if (a in selected) and (a!=a2)], key=atom_name) for a4 in sorted(attached_to_a4, key=atom_mass, reverse=True): return (a1, a2, a3, a4) print...
:param colorBy: color atoms by 'Occupancy', or 'Beta'. None uses default colors. """
random_line_split
BAT.py
atom: atom.mass() terminal_atoms = sorted(\ [a for a in self.molecule.atoms if len(a.bondedTo())==1], key=atom_name) terminal_atoms = sorted(terminal_atoms, key=atom_mass) if (initial_atom is None): # Select the heaviest root atoms from the heaviest terminal atom root = [terminal_atoms[-1...
def BAT(self, XYZ, extended=False): """ Conversion from Cartesian to Bond-Angle-Torsion coordinates :param extended: whether to include external coordinates or not :param Cartesian: Cartesian coordinates. If None, then the molecules' coordinates will be used """ root = [distance(XYZ[self.roo...
""" Indices of the first torsions in the BAT array """ offset = 6 if extended else 0 torsionInds = np.array(range(offset + 5, self.natoms * 3, 3)) primaryTorsions = sorted(list(set(self._firstTorsionTInd))) return list(torsionInds[primaryTorsions])
identifier_body
BAT.py
attached_to_zero = sorted(root[0].bondedTo(), key=atom_name) attached_to_zero = sorted(attached_to_zero, key=atom_mass) root.append(attached_to_zero[-1]) attached_to_one = sorted([a for a in root[-1].bondedTo() \ if (a not in root) and (a not in terminal_atoms)], key=atom_name) attached_to_o...
sphere = Sphere(Vector(XYZ[a2]), bond) cone = Cone(Vector(XYZ[a2]), Vector(XYZ[a3] - XYZ[a2]), angle) plane123 = Plane(Vector(XYZ[a4]), Vector(XYZ[a3]), Vector(XYZ[a2])) points = sphere.intersectWith(cone).intersectWith(plane123) p = points[0] if (Plane(Vector(XYZ[a3]), Vector( XYZ[a2]),...
conditional_block
BAT.py
atom: atom.mass() terminal_atoms = sorted(\ [a for a in self.molecule.atoms if len(a.bondedTo())==1], key=atom_name) terminal_atoms = sorted(terminal_atoms, key=atom_mass) if (initial_atom is None): # Select the heaviest root atoms from the heaviest terminal atom root = [terminal_atoms[-1...
(self, extended): """ Indices of the first torsions in the BAT array """ offset = 6 if extended else 0 torsionInds = np.array(range(offset + 5, self.natoms * 3, 3)) primaryTorsions = sorted(list(set(self._firstTorsionTInd))) return list(torsionInds[primaryTorsions]) def BAT(self, XYZ, ext...
getFirstTorsionInds
identifier_name
gen_mike_input_rf_linux.py
ir_if_not_exist_given_filepath(filename): if not os.path.exists(os.path.dirname(filename)): try: os.makedirs(os.path.dirname(filename)) except OSError as exc: # Guard against race condition pass def read_attribute_from_config_file(attribute, config, compulsory=False): ...
print("{} completed preparing mike rainfall input".format(datetime.now())) print("Mike input rainfall file is available at {}".format(mike_rf_file_path))
random_line_split
gen_mike_input_rf_linux.py
import connection as con_params from db_adapter.base import get_Pool, destroy_Pool from db_adapter.constants import CURW_SIM_DATABASE, CURW_SIM_PASSWORD, CURW_SIM_USERNAME, CURW_SIM_PORT, CURW_SIM_HOST from db_adapter.curw_sim.timeseries import Timeseries from db_adapter.constants import COMMON_DATE_TIME_FORMAT ROOT...
if __name__ == "__main__": set_db_config_file_path(os.path.join(ROOT_DIRECTORY, 'db_adapter_config.json')) try: start_time = None end_time = None try: opts, args = getopt.getopt(sys.argv[1:], "h:s:e:", ["help", "start_time=", "end...
usageText = """ Usage: ./inputs/gen_mike_input_rf_linux.py [-s "YYYY-MM-DD HH:MM:SS"] [-e "YYYY-MM-DD HH:MM:SS"] -h --help Show usage -s --start_time Mike rainfall timeseries start time (e.g: "2019-06-05 00:00:00"). Default is 00:00:00, 3 days before today. -e --end_time Mike rainfa...
identifier_body
gen_mike_input_rf_linux.py
import connection as con_params from db_adapter.base import get_Pool, destroy_Pool from db_adapter.constants import CURW_SIM_DATABASE, CURW_SIM_PASSWORD, CURW_SIM_USERNAME, CURW_SIM_PORT, CURW_SIM_HOST from db_adapter.curw_sim.timeseries import Timeseries from db_adapter.constants import COMMON_DATE_TIME_FORMAT ROOT...
else: check_time_format(time=end_time) if output_dir is None: output_dir
end_time = (datetime.now() + timedelta(days=2)).strftime('%Y-%m-%d 00:00:00')
conditional_block