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
fixture.go
Vars: []string{ customCrOSUsername, customCrOSPassword, KeepStateVar, }, SetUpTimeout: 10*time.Minute + BugReportDuration, ResetTimeout: resetTimeout, TearDownTimeout: resetTimeout, PreTestTimeout: resetTimeout, PostTestTimeout: postTestTimeout, }) testing.AddFixture(&testing.Fixture{ ...
defer androidDevice.DumpLogs(cleanupCtx, s.OutDir(), "fixture_setup_persistent_logcat.txt") // Set default chrome options. opts, err := f.fOpt(ctx, s) if err != nil { s.Fatal("Failed to obtain Chrome options: ", err) } tags := []string{ "*nearby*=3", "*cryptauth*=3", "*device_sync*=3", "*multidevice*=...
{ // Android device from parent fixture. androidDevice := s.ParentValue().(*FixtData).AndroidDevice f.androidDevice = androidDevice // Credentials to use (same as Android). crosUsername := s.ParentValue().(*FixtData).Username crosPassword := s.ParentValue().(*FixtData).Password // Allocate time for logging and...
identifier_body
process.go
() []*Goroutine { return p.goroutines } // Stats returns a breakdown of the program's memory use by category. func (p *Process) Stats() *Stats { return p.stats } // BuildVersion returns the Go version that was used to build the inferior binary. func (p *Process) BuildVersion() string { return p.buildVersion } fun...
Goroutines
identifier_name
process.go
())) spanTableStart := mheap.Field("spans").SlicePtr().Address() spanTableEnd := spanTableStart.Add(mheap.Field("spans").SliceCap() * ptrSize) arenas = append(arenas, arena{ heapMin: arenaStart, heapMax: arenaEnd, bitmapMin: bitmapStart, bitmapMax: bitmapEnd, spanTableMin: spanTable...
arenas = append(arenas, arena{ heapMin: min, heapMax: max, bitmapMin: bitmap.a, bitmapMax: bitmap.a.Add(bitmap.ArrayLen()), spanTableMin: spans.a, spanTableMax: spans.a.Add(spans.ArrayLen() * ptrSize), }) // Copy out ptr/nonptr bits n := bitmap.ArrayLen() ...
{ ptr := level1Table.ArrayIndex(level1) if ptr.Address() == 0 { continue } level2table := ptr.Deref() level2size := level2table.ArrayLen() for level2 := int64(0); level2 < level2size; level2++ { ptr = level2table.ArrayIndex(level2) if ptr.Address() == 0 { continue } a := ptr.D...
conditional_block
process.go
, nil}, &Stats{"released", releasedSpanSize, nil}, }}, }}, &Stats{"ptr bitmap", bitmap, nil}, &Stats{"span table", spanTable, nil}, }} var check func(*Stats) check = func(s *Stats) { if len(s.Children) == 0 { return } var sum int64 for _, c := range s.Children { sum += c.Size } if sum...
{ for _, c := range s.Children { if c.Name == name { return c } } return nil }
identifier_body
process.go
bitmapStart, bitmapMax: bitmapEnd, spanTableMin: spanTableStart, spanTableMax: spanTableEnd, }) // Copy pointer bits to heap info. // Note that the pointer bits are stored backwards. for a := arenaStart; a < arenaUsed; a = a.Add(ptrSize) { off := a.Sub(arenaStart) >> logPtrSize if p.proc....
} spanRoundSize += spanSize - n*elemSize
random_line_split
server.js
// Port number: 3306 var connect = mysql.createConnection({ host: 'sql9.freesqldatabase.com', user:'sql9203547', password:'hhldFiMrKp', database:'sql9203547' }); // --------------------------Data base side---------------------------------------- // ---------------------create tables and connection----------...
}) } var createSession = function(req, responce, newUser) { return req.session.regenerate(function() { //newuser>>>> { id: 2, username: 'hananmajali', password: 'hananmajali' } bcrypt.hash(req.body.password,3,function (err,hash) { console.log(hash) //...
{ bcrypt.compare(req.body.password,results[0].password,function (err,match) { if(err){ console.log(err) } if(match){ console.log('this user is correct') flag = 'true'; console.log('flag now is true') createSession(req,res,results[0]); }else{ console.log('this ...
identifier_body
server.js
// Port number: 3306 var connect = mysql.createConnection({ host: 'sql9.freesqldatabase.com', user:'sql9203547', password:'hhldFiMrKp', database:'sql9203547' }); // --------------------------Data base side---------------------------------------- // ---------------------create tables and connection----------...
}); //---------languge----------------------------- app.post('/translate',function(req,response){ var value=req.body; translate(req.body.text, {from:req.body.languageFrom+'', to: req.body.languageTo+'' }) .then(res => { console.log(res.text); //=> I speak English //console.log(res.from.languag...
random_line_split
server.js
exist var data = 'INSERT INTO users (username,password,Nationallity,Birthday,location,imag) VALUES (\''+username+'\',\''+password+'\',\''+Nationallity+'\',\''+Birthday+'\',\''+location +'\',\''+Image+'\')'; connect.query(data); res.send('true'); }else{ res.send('false');...
{ --numUsers; // echo globally that this client has left socket.broadcast.emit('user left', { username: socket.username, numUsers: numUsers }); }
conditional_block
server.js
// Port number: 3306 var connect = mysql.createConnection({ host: 'sql9.freesqldatabase.com', user:'sql9203547', password:'hhldFiMrKp', database:'sql9203547' }); // --------------------------Data base side---------------------------------------- // ---------------------create tables and connection----------...
() { bcrypt.compare(req.body.password,results[0].password,function (err,match) { if(err){ console.log(err) } if(match){ console.log('this user is correct') flag = 'true'; console.log('flag now is true') createSession(req,res,results[0]); }else{ console.log('th...
compare
identifier_name
msc_chart.py
elif github_token: g = Github(github_token) else: raise Exception( "Either pygithub or github_token must be set when initializing MSCChart" ) # Create a Github instance. The token only needs read:public_repo self.repository = g.get_rep...
g = pygithub
random_line_split
msc_chart.py
_token) else: raise Exception( "Either pygithub or github_token must be set when initializing MSCChart" ) # Create a Github instance. The token only needs read:public_repo self.repository = g.get_repo("matrix-org/matrix-doc") def generate(self, type:...
( self, msc: Issue, msc_events: List[Tuple[IssueEvent, Optional[Label]]], dt: datetime, ) -> MSCState: """Given a datetime, get the state of an MSC at that time Args: msc: The MSC to target, msc_events: A cached List of github issue events to ...
_get_msc_state_at_time
identifier_name
msc_chart.py
then don't update the events # This would prevent us from needing to fetch the label for each event # Also try the GraphQL API # Loop until we succeeded in getting the events for this MSC while True: try: # Pre-request the event labe...
labels[idx] = f"{label} ({values[idx]})"
conditional_block
msc_chart.py
_token) else: raise Exception( "Either pygithub or github_token must be set when initializing MSCChart" ) # Create a Github instance. The token only needs read:public_repo self.repository = g.get_repo("matrix-org/matrix-doc") def generate(self, type:...
def _generate_stacked_area_chart(self, filepath: str): """Generates a historical stacked area chart of msc status""" # Get time of the earliest issue mscs = list( self.repository.get_issues( sort="created", state="all", direction="asc", labels=["proposal"], ...
"""Generate the chart Args: type: The type of chart to generate filepath: Where to place the generated chart """ # Choose which chart type to generate if type == ChartType.PIE: self._generate_msc_pie_chart(filepath) elif type == ChartType.STAC...
identifier_body
main.rs
cfg(not(feature = "serde_type"))] extern crate rustc_serialize; extern crate mount; extern crate staticfile; extern crate reqwest; extern crate serde_json; extern crate iron_sessionstorage; extern crate urlencoded; use iron::prelude::*; use iron::headers::ContentType; use iron::modifiers::Redirect; use iron::{Url, sta...
let mut resp = Response::new(); resp.set_mut(Template::new("index", data)).set_mut(status::Ok); Ok(Response::with((status::Found, Redirect( Url::parse(redirect_url.as_str()).expect("parse url failed") )))) ...
}) }, None => HashMap::<String, Json>::new(), };
random_line_split
main.rs
cfg(not(feature = "serde_type"))] extern crate rustc_serialize; extern crate mount; extern crate staticfile; extern crate reqwest; extern crate serde_json; extern crate iron_sessionstorage; extern crate urlencoded; use iron::prelude::*; use iron::headers::ContentType; use iron::modifiers::Redirect; use iron::{Url, sta...
} } #[derive(Debug)] struct AccessToken(String); impl iron_sessionstorage::Value for AccessToken { fn get_key() -> &'static str { "access_token" } fn into_raw(self) -> String { self.0 } fn from_raw(value: String) -> Option<Self> { Some(AccessToken(value)) } } fn main() { dotenv().ok(...
{ match x { Value::Number(ref x) if x.is_i64() => Json::I64(x.as_i64().unwrap()), Value::Number(ref x) if x.is_u64() => Json::U64(x.as_u64().unwrap()), Value::Number(ref x) if x.is_f64() => Json::F64(x.as_f64().unwrap()), Value::String(x) => Json::String(x), Value::Array(x) =...
identifier_body
main.rs
cfg(not(feature = "serde_type"))] extern crate rustc_serialize; extern crate mount; extern crate staticfile; extern crate reqwest; extern crate serde_json; extern crate iron_sessionstorage; extern crate urlencoded; use iron::prelude::*; use iron::headers::ContentType; use iron::modifiers::Redirect; use iron::{Url, sta...
(String); impl iron_sessionstorage::Value for AccessToken { fn get_key() -> &'static str { "access_token" } fn into_raw(self) -> String { self.0 } fn from_raw(value: String) -> Option<Self> { Some(AccessToken(value)) } } fn main() { dotenv().ok(); let port = match env::var("PORT") { ...
AccessToken
identifier_name
MySVN.py
(message, raise_exception = True): """ Display error message, then terminate. """ print "Error:", message print if raise_exception: raise ExternalCommandFailed else: sys.exit(1) # Windows compatibility code by Bill Baxter if os.name == "nt": def find_program...
display_error
identifier_name
MySVN.py
< 100: commit_paths.append(p) # Detect special cases old_p = d['copyfrom_path'] if old_p and old_p.startswith(svn_path + "/"): old_p = old_p[len(svn_path):].strip("/") # Both paths can be identical if copied from an old rev. # We treat like...
pull_svn_rev(log_entry, svn_url, target_url, svn_path, original_wc, keep_author)
conditional_block
MySVN.py
locale_encoding = locale.getpreferredencoding() def run_svn(args, fail_if_stderr=False, encoding="utf-8"): """ Run svn cmd in PIPE exit if svn cmd failed """ def _transform_arg(a): if isinstance(a, unicode): a = a.encode(encoding or locale_encoding) elif no...
if os.name == "nt": q = '"' else: q = "'" return q + s.replace('\\', '\\\\').replace("'", "'\"'\"'") + q
identifier_body
MySVN.py
vn_url_or_wc, rev_number=None): """ Get SVN information for the given URL or working copy, with an optionally specified revision number. Returns a dict as created by parse_svn_info_xml(). """ if rev_number is not None: args = [svn_url_or_wc + "@" + str(rev_number)] else: ...
random_line_split
base.js
AlertAge:path+"/web/healthAlert/getAlertAge",// 获得预警年龄列表 riskNewHealthAlert:path+"/web/healthAlert/newHealthAlert",// 新增风险预警 riskGetHealthAlert:path+"/web/healthAlert/getHealthAlert",// 获取单条健康预警 riskUpdateHealthAlert:path+"/web/healthAlert/updateHealthAlert",// 更改健康预警 riskDeleteHealthAlert:path+"/web/healthAler...
identifier_body
base.js
/TJ/TJ_GCJL_GetClassAbilibySimple",// 班级领域发展水平--数量统计 getCourseAbilibyCount:path+"/web/sample/TJ/TJ_GCJL_GetCourseAbilibyCount",// 课程发展水平--数量统计 // 成长档案 recordStudent:path+"/web/mbtrack/dan/student",// 获取学生列表(含档案信息) recordList:path+"/web/mbtrack/danbook/list",// 获取档案册列表 recordMonthList:path+"/web/mbtrack/danb...
};
random_line_split
base.js
AlertAge:path+"/web/healthAlert/getAlertAge",// 获得预警年龄列表 riskNewHealthAlert:path+"/web/healthAlert/newHealthAlert",// 新增风险预警 riskGetHealthAlert:path+"/web/healthAlert/getHealthAlert",// 获取单条健康预警 riskUpdateHealthAlert:path+"/web/healthAlert/updateHealthAlert",// 更改健康预警 riskDeleteHealthAlert:path+"/web/healthAler...
identifier_name
base.js
AlertAge:path+"/web/healthAlert/getAlertAge",// 获得预警年龄列表 riskNewHealthAlert:path+"/web/healthAlert/newHealthAlert",// 新增风险预警 riskGetHealthAlert:path+"/web/healthAlert/getHealthAlert",// 获取单条健康预警 riskUpdateHealthAlert:path+"/web/healthAlert/updateHealthAlert",// 更改健康预警 riskDeleteHealthAlert:path+"/web/healthAler...
conditional_block
pouch-db-singleton.ts
'../storage-provider-base.js'; import {SerializedModelEntry, ModelValue} from '../crdt-collection-model.js'; import {PouchDbStorageProvider} from './pouch-db-storage-provider.js'; import {PouchDbStorage} from './pouch-db-storage.js'; import {upsert, UpsertDoc, UpsertMutatorFn} from './pouch-db-upsert.js'; /** * A r...
(): Promise<{version: number; model: SerializedModelEntry[]}> { await this.initialized; const doc = await this.upsert(async doc => doc); const value = doc.value; let model: SerializedModelEntry[] = []; if (value != null) { model = [ { id: value.id, keys: [], ...
serializeContents
identifier_name
pouch-db-singleton.ts
'../storage-provider-base.js'; import {SerializedModelEntry, ModelValue} from '../crdt-collection-model.js'; import {PouchDbStorageProvider} from './pouch-db-storage-provider.js'; import {PouchDbStorage} from './pouch-db-storage.js'; import {upsert, UpsertDoc, UpsertMutatorFn} from './pouch-db-upsert.js'; /** * A r...
} await this._fire(new ChangeEvent({data: newvalue, version: this._version})); } } /** * Returns the model data in a format suitable for transport over * the API channel (i.e. between execution host and context). */ async modelForSynchronization() { await this.initialized; const...
doc.referenceMode = this.referenceMode; doc.version = Math.max(this._version, doc.version) + 1; return doc; });
random_line_split
pouch-db-singleton.ts
= 0; /** * Create a new PouchDbSingleton. * * @param type the underlying type for this singleton. * @param storageEngine a reference back to the PouchDbStorage, used for baseStorageKey calls. * @param name appears unused. * @param id see base class. * @param key the storage key for this collect...
{ await this._fire(new ChangeEvent({data: value, version: this._version})); }
conditional_block
world.py
] self.legalstate = filter(lambda x:not ( x in self.traps or x in self.targets or x in self.walls ) , [ i for i in range(self.rows * self.cols)]) # print(self.legalstate) self.actionmap = { 0:'up', 1:'down', 2:'left', 3:'right' }...
return (-1,self.targetReward) elif state in self.traps : return (-1,self.trapReward) elif state in self.walls : return (0,self.wallReward) else: return (0,self.norReward) def isLegalState(self,state): if state >= 0 and state <...
if state in self.targets :
random_line_split
world.py
] self.legalstate = filter(lambda x:not ( x in self.traps or x in self.targets or x in self.walls ) , [ i for i in range(self.rows * self.cols)]) # print(self.legalstate) self.actionmap = { 0:'up', 1:'down', 2:'left', 3:'right' }...
(self,state): if state < 0 or state >= self.rows * self.cols: return False state = self.state_to_map[state] row = state / self.cols col = state - row * self.cols if self.map[row][col] == 'g': return True return False de...
isTarget
identifier_name
world.py
] self.legalstate = filter(lambda x:not ( x in self.traps or x in self.targets or x in self.walls ) , [ i for i in range(self.rows * self.cols)]) # print(self.legalstate) self.actionmap = { 0:'up', 1:'down', 2:'left', 3:'right' }...
ll.Y ) > math.fabs(targetCell.Y - state.realCell.Y) : addreward += 20 if math.fabs(targetCell.Y - state.realCell.Y) <= 1 : addreward += 5 if math.fabs( targetCell.Y - state.curCell.Y ) < math.fabs(targetCell.Y - state.realCell.Y) : addrewa...
d -= 50 if math.fabs( targetCell.Y - state.curCe
conditional_block
world.py
.legalstate = filter(lambda x:not ( x in self.traps or x in self.targets or x in self.walls ) , [ i for i in range(self.rows * self.cols)]) # print(self.legalstate) self.actionmap = { 0:'up', 1:'down', 2:'left', 3:'right' } self....
urn cell def getPositionStateNum(self,pos):
identifier_body
sheetDocument.ts
arrays); class SheetDocument { pages: SheetPage[]; constructor (fields: Partial<SheetDocument>, {initialize = true} = {}) { Object.assign(this, fields); if (initialize) this.updateTokenIndex(); } get systems (): SheetSystem[] { return [].concat(...this.pages.map(page => page.systems)); } // DEPR...
const bottom = Math.max(...rects.map(rect => rect[3]), ...tokenYs); const x = verticalCropOnly ? page.viewBox.x : left - margin; const y = (verticalCropOnly && i === 0) ? page.viewBox.y : top - margin; const width = verticalCropOnly ? page.viewBox.width : right - left + margin * 2; const height = (verti...
const left = Math.min(...rects.map(rect => rect[0]), ...tokenXs); const right = Math.max(...rects.map(rect => rect[1]), ...tokenXs); const top = Math.min(...rects.map(rect => rect[2]), ...tokenYs);
random_line_split
sheetDocument.ts
(...arrays); class SheetDocument { pages: SheetPage[]; constructor (fields: Partial<SheetDocument>, {initialize = true} = {}) { Object.assign(this, fields); if (initialize) this.updateTokenIndex(); } get systems (): SheetSystem[] { return [].concat(...this.pages.map(page => page.systems)); } // ...
(): number{ return Math.max(...this.systems.map(system => system.staves.length), 0); } get pageSize (): {width: number, height: number} { const page = this.pages && this.pages[0]; if (!page) return null; return { width: parseUnitExp(page.width), height: parseUnitExp(page.height), }; } updat...
trackCount
identifier_name
sw_06_cv_functions.py
eresis thresholding using some bitwise magic. """ print("BEFORE HYSTERISIS THRESHOLDING:", image) print("gradients:", image_gradients) largest_gradient_value = np.max(image_gradients) while largest_gradient_value < max_val: print("Largest gradient value:", largest_gradient_value) warnings.warn(UserWarning("Im...
def indices_where(condition): return np.concatenate(np.dstack(np.where(condition))) def index_with(list_of_indices): return list_of_indices[:, 0], list_of_indices[:, 1] def neighbourhood(index, image_width, image_height): """Returns the coordinates of the neighbours of a given coordinate or list of coordinates. ...
return np.concatenate(np.dstack(list_of_indices))
identifier_body
sw_06_cv_functions.py
eresis thresholding using some bitwise magic. """ print("BEFORE HYSTERISIS THRESHOLDING:", image) print("gradients:", image_gradients) largest_gradient_value = np.max(image_gradients) while largest_gradient_value < max_val: print("Largest gradient value:", largest_gradient_value) warnings.warn(UserWarning("Im...
(list_of_indices): return np.concatenate(np.dstack(list_of_indices)) def indices_where(condition): return np.concatenate(np.dstack(np.where(condition))) def index_with(list_of_indices): return list_of_indices[:, 0], list_of_indices[:, 1] def neighbourhood(index, image_width, image_height): """Returns the coordin...
aggregate
identifier_name
sw_06_cv_functions.py
# do not re-explore already explored indices. to_explore &= ~already_explored unexplored_indices = aggregate(np.nonzero(to_explore)) out = np.zeros_like(image_gradients) out[~strong] = 0 out[strong] = 255 print("AFTER HYSTERISIS THRESHOLDING:", out) return out def aggregate(list_of_indices): return np....
padding = np.array(kernel.shape) // 2
conditional_block
sw_06_cv_functions.py
ysteresis thresholding using some bitwise magic. """ print("BEFORE HYSTERISIS THRESHOLDING:", image) print("gradients:", image_gradients) largest_gradient_value = np.max(image_gradients) while largest_gradient_value < max_val: print("Largest gradient value:", largest_gradient_value) warnings.warn(UserWarning(...
NOTE: the pixels neighbours are clipped of (image_height-1, ) Returns: np.ndarray -- ndarray of shape [?, 2], which contains the indices of the neighbouring pixels """ neighbourhoods = np.concatenate(np.dstack((np.indices([3,3]) - 1))) if len(index.shape) == 2: neighbourhoods = neighbourhoods[:, np.newaxis,...
random_line_split
apitest.go
query map[string]string queryCollection map[string][]string headers map[string]string cookies map[string]string basicAuth string apiTest *APITest } type pair struct { l string r string } var DumpHttp Observe = func(res *http.Response, req *http.Request) { requestDump, ...
func (r *Response) CookieNotPresent(cookieName string) *Response { r.cookiesNotPresent = append(r.cookiesNotPresent, cookieName) return r } // Headers is the expected response headers func (r *Response) Headers(headers map[string]string) *Response { r.headers = headers return r } // Status is the expected respons...
// CookieNotPresent is used to assert that a cookie is not present in the response
random_line_split
apitest.go
map[string]string queryCollection map[string][]string headers map[string]string cookies map[string]string basicAuth string apiTest *APITest } type pair struct { l string r string } var DumpHttp Observe = func(res *http.Response, req *http.Request) { requestDump, err :=...
(url string) *Request { r.method = http.MethodPost r.url = url return r } // Put is a convenience method for setting the request as http.MethodPut func (r *Request) Put(url string) *Request { r.method = http.MethodPut r.url = url return r } // Delete is a convenience method for setting the request as http.Metho...
Post
identifier_name
apitest.go
used in combination with request.QueryCollection func (r *Request) Query(q map[string]string) *Request { r.query = q return r } // Query is a builder method to set the request query parameters // This can be used in combination with request.Query func (r *Request) QueryCollection(q map[string][]string) *Request { ...
{ assert.Nil(a.t, err) }
conditional_block
apitest.go
map[string]string queryCollection map[string][]string headers map[string]string cookies map[string]string basicAuth string apiTest *APITest } type pair struct { l string r string } var DumpHttp Observe = func(res *http.Response, req *http.Request) { requestDump, err :=...
for k, v := range a.request.headers { req.Header.Set(k, v) } for k, v := range a.request.cookies { cookie := &http.Cookie{Name: k, Value: v} req.AddCookie(cookie) } if a.request.basicAuth != "" { parts := strings.Split(a.request.basicAuth, ":") req.SetBasicAuth(parts[0], parts[1]) } return req } f...
{ req, _ := http.NewRequest(a.request.method, a.request.url, bytes.NewBufferString(a.request.body)) query := req.URL.Query() if a.request.queryCollection != nil { for _, param := range buildQueryCollection(a.request.queryCollection) { query.Add(param.l, param.r) } } if a.request.query != nil { for k, v ...
identifier_body
raft.go
} } r.state = candidate r.CurrentTerm++ r.VotedFor = r.id } // StoreClientData allows a client to send data to the raft cluster via RPC for storage // We fill the reply struct with "success = true" if we are leader and store the data successfully. // If we are not leader, we will reply with the id of another no...
(ae AppendEntriesStruct, response *RPCResponse) error { r.Lock() defer r.Unlock() if r.verbose { log.Printf("AppendEntries(). ae: %s", ae.String()) log.Printf("My log: %s", r.Log.String()) } response.Term = r.CurrentTerm if ae.LeaderID == r.currentLeader { if r.verbose { log.Println("AppendEntries from...
AppendEntries
identifier_name
raft.go
false } } r.state = candidate r.CurrentTerm++ r.VotedFor = r.id } // StoreClientData allows a client to send data to the raft cluster via RPC for storage // We fill the reply struct with "success = true" if we are leader and store the data successfully. // If we are not leader, we will reply with the id of anot...
log.Printf("commitIndex %d ineligible because of log entry %s", n, r.Log[n].String()) } continue } peersAtThisLevel := make(map[HostID]bool) for hostID := range r.hosts { if hostID == r.id { peersAtThisLevel[hostID] = true } else { peersAtThisLevel[hostID] = r.matchIndex[hostID] >= n } ...
// Then: // set commitIndex = N for n := r.commitIndex + 1; n <= r.getLastLogIndex(); n++ { if r.Log[n].Term != r.CurrentTerm { if r.verbose {
random_line_split
raft.go
because if it is not us, the client will // just get confused and contact the wrong node next time // this situation only arises if the client's previous attempt was partially successful, but leader crashed before replying return nil } // We are the leader and this is a new entry. Attempt to replicate this to...
{ if x < y { return x } return y }
identifier_body
raft.go
prevReply.Success // response.leader = prevReply.leader // NOTE - we do not want to notify about the previous leader, because if it is not us, the client will // just get confused and contact the wrong node next time // this situation only arises if the client's previous attempt was partially successful, but l...
{ return x }
conditional_block
svgfrags.py
+= options.margin[1] ymin -= options.margin[2] ymax += options.margin[3] # and calculate bbox's dimensions dx = xmax - xmin dy = ymax - ymin if eq_id is not None: # more then one reference, create new node <use> equation = XML.createElement('use') equation.setAttributeNS('xlink', 'xlink...
remove temporary files" extensions = ['.aux', '.log'] if not setup.options.frags_keeptex: extensions.append('.tex') if not setup.options.frags_keepdvi: extensions.append('.dvi') for ext in extensions: frags.remove_file(tmp_filename + ext)
identifier_body
svgfrags.py
sys.exit(1) elif not os.path.exists(input_txt): log.error("Rules file '%s' don't exist", input_txt) sys.exit(1) if not input_svg: log.error("Input SVG file not provided, use switch -i or --input") sys.exit(1) elif not os.path.exists(input_svg): log.error("Input SVG file '%s' don't exist", input_svg) s...
exitstatus = os.system("latex %s.tex > /dev/null" % tmp_filename) if exitstatus: log.error("LaTeX failed - error code %d; check log file '%s.log'", exitstatus, tmp_filename) sys.exit(2) else: log.error("Program 'latex' isn't avaialable.") sys.exit(3) else: log.info("File %s not changed, used ex...
tmp.write(line + "\n") tmp.close() if which('latex'):
random_line_split
svgfrags.py
self, filename): defs = self.document.getElementsByTagName('defs')[0] for element in self.flush_glyphs(): defs.appendChild(element) # save file f = open(filename, 'wb') if setup.options.prettyXML: f.write(self.document.toprettyxml()) else: f.write(self.document.toxml()) f.close() def main(args...
ave(
identifier_name
svgfrags.py
.path.getmtime(input_txt) ) atexit.register(cleanup, tmp_filename) if not os.path.exists(tmp_filename + ".dvi"): # 3. prepare LaTeX source tmp_lines = [ '\\batchmode', '\\documentclass{article}', '\\pagestyle{empty}' '\\begin{document}', ] for tex in repl_defs: tmp_lines.append(tex) # each Te...
ass # no scale
conditional_block
update_configuration_files.py
in this script. """ ROOT = get_shared_data_root() / "pipette" / "definitions" / "2" NOZZLE_LOCATION_CONFIGS = ["nozzle_offset", "nozzle_map"] def
(c: str) -> str: # Tiny helper function to convert to camelCase. config_name = c.split("_") if len(config_name) == 1: return config_name[0] return f"{config_name[0]}" + "".join(s.capitalize() for s in config_name[1::]) def list_configuration_keys() -> Tuple[List[str], Dict[int, str]]: """L...
_change_to_camel_case
identifier_name
update_configuration_files.py
in this script. """ ROOT = get_shared_data_root() / "pipette" / "definitions" / "2" NOZZLE_LOCATION_CONFIGS = ["nozzle_offset", "nozzle_map"] def _change_to_camel_case(c: str) -> str: # Tiny helper function to convert to camelCase. config_name = c.split("_") if len(config_name) == 1: return conf...
def build_nozzle_map( nozzle_offset: List[float], channels: PipetteChannelType ) -> Dict[str, List[float]]: Y_OFFSET = 9 X_OFFSET = -9 breakpoint() if channels == PipetteChannelType.SINGLE_CHANNEL: return {"A1": nozzle_offset} elif channels == PipetteChannelType.EIGHT_CHANNEL: ...
""" Recursively update the given dictionary to ensure no data is lost when updating. """ next_key = next(iter_of_configs, None) if next_key and isinstance(dict_to_update[next_key], dict): dict_to_update[next_key] = update( dict_to_update.get(next_key, {}), iter_of_configs, value_to_u...
identifier_body
update_configuration_files.py
in this script. """ ROOT = get_shared_data_root() / "pipette" / "definitions" / "2" NOZZLE_LOCATION_CONFIGS = ["nozzle_offset", "nozzle_map"] def _change_to_camel_case(c: str) -> str: # Tiny helper function to convert to camelCase. config_name = c.split("_") if len(config_name) == 1: return conf...
channels = list(PipetteChannelType)[int(input("Please select from above\n"))] version = PipetteVersionType.convert_from_float( float(check_from_version(input("Please
print(f"\t{row}")
conditional_block
update_configuration_files.py
print(f"\t{row}") tip_type = list(PipetteTipType)[ int(input("select the tip volume size to modify")) ] top_level_configuration.append(tip_type.name) lookup = {i: v for (i, v) in enumerate(base_model.__fields__)} config_list = [f"{i}: ...
"You selected nozzle_map to edit. If you wish to update the nozzle offset, enter it on the next line.\n" )
random_line_split
adversarial_semantic_dis_trainer.py
from pytorch3d.renderer import Textures from pytorch3d.renderer import ( look_at_view_transform, OpenGLPerspectiveCameras, PointLights, DirectionalLights, Materials, RasterizationSettings, MeshRenderer, MeshRasterizer, SoftPhongShader ) from pytorch3d.loss import mesh_laplac...
def train(self): # setting up dataloaders # https://stackoverflow.com/questions/51444059/how-to-iterate-over-two-dataloaders-simultaneously-using-pytorch generation_dataset = GenerationDataset(cfg, self.device) generation_loader = torch.utils.data.DataLoader(generation_dataset, b...
self.cfg = utils.load_config(cfg_path, "configs/default.yaml") self.device = torch.device("cuda:"+str(gpu_num)) self.batch_size = self.cfg["semantic_dis_training"]["batch_size"] self.total_training_iters = 2 self.num_batches_dis_train = 5 self.num_batches_gen_train = 5 s...
identifier_body
adversarial_semantic_dis_trainer.py
from pytorch3d.renderer import Textures from pytorch3d.renderer import ( look_at_view_transform, OpenGLPerspectiveCameras, PointLights, DirectionalLights, Materials, RasterizationSettings, MeshRenderer, MeshRasterizer, SoftPhongShader ) from pytorch3d.loss import mesh_laplac...
return loss_dict, deformed_mesh if __name__
loss_dict["semantic_dis_loss"] = torch.tensor(0).to(self.device)
conditional_block
adversarial_semantic_dis_trainer.py
from pytorch3d.renderer import Textures from pytorch3d.renderer import ( look_at_view_transform, OpenGLPerspectiveCameras, PointLights, DirectionalLights, Materials, RasterizationSettings, MeshRenderer, MeshRasterizer, SoftPhongShader ) from pytorch3d.loss import mesh_laplac...
dis_loss = F.binary_cross_entropy_with_logits(pred_logits_real, real_labels) + \ F.binary_cross_entropy_with_logits(pred_logits_fake, fake_labels) dis_loss.backward() dis_optimizer.step() continue ...
fake_labels = fake_labels_dist.sample((batch_size,1)).squeeze(2).to(self.device)
random_line_split
adversarial_semantic_dis_trainer.py
from pytorch3d.renderer import Textures from pytorch3d.renderer import ( look_at_view_transform, OpenGLPerspectiveCameras, PointLights, DirectionalLights, Materials, RasterizationSettings, MeshRenderer, MeshRasterizer, SoftPhongShader ) from pytorch3d.loss import mesh_laplac...
(self): # setting up dataloaders # https://stackoverflow.com/questions/51444059/how-to-iterate-over-two-dataloaders-simultaneously-using-pytorch generation_dataset = GenerationDataset(cfg, self.device) generation_loader = torch.utils.data.DataLoader(generation_dataset, batch_size=self.b...
train
identifier_name
endpoint.rs
place for PCI device.function: {:?}", s); }; let dev = with_context!(("invalid PCI device: {}", dev_s), u8::from_str_radix(dev_s, 16).map_err(|e| e.into()) )?; let fun = with_context!(("invalid PCI function: {}", fun_s), Ok(u8::from_str_radix(fun_s, 8)?) )?; ensure!(dev < 0x20, "invalid PCI device:...
(mut self) -> crate::AResult<()> { if let Some(ep) = self.ep.take() { ep.disable()?; } Ok(()) } } impl Drop for ScopedEnable { fn drop(&mut self) { if let Some(ep) = self.ep.take() { if let Err(e) = ep.disable() { error!("PCI {}: Failed to disable temporarily enabled device: {}", ep, e); } } ...
close
identifier_name
endpoint.rs
// short: 0.0, long: 1f.7 let (dev_s, fun_s) = if r.len() == 3 && r[1] == b'.' { (&s[0..1], &s[2..3]) } else if r.len() == 4 && r[2] == b'.' { (&s[0..2], &s[3..4]) } else { bail!("Couldn't find '.' in valid place for PCI device.function: {:?}", s); }; let dev = with_context!(("invalid PCI device:...
fn from_str(s: &str) -> Result<Self, Self::Err> { let r = s.as_bytes(); ensure!(r.len() <= 4, "String too long for PCI device.function: {:?}", s);
random_line_split
common.rs
(size: usize) -> Option<Vec<usize>> { if size == 0 { return Some(vec![]); } let mut peak_size = ALL_ONES >> size.leading_zeros(); let mut num_left = size; let mut sum_prev_peaks = 0; let mut peaks = vec![]; while peak_size != 0 { if num_left >= peak_size { peaks.p...
Some(peaks) } /// Calculates the positions of the (parent, sibling) of the node at the provided position. /// Returns an error if the pos provided would result in an underflow or overflow. pub fn family(pos: usize) -> Result<(usize, usize), MerkleMountainRangeError> { let (peak_map, height) = peak_map_height(...
{ // This happens, whenever the MMR is not valid, that is, all nodes are not // fully spawned. For example, in this case // 2 // / \ // 0 1 3 4 // is invalid, as it can be completed to form // 6 // / \ // 2 5 ...
conditional_block
common.rs
/// Returns an error if the pos provided would result in an underflow or overflow. pub fn family(pos: usize) -> Result<(usize, usize), MerkleMountainRangeError> { let (peak_map, height) = peak_map_height(pos); let peak = 1 << height; // Convert to i128 so that we don't over/underflow, and then we will cast...
peak_map_heights
identifier_name
common.rs
0 } pub fn hash_together<D: Digest + DomainDigest>(left: &[u8], right: &[u8]) -> Hash { D::new().chain_update(left).chain_update(right).finalize().to_vec() } /// The number of leaves in a MMR of the provided size. /// Example: on input 5 returns (2 + 1 + 1) as mmr state before adding 5 was /// 2 /// / \ ///...
assert_eq!(family_branch(3, 6), [(5, 4), (6, 2)]);
random_line_split
common.rs
(size: usize) -> Option<Vec<usize>> { if size == 0 { return Some(vec![]); } let mut peak_size = ALL_ONES >> size.leading_zeros(); let mut num_left = size; let mut sum_prev_peaks = 0; let mut peaks = vec![]; while peak_size != 0 { if num_left >= peak_size { peaks.p...
/// Is the node at this pos the "left" sibling of its parent? pub fn is_left_sibling(pos: usize) -> bool { let (peak_map, height) = peak_map_height(pos); let peak = 1 << height; (peak_map & peak) == 0 } pub fn hash_together<D: Digest + DomainDigest>(left: &[u8], right: &[u8]) -> Hash { D::new().chain...
{ if pos == 0 { return (0, 0); } let mut peak_size = ALL_ONES >> pos.leading_zeros(); let mut bitmap = 0; while peak_size != 0 { bitmap <<= 1; if pos >= peak_size { pos -= peak_size; bitmap |= 1; } peak_size >>= 1; } (bitmap, po...
identifier_body
search_log.go
FilePath) filePrefix := logFilePath[:len(logFilePath)-len(ext)] files, err := ioutil.ReadDir(logDir) if err != nil { return nil, err } walkFn := func(path string, info os.FileInfo) error { if info.IsDir() { return nil } // All rotated log files have the same prefix and extension with the original file ...
cursor -= size _, err := file.Seek(cursor, io.SeekStart) if err != nil { return nil, 0, ctx.Err() } chars := make([]byte, size) _, err = file.Read(chars) if err != nil { return nil, 0, ctx.Err() } lines = append(chars, lines...) // find first '\n' or '\r' for i := 0; i < len(chars)-1; i++ ...
}
random_line_split
search_log.go
return nil } if !strings.HasSuffix(path, ext) { return nil } if isCtxDone(ctx) { return ctx.Err() } // If we cannot open the file, we skip to search the file instead of returning // error and abort entire searching task. // TODO: do we need to return some warning to client? file, err := os.Op...
{ if logFilePath == "" { return nil, errors.New("empty log file location configuration") } var logFiles []logFile var skipFiles []*os.File logDir := filepath.Dir(logFilePath) ext := filepath.Ext(logFilePath) filePrefix := logFilePath[:len(logFilePath)-len(ext)] files, err := ioutil.ReadDir(logDir) if err !=...
identifier_body
search_log.go
) filePrefix := logFilePath[:len(logFilePath)-len(ext)] files, err := ioutil.ReadDir(logDir) if err != nil { return nil, err } walkFn := func(path string, info os.FileInfo) error { if info.IsDir() { return nil } // All rotated log files have the same prefix and extension with the original file if !str...
} return string(line), nil } const maxReadCacheSize = 1024 * 1024 * 16 // Read lines from the end of a file // endCursor initial value should be the file size func readLastLines(ctx context.Context, file *os.File, endCursor int64) ([]string, int, error) { var lines []byte var firstNonNewlinePos int var cursor =...
{ return "", err }
conditional_block
search_log.go
) filePrefix := logFilePath[:len(logFilePath)-len(ext)] files, err := ioutil.ReadDir(logDir) if err != nil { return nil, err } walkFn := func(path string, info os.FileInfo) error { if info.IsDir() { return nil } // All rotated log files have the same prefix and extension with the original file if !str...
(ctx context.Context, file *os.File, endCursor int64) ([]string, int, error) { var lines []byte var firstNonNewlinePos int var cursor = endCursor var size int64 = 256 for { // stop if we are at the begining // check it in the start to avoid read beyond the size if cursor <= 0 { break } // enlarge the...
readLastLines
identifier_name
lisp.go
_iid) { iid := a.instance_id if (iid == 0xffffff) { iid = -1 } return(fmt.Sprintf("[%d]%s", iid, a.address_string)) } return(a.address_string) } // // lisp_store_address // // Store and instance-ID and string representation of an IPv4 or IPv6 address // and store in Lisp_address format. // func (a *Lisp_addres...
// // lisp_count // // Increment stats counters. Either do it for an RLOC/RLE entry or for the // lisp_decap_stats map. Argument 'key-name' needs to be set if stats is nil. // func lisp_count(stats *Lisp_stats, key_name string, packet []byte) { if (stats == nil) { s, ok := lisp_decap_stats[key_name] if (!ok) { ...
random_line_split
lisp.go
_iid) { iid := a.instance_id if (iid == 0xffffff) { iid = -1 } return(fmt.Sprintf("[%d]%s", iid, a.address_string)) } return(a.address_string) } // // lisp_store_address // // Store and instance-ID and string representation of an IPv4 or IPv6 address // and store in Lisp_address format. // func (a *Lisp_addres...
if (a.instance_id != addr.instance_id) { return(false) } if (a.address.Equal(addr.address) == false) { return(false) } return(true) } // // lisp_more_specific // // Return true if the supplied address is more specific than the method // address. If the mask-lengths are the same, a true is returned. // func (...
{ return(false) }
conditional_block
lisp.go
with_iid) { iid := a.instance_id if (iid == 0xffffff) { iid = -1 } return(fmt.Sprintf("[%d]%s", iid, a.address_string)) } return(a.address_string) } // // lisp_store_address // // Store and instance-ID and string representation of an IPv4 or IPv6 address // and store in Lisp_address format. // func (a *Lisp_ad...
(command string) string { cmd := exec.Command(command) out, err := cmd.CombinedOutput() if (err != nil) { return("") } output := string(out) return(output[0:len(output)-1]) } // // lisp_read_file // // Read entire file into a string. // func lisp_read_file(filename string) string { fd, err := os.Open(filename...
lisp_command_output
identifier_name
lisp.go
_iid) { iid := a.instance_id if (iid == 0xffffff) { iid = -1 } return(fmt.Sprintf("[%d]%s", iid, a.address_string)) } return(a.address_string) } // // lisp_store_address // // Store and instance-ID and string representation of an IPv4 or IPv6 address // and store in Lisp_address format. // func (a *Lisp_addres...
// // lisp_is_ipv6 // // Return true if Lisp_address is IPv6. // func (a *Lisp_address) lisp_is_ipv6() bool { return((len(a.address) == 16)) } // // lisp_is_multicast // // Return true if Lisp_address is an IPv4 or IPv6 multicast group address. // func (a *Lisp_address) lisp_is_multicast() bool { if (a.lisp_is_ipv...
{ return((len(a.address) == 4)) }
identifier_body
FastSlamV2.py
o) def get_weight(self): return self.weight def normalize_weight(self, total_weight): self.weight = self.weight / total_weight def set_weight(self, new_weight): self.weight = new_weight def get_position(self): return self.X_robot def get_landmarkers(self): return self.Landmarkers def get_path(self...
actual_movement
identifier_name
FastSlamV2.py
(self, marker_id, Z): if self.Landmarkers[marker_id] == None: self.Landmarkers[marker_id] = KalmanFilter() return self.Landmarkers[marker_id] def particle_prediction(self, motion_model): #if the robot moves we just add the motion model to the previous pose to predict the particle position x = 0 y = 1...
self.read_move = np.array([0, 0, 0], dtype='float64').transpose() self.first_read = True
identifier_body
FastSlamV2.py
]=x_map[37]+1.00; y_map[40]=y_map[37]-1.10; x_map[39]=x_map[37]+2.65; y_map[39]=y_map[37]+0.35; x_map[38]=x_map[39]; y_map[38]=y_map[39]-2.66; y_map[36]=y_map[34]=y_map[35]=y_map[38]; x_map[36]=x_map[38]-1.46; x_map[34]=x_map[36]-1.96; x_map[35]=x_map[34]-1.46; y_map[32]=y_map[35]+0.28; x_map[32]=x_map[35]-0.68-0.28; ...
marker_line.set_xdata(x_f) marker_line.set_ydata(y_f) ax.draw_artist(ax.patch) ax.draw_artist(marker_line) fig.canvas.flush_events() def resample_particles(particles, updated_marker): # Returns a new set of particles obtained by performing stochastic universal sampling, according to the particle weights. # d...
if marker == None: x_f[i] = KEY_NUMBER + circle y_f[i] = KEY_NUMBER + circle i += 1 continue pose_m = marker.get_marker_position() x_m = pose_m[0] y_m = pose_m[1] std_m = marker.get_marker_covariance() x_std_m = std_m[0][0] y_std_m = std_m[1][1] x_f[i] = x_m + x_std_m * np.cos(circle) y_f[i]...
conditional_block
FastSlamV2.py
NUMBER_MARKERS plt.ion() plt.xlim(-10, 20) plt.ylim(-20, 10) plt.xlabel('X', fontsize=10) # X axis label plt.ylabel('Y', fontsize=10) # Y axis label plt.title('FastSlam 2.0') #plt.legend() plt.grid(True) # Enabling gridding def drawing_plot(particles): Max = 0 Max_id = 0 for i in range(NUMBER_PARTICLES): if...
self.X_ = np.array([X_robot[x] + Z[d]*np.cos(angle), X_robot[y] + Z[d]*np.sin(angle)], dtype='float64').transpose() # first landmark position self.compute_G(X_robot)
random_line_split
hellweg.py
), 'title': _report_title(report.reportType, 'BeamReportType', beam_info), 'z_label': 'Number of Particles', 'summaryData': _summary_text(run_dir), }) def extract_parameter_report(report, run_dir): s = solver.BeamSolver( os.path.join(str(run_dir), HELLWEG_INI_FILE), os....
(models): # BEAM SPH2D 0.564 -15 5 NORM2D 0.30 0.0000001 90 180 beam_def = models.beam.beamDefinition if beam_def == 'transverse_longitude': return 'BEAM {} {}'.format(_generate_transverse_dist(models), _generate_longitude_dist(models)) if beam_def == 'cst_pit': return 'BEAM CST_PIT {} {...
_generate_beam
identifier_name
hellweg.py
), 'title': _report_title(report.reportType, 'BeamReportType', beam_info), 'z_label': 'Number of Particles', 'summaryData': _summary_text(run_dir), }) def extract_parameter_report(report, run_dir): s = solver.BeamSolver( os.path.join(str(run_dir), HELLWEG_INI_FILE), os....
def lib_files(data, source_lib): return template_common.filename_to_path(_simulation_files(data), source_lib) def get_simulation_frame(run_dir, data, model_data): frame_index = int(data['frameIndex']) if data['modelName'] == 'beamAnimation': args = template_common.parse_animation_args( ...
if data['method'] == 'compute_particle_ranges': return template_common.compute_field_range(data, _compute_range_across_files) assert False, 'unknown application data method: {}'.format(data['method'])
identifier_body
hellweg.py
def extract_beam_histrogram(report, run_dir, frame): beam_info = hellweg_dump_reader.beam_info(_dump_file(run_dir), frame) points = hellweg_dump_reader.get_points(beam_info, report.reportType) hist, edges = np.histogram(points, template_common.histogram_bins(report.histogramBins)) return { 'titl...
'error': _parse_error_message(run_dir) }
random_line_split
hellweg.py
format(data['method']) def lib_files(data, source_lib): return template_common.filename_to_path(_simulation_files(data), source_lib) def get_simulation_frame(run_dir, data, model_data): frame_index = int(data['frameIndex']) if data['modelName'] == 'beamAnimation': args = template_common.parse_an...
v['latticeCommands'] = _generate_lattice(data['models'])
conditional_block
lib.rs
/// Other, one-off errors, with reasoning provided as a string Other(&'static str), } impl From<io::Error> for Error { fn from(err: io::Error) -> Self { Error::IO(err) } } impl From<Error> for io::Error { fn from(err: Error) -> Self { match err { Error::IO(err) => err, ...
fn is_py3(&self) -> Result<(), Error> { if self.ver != Version::Three { Err(Error::Python3Only) } else { Ok(()) } } /// Create a `PythonConfig` that uses the interpreter at the path `interpreter`. /// /// This fails if the path cannot be represented...
{ PythonConfig { cmdr, ver } }
identifier_body
lib.rs
'") })?; semver::Version::parse(ver).map_err(|_| other_err("unable to parse semver")) }) .map_err(From::from) } fn script(&self, lines: &[&str]) -> PyResult<String> { self.cmdr .commands(&["-c", &build_script(lines)]) .map_...
include_paths_same
identifier_name
lib.rs
/// Other, one-off errors, with reasoning provided as a string Other(&'static str), } impl From<io::Error> for Error { fn from(err: io::Error) -> Self { Error::IO(err) } } impl From<Error> for io::Error { fn from(err: Error) -> Self { match err { Error::IO(err) => err, ...
/// The result type denotes that this function /// is only available when interfacing a Python 3 /// interpreter. /// /// It's the same as the normal [`PyResult`](type.PyResult.html) /// used throughout this module, but it's just a little /// type hint. pub type Py3Only<T> = Result<T, Error>; #[inline] fn other_err(wh...
/// an [`Error`](enum.Error.html). pub type PyResult<T> = Result<T, Error>;
random_line_split
forward.go
type PortMappings struct { // Name of the container - May be left empty in YAML config file Name string `yaml:"name,omitempty"` // Protocol should be "tcp" or "udp" Protocol string `yaml:"protocol"` // Ports is a mapping of host ports as keys to container ports as values Ports map[string]int `yaml:",inline"` } /...
"gopkg.in/yaml.v2" ) // PortMappings contains information for mapping ports from a host to a container
random_line_split
forward.go
each container, makes sure an equal number of Host and Container Ports are provided // * Makes sure no Host port is used more than once. func (c Config) Validate() (bool, error) { // First do some sanity checks hostPorts := map[string]interface{}{} for container, portForwards := range c.Forwards { for _, portFor...
Watch
identifier_name
forward.go
.Errorf("No ports provided for container %s", container) } for hPort := range portForward.Ports { _, err := strconv.Atoi(hPort) if err != nil { return false, fmt.Errorf("Invalid port %s provided for container %s", hPort, container) } // Can only forward a port from the host to one container,...
{ handler := func(i interface{}) { var container string var message string var context map[string]interface{} data := i.(map[string]interface{}) metadata := data["metadata"].(map[string]interface{}) tmp, ok := metadata["context"] if ok { context = tmp.(map[string]interface{}) } tmp, ok = context...
identifier_body
forward.go
Mappings() PortMappings { p := PortMappings{} p.Ports = map[string]int{} return p } // Config represents the Config File format that can be stored in YAML format type Config struct { Forwards map[string][]PortMappings `yaml:",inline"` } // NewConfig creates and returns initialized config func NewConfig() Config ...
err = yaml.Unmarshal(yml, &config) return config, err } // Validate checks a config for correctness. Currently provides the following checks: // * For each container, makes sure an equal number of Host and Container Ports are provided // * Makes sure no Host port is used more than once. func (c Config) Validate() (...
{ return config, err }
conditional_block
login.py
return disable_cache(response) return aiohttp.web.Response( status=302, headers={ "Location": HAKA_OIDC_ENDPOINT( endpoint=str(setd["auth_endpoint_url"]), oidc=str(setd["keystone_oidc_provider"]), origin=str(setd["set_origin_address"]), ...
random_line_split
login.py
["has_trust"]: response = aiohttp.web.FileResponse(str(setd["static_directory"]) + "/login.html") return disable_cache(response) return aiohttp.web.Response( status=302, headers={ "Location": HAKA_OIDC_ENDPOINT( endpoint=str(setd["auth_endpoint_url"]), ...
session["projects"] = dict( filter(lambda val: not val[1]["tainted"], session["projects"].items()) )
conditional_block
login.py
} :: {time.ctime()}" ) # Try getting the token id from headers if "X-Auth-Token" in request.headers and unscoped is None: unscoped = request.headers["X-Auth-Token"] log.debug( "Got OS token in http header " f"from address {request.remote} :: {time.ctime()}" ...
"""Properly kill the session for the user.""" log = request.app["Log"] client = request.app["api_client"] if not setd["set_session_devmode"]: try: session = await aiohttp_session.get_session(request) log.info(f"Killing session {session.identity}") for project in s...
identifier_body
login.py
) except KeyError as e: request.app["Log"].error(f"Issuer {oidc_session['iss']} not found: {e}.") raise aiohttp.web.HTTPBadRequest(reason="Token issuer not found.") except OidcServiceError as e: # This exception is raised if RPHandler encounters an error due to: # 1. "code" is w...
( request: aiohttp.web.Request, ) -> typing.Union[aiohttp.web.Response, aiohttp.web.FileResponse]: """Create new session cookie for the user.""" response: typing.Union[aiohttp.web.Response, aiohttp.web.FileResponse] response = aiohttp.web.Response(status=302, reason="Redirection to login") # Add a ...
handle_login
identifier_name
docker.go
(g *g) dockerConnect() (*docker, error) { g.log.Info("connecting to docker engine") cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) if err != nil { return nil, errors.Join(ErrEnvClient, err) } g.log.Info("connected to docker engine") return &docker{client: cli, log: ...
} return resp, err } func (d *docker) waitForContainerNetwork(ctx context.Context, id string, ports NamedPorts) (*Container, error) { d.log.Infow("waiting for container network", "container", id) tick := time.NewTicker(time.Millisecond * 250) defer tick.Stop() for { select { case <-ctx.Done(): return n...
resp, err := d.createContainer(ctx, image, ports, cfg) if err != nil { return nil, fmt.Errorf("can't create container: %w", err)
random_line_split
docker.go
); err == nil { sidecarChan <- sc.ID } }() return sidecarChan } func (d *docker) prepareContainer( ctx context.Context, image string, ports NamedPorts, cfg *Options, ) (*container.CreateResponse, error) { pullImage := true if cfg.UseLocalImagesFirst { isExisting, err := d.isExistingLocalImage(ctx, im...
isDeletionAlreadyInProgessError
identifier_name
docker.go
(g *g) dockerConnect() (*docker, error) { g.log.Info("connecting to docker engine") cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) if err != nil { return nil, errors.Join(ErrEnvClient, err) } g.log.Info("connected to docker engine") return &docker{client: cli, log: ...
sidecarChan := d.setupContainerCleanup(resp.ID, cfg) err = d.client.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}) if err != nil { return nil, fmt.Errorf("can't start container %s: %w", resp.ID, err) } container, err := d.waitForContainerNetwork(ctx, resp.ID, ports) if err != nil { return nil, ...
{ if cfg.Reuse { container, ok, err := d.findReusableContainer(ctx, image, ports, cfg) if err != nil { return nil, err } if ok { d.log.Info("re-using container") return container, nil } } d.log.Info("starting container") resp, err := d.prepareContainer(ctx, image, ports, cfg) if err != nil { ...
identifier_body
docker.go
(g *g) dockerConnect() (*docker, error) { g.log.Info("connecting to docker engine") cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) if err != nil { return nil, errors.Join(ErrEnvClient, err) } g.log.Info("connected to docker engine") return &docker{client: cli, log: ...
matches := duplicateContainerRegexp.FindStringSubmatch(err.Error()) if len(matches) == 2 { d.log.Infow("duplicate container found, stopping", "container", matches[1]) err = d.client.ContainerRemove(ctx, matches[1], types.ContainerRemoveOptions{ Force: true, }) if err != nil { return nil, fmt.Errorf("...
{ return &resp, nil }
conditional_block
amqp_transport.py
max permissible number of channels per connection. Defaults to 128. """ __slots__ = [ 'host', 'port', 'secure', 'vhost', 'reconnect_attempts', 'retry_delay', 'timeout', 'heartbeat_timeout', 'blocked_connection_timeout', 'creds' ] def __init__(self, host='127.0.0.1', port='...
self.connection_params.credentials = self.credentials else: self.credentials = self.connection_params.credentials # So that connections do not go zombie atexit.register(self._graceful_shutdown) @property def channel(self): return self._channel @prop...
random_line_split
amqp_transport.py
"""Constructor.""" self.host = host self.port = port self.secure = secure self.vhost = vhost self.reconnect_attempts = reconnect_attempts self.retry_delay = retry_delay self.timeout = timeout self.blocked_connection_timeout = blocked_connection_tim...
return False
conditional_block
amqp_transport.py
Args: username (str): The username. password (str): The password (Basic Authentication). """ __slots__ = ['username', 'password'] def __init__(self, username='guest', password='guest'): """Constructor.""" super(Credentials, self).__init__(username=username, password=pas...
CONNECTION_TIMEOUT_SEC = 5 def __init__(self, host='127.0.0.1', port='5672', exchange='amq.topic'): self._connection = None self._channel = None self._closing = False self.logger = create_logger(self.__class__.__name__) self._exchange = 'amq.topic' self._host = host ...
identifier_body
amqp_transport.py
(pika.BasicProperties): """Message Properties/Attribures used for sending and receiving messages. Args: content_type (str): content_encoding (str): timestamp (str): """ def __init__(self, content_type=None, content_encoding=None, timestamp=None, correlation_id=...
MessageProperties
identifier_name
path.rs
.split_terminator(DELIMITER) .map(|s| PathPart(s.to_string())) .collect(), } } /// For use when receiving a path from a filesystem directly, not /// when building a path. Uses the standard library's path splitting /// implementation to separate in...
{} impl FileConverter { /// Creates a filesystem `PathBuf` location by using the standard library's /// `PathBuf` building implementation appropriate for the current /// platform. pub fn convert(object_store_path: &ObjectStorePath) -> PathBuf { object_store_path.parts.iter().map(|p| &p.0).coll...
FileConverter
identifier_name
path.rs
parts: path .iter() .flat_map(|s| s.to_os_string().into_string().map(PathPart)) .collect(), } } /// Add a part to the end of the path, encoding any restricted characters. pub fn push(&mut self, part: impl Into<String>) { let part =...
} #[test]
random_line_split