file_name
large_string
prefix
large_string
suffix
large_string
middle
large_string
fim_type
large_string
scaledobject_controller.go
scaledObject *kedav1alpha1.ScaledObject) (string, error) { // Check scale target Name is specified if scaledObject.Spec.ScaleTargetRef.Name == "" { err := fmt.Errorf("ScaledObject.spec.scaleTargetRef.name is missing") return "ScaledObject doesn't have correct scaleTargetRef specification", err } // Check the ...
scaledObjectGenerationChanged
identifier_name
create_secret.go
a secret using specified subcommand.", Run: cmdutil.DefaultSubCommandRun(errOut), } cmd.AddCommand(NewCmdCreateSecretDockerRegistry(f, cmdOut)) cmd.AddCommand(NewCmdCreateSecretTLS(f, cmdOut)) cmd.AddCommand(NewCmdCreateSecretGeneric(f, cmdOut)) return cmd } var ( secretLong = templates.LongDesc(i18n.T(` ...
} // CreateSecretGeneric is the implementation of the create secret generic command func CreateSecretGeneric(f cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error { name, err := NameFromCommandArgs(cmd, args) if err != nil { return err } var generator kubectl.StructuredGenerator switch ...
{ cmd := &cobra.Command{ Use: "generic NAME [--type=string] [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run]", Short: i18n.T("Create a secret from a local file, directory or literal value"), Long: secretLong, Example: secretExample, Run: func(cmd *cobra.Command, args []string) { ...
identifier_body
create_secret.go
&cobra.Command{ Use: "generic NAME [--type=string] [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run]", Short: i18n.T("Create a secret from a local file, directory or literal value"), Long: secretLong, Example: secretExample, Run: func(cmd *cobra.Command, args []string) { err := ...
{ if value := cmdutil.GetFlagString(cmd, requiredFlag); len(value) == 0 { return cmdutil.UsageError(cmd, "flag %s is required", requiredFlag) } }
conditional_block
create_secret.go
a secret using specified subcommand.", Run: cmdutil.DefaultSubCommandRun(errOut), } cmd.AddCommand(NewCmdCreateSecretDockerRegistry(f, cmdOut)) cmd.AddCommand(NewCmdCreateSecretTLS(f, cmdOut)) cmd.AddCommand(NewCmdCreateSecretGeneric(f, cmdOut)) return cmd } var ( secretLong = templates.LongDesc(i18n.T(` ...
Use: "generic NAME [--type=string] [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run]", Short: i18n.T("Create a secret from a local file, directory or literal value"), Long: secretLong, Example: secretExample, Run: func(cmd *cobra.Command, args []string) { err := CreateSecretGener...
) // NewCmdCreateSecretGeneric is a command to create generic secrets from files, directories, or literal values func NewCmdCreateSecretGeneric(f cmdutil.Factory, cmdOut io.Writer) *cobra.Command { cmd := &cobra.Command{
random_line_split
create_secret.go
secret using specified subcommand.", Run: cmdutil.DefaultSubCommandRun(errOut), } cmd.AddCommand(NewCmdCreateSecretDockerRegistry(f, cmdOut)) cmd.AddCommand(NewCmdCreateSecretTLS(f, cmdOut)) cmd.AddCommand(NewCmdCreateSecretGeneric(f, cmdOut)) return cmd } var ( secretLong = templates.LongDesc(i18n.T(` C...
(f cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error { name, err := NameFromCommandArgs(cmd, args) if err != nil { return err } var generator kubectl.StructuredGenerator switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName { case cmdutil.SecretV1GeneratorName:...
CreateSecretGeneric
identifier_name
utils.js
.dispose() $bitmap.dispose() `.replace(/\r?\n|\r|\u2028|\u2029/g, "\r\n"); execFileSync("powershell.exe", [ "-NoLogo", "-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-Command", "-", ], {input, encoding: "utf8", windowsHide: true}); break; default: throw ...
flags){ src = (src || "").toString(); if(!src) return null; const matchEnd = src.match(/\/([gimuy]*)$/); // Input is a "complete" regular expression if(matchEnd && /^\//.test(src)) return new RegExp( src.replace(/^\/|\/([gimuy]*)$/gi, ""), flags != null ? flags : matchEnd[1] ); return...
romString(src,
identifier_name
utils.js
context.dispose() $bitmap.dispose() `.replace(/\r?\n|\r|\u2028|\u2029/g, "\r\n"); execFileSync("powershell.exe", [ "-NoLogo", "-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-Command", "-", ], {input, encoding: "utf8", windowsHide: true}); break; default: ...
matched.push(str); } } return matched.join(POSIX ? "/" : "\\"); }, /** * Return the width of the scrollbars being displayed by this user's OS/device. * * @return {Number} */ getScrollbarWidth(){ const el = document.createElement("div"); const {style} = el; const size = 120; ...
nst POSIX = paths[0].indexOf("/") !== -1; let matched = []; // Spare ourselves the trouble if there's only one path if(1 === paths.length){ matched = (paths[0].replace(/[\\/]+$/, "")).split(/[\\/]/g); matched.pop(); } // Otherwise, comb each array else{ const rows = paths.map(d => d.split(/...
identifier_body
utils.js
the newly-created object. * @return {Element} */ New(nodeType, obj){ function absorb(a, b){ for(const i in b) if(Object(a[i]) === a[i] && Object(b[i]) === b[i]) absorb(a[i], b[i]); else a[i] = b[i]; } const node = document.createElement(nodeType); if(obj) absorb(node, obj); return node; ...
// Normalise newlines and strip leading or trailing blank lines const chunk = String.raw.call(null, input, ...args) .replace(/\r(\n?)/g, "$1")
random_line_split
HFIF_RunTime.py
result*np.sign(xValue) def getNormInduData(xData,pclMatrix): xShape=len(xData) normInduData=np.zeros(xShape) for j in range(xShape): arrPercentile=pclMatrix[:,j] normInduData[j]=calPercentile(xData[j],arrPercentile) return normInduData def btstr(btpara): return str(btpa...
def myLoss(y_true, y_pred): #return backend.mean(backend.square((y_pred - y_true)*y_true), axis=-1) return backend.mean(backend.abs((y_pred - y_true)*y_true), axis=-1) def myMetric(y_true, y_pred): return backend.mean(y_pred*y_true, axis=-1)*10 def getCfgFareFactor(ffPath): cfgFile=os.path.joi...
random_line_split
HFIF_RunTime.py
result*np.sign(xValue) def getNormInduData(xData,pclMatrix): xShape=len(xData) normInduData=np.zeros(xShape) for j in range(xShape): arrPercentile=pclMatrix[:,j] normInduData[j]=calPercentile(xData[j],arrPercentile) return normInduData def btstr(btpara): return str(btpa...
stPm)) if isPush and ((intNTime>93100 and intNTime<113000) or (intNTime>130100 and intNTime<150000)): sql.UpdateAllFF() finally: lock.release() def ReceiveQuote(quoteEvent): global dictQuote,lock dt =quoteEvent.data lock.acquire() try: code=byt...
end(ff.pm) print(intNTime,*tuple(li
conditional_block
HFIF_RunTime.py
result*np.sign(xValue) def getNormInduData(xData,pclMatrix): xShape=len(xData) normInduData=np.zeros(xShape) for j in range(xShape): arrPercentile=pclMatrix[:,j] normInduData[j]=calPercentile(xData[j],arrPercentile) return normInduData def btstr(btpara): return str(btpa...
self.__active = True self.__thread.start() def AddEventListener(self, type_, handler): try: handlerList = self.__handlers[type_] except KeyError: handlerList = [] self.__handlers[type_] = handlerList if handler not in handlerList: ...
def __init__(self): self.__eventQueue = Queue() self.__active = False self.__thread = Thread(target = self.__Run) self.__handlers = {} def __Run(self): while self.__active == True: try: event = self.__eventQueue.get(block = True, timeout ...
identifier_body
HFIF_RunTime.py
result*np.sign(xValue) def getNormInduData(xData,pclMatrix): xShape=len(xData) normInduData=np.zeros(xShape) for j in range(xShape): arrPercentile=pclMatrix[:,j] normInduData[j]=calPercentile(xData[j],arrPercentile) return normInduData def btstr(btpara): return str(btpa...
self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="UTF-8") self.conn.autocommit(True) self.cur = self.conn.cursor() if not self.cur: return False else: return True except: ...
identifier_name
utils.py
return dt.replace(tzinfo=timezone('UTC')).astimezone(timezone(tz)) def getWeekDays(dt): if not dt.tzinfo: dt = dt.replace(tzinfo=timezone(TIMEZONE)) else: dt = dt.astimezone(timezone(TIMEZONE)) # weekday of Monday is 0 monday = dt - timedelta(days=dt.weekday()) weekdays = [monday] ...
user = models.user.objects.filter(id=id).first() cache = {} if not user else json.loads(user.cache) return cache.get(name, default) def userCacheSet(id, name, value): user = models.user.objects.filter(id=id).first() if not user: models.user.create(id=id, cache=json.dumps({})) user = mode...
def getBookingDateFromEvent(event, fmt = '%Y-%m-%d %H:%M'): start = datetime.strptime(event['start']['dateTime'][:19], "%Y-%m-%dT%H:%M:%S") bookingDatetime = start.strftime(fmt) return bookingDatetime def userCacheGet(id, name, default=None):
random_line_split
utils.py
return dt.replace(tzinfo=timezone('UTC')).astimezone(timezone(tz)) def getWeekDays(dt): if not dt.tzinfo: dt = dt.replace(tzinfo=timezone(TIMEZONE)) else: dt = dt.astimezone(timezone(TIMEZONE)) # weekday of Monday is 0 monday = dt - timedelta(days=dt.weekday()) weekdays = [monday] ...
# get: name, default(nullable) # set: nameValues(dict), minutes(nullable) def cache(*args): if isinstance(args[0], dict): # set nameValues = args[0] minutes = listGet(args, 1) for k, v in nameValues.items(): item = models.cache.objects.filter(name=k).first() ...
return dc.get(name, default)
conditional_block
utils.py
return dt.replace(tzinfo=timezone('UTC')).astimezone(timezone(tz)) def getWeekDays(dt): if not dt.tzinfo: dt = dt.replace(tzinfo=timezone(TIMEZONE)) else: dt = dt.astimezone(timezone(TIMEZONE)) # weekday of Monday is 0 monday = dt - timedelta(days=dt.weekday()) weekdays = [monday] ...
(ts): return datetime.fromtimestamp(ts) gcService = None def getGoogleCalendarService(): global gcService if not gcService: import httplib2 from apiclient import discovery from get_google_calendar_credentials import get_google_calendar_credentials credentials = get_google_cal...
toDatetime
identifier_name
utils.py
return dt.replace(tzinfo=timezone('UTC')).astimezone(timezone(tz)) def getWeekDays(dt): if not dt.tzinfo: dt = dt.replace(tzinfo=timezone(TIMEZONE)) else: dt = dt.astimezone(timezone(TIMEZONE)) # weekday of Monday is 0 monday = dt - timedelta(days=dt.weekday()) weekdays = [monday] ...
def toTimestamp(dt): return int(time.mktime(dt.timetuple())) def toDatetime(ts): return datetime.fromtimestamp(ts) gcService = None def getGoogleCalendarService(): global gcService if not gcService: import httplib2 from apiclient import discovery from get_google_calendar_creden...
month = dt.month - 1 + months year = dt.year + month // 12 month = month % 12 + 1 day = min(dt.day,calendar.monthrange(year,month)[1]) return dt.replace(year=year, month = month,day=day)
identifier_body
peers_tests.rs
, "`ulimit -n` is too low: {}", n) } let ctx = MmCtxBuilder::new().with_conf(conf).into_mm_arc(); unwrap!(ctx.log.thread_gravity_on()); let seed = fomat!((small_rng().next_u64())); unwrap!(ctx.secp256k1_key_pair.pin(unwrap!(key_pair_from_seed(&seed)))); if let Some(seednodes) = ctx.conf["seed...
.direct_chunks .load(Ordering::Relaxed) > 0)); let start = now_float();
random_line_split
peers_tests.rs
lim_cur as u32) } else { None } } #[cfg(not(any(target_os = "macos", target_os = "linux")))] fn ulimit_n() -> Option<u32> { None } async fn peer(conf: Json, port: u16) -> MmArc { if let Some(n) = ulimit_n() { assert!(n > 2000, "`ulimit -n` is too low: {}", n) } let ctx = MmCtxBuil...
/// Using a minimal one second HTTP fallback which should happen before the DHT kicks in. #[cfg(feature = "native")] pub fn peers_http_fallback_recv() { let ctx = MmCtxBuilder::new().into_mm_arc(); let addr = SocketAddr::new(unwrap!("127.0.0.1".parse()), 30204); let server = unwrap!(super::http_fallback::ne...
use std::ptr::null; common::executor::spawn(async move { peers_dht().await; unsafe { call_back(cb_id, null(), 0) } }) }
identifier_body
peers_tests.rs
lim_cur as u32) } else { None } } #[cfg(not(any(target_os = "macos", target_os = "linux")))] fn ulimit_n() -> Option<u32> { None } async fn peer(conf: Json, port: u16) -> MmArc { if let Some(n) = ulimit_n() { assert!(n > 2000, "`ulimit -n` is too low: {}", n) } let ctx = MmCtxBuil...
// NB: Still need the DHT enabled in order for the pings to work. let alice = block_on(peer(json! ({"dht": "on"}), 2121)); let bob = block_on(peer(json! ({"dht": "on"}), 2122)); let bob_id = unwrap!(bob.public_id()); // Bob isn't a friend yet. let alice_pctx = unwrap!(super::PeersContext::from_...
return; }
conditional_block
peers_tests.rs
_cur as u32) } else { None } } #[cfg(not(any(target_os = "macos", target_os = "linux")))] fn ulimit_n() -> Option<u32> { None } async fn peer(conf: Json, port: u16) -> MmArc { if let Some(n) = ulimit_n() { assert!(n > 2000, "`ulimit -n` is too low: {}", n) } let ctx = MmCtxBuilder...
(mm: MmArc) { mm.stop(); if let Err(err) = wait_for_log_re(&mm, 1., "delete_dugout finished!").await { // NB: We want to know if/when the `peers` destruction doesn't happen, but we don't want to panic about it. pintln!((err)) } } async fn peers_exchange(conf: Json) { let fallback_on = c...
destruction_check
identifier_name
fbb_churn_eval_ensemb_alberto.py
).write.save(path, format='parquet', mode='overwrite') ## Reading the Extra Features dfExtraFeat = spark.read.parquet('/data/udf/vf_es/churn/extra_feats_mod/extra_feats/year={}/month={}/day={}' .format(int(trcycle_ini[0:4]), int(trcycle_ini[4:6]), int(trcycle_ini[6:8]))...
for fimp in feat_importance: print "[Info Main FbbChurn] Imp feat " + str(fimp[0]) + ": " + str(fimp[1])
random_line_split
fbb_churn_eval_ensemb_alberto.py
SPARK_COMMON_OPTS += " --conf spark.dynamicAllocation.minExecutors=%s" % (MIN_N_EXECUTORS) SPARK_COMMON_OPTS += " --conf spark.executor.cores=%s" % (N_CORES_EXECUTOR) SPARK_COMMON_OPTS += " --conf spark.dynamicAllocation.executorIdleTimeout=%s" % (EXECUTOR_IDLE_MAX_TIME) # SPARK_COMMON_OPTS += " --conf ...
MAX_N_EXECUTORS = max_n_executors MIN_N_EXECUTORS = min_n_executors N_CORES_EXECUTOR = n_cores EXECUTOR_IDLE_MAX_TIME = 120 EXECUTOR_MEMORY = executor_memory DRIVER_MEMORY = driver_memory N_CORES_DRIVER = 1 MEMORY_OVERHEAD = N_CORES_EXECUTOR * 2048 QUEUE = "root.BDPtenants.es.medium" ...
identifier_body
fbb_churn_eval_ensemb_alberto.py
) SPARK_COMMON_OPTS += " --conf spark.shuffle.service.enabled = true" BDA_ENV = os.environ.get('BDA_USER_HOME', '') # Attach bda-core-ra codebase SPARK_COMMON_OPTS+=" --files {}/scripts/properties/red_agent/nodes.properties,{}/scripts/properties/red_agent/nodes-de.properties,{}/scripts/properties/red_...
print "[Info Main FbbChurn] Non-informative feat: " + f
conditional_block
fbb_churn_eval_ensemb_alberto.py
(min_n_executors = 1, max_n_executors = 15, n_cores = 8, executor_memory = "16g", driver_memory="8g", app_name = "Python app", driver_overhead="1g", executor_overhead='3g'): MAX_N_EXECUTORS = max_n_executors MIN_N_EXECUTORS = min_n_executors N_CORES_EXECUTOR = n_cores EXECUTOR_IDLE_M...
setting_bdp
identifier_name
feature_extraction.py
1), detect valleys (local minima) instead of peaks. show : bool, optional (default = False) if True (1), plot data in matplotlib figure. ax : a matplotlib.axes.Axes instance, optional (default = None). Returns ------- ind : 1D array_like indeces of the peaks in `x`. References ...
run_experiment
identifier_name
feature_extraction.py
edge='rising', kpsh=False, valley=False, show=False, ax=None): """Detect peaks in data based on their amplitude and other features. Parameters ---------- x : 1D array_like data. mph : {None, number}, optional (default = None) detect peaks that are greater than mini...
# remove the small peaks and sort back the indices by their occurrence ind = np.sort(ind[~idel]) if show: if indnan.size: x[indnan] = np.nan if valley: x = -x _plot(x, mph, mpd, threshold, edge, valley, ax, ind) return ind def get_values(y_val...
idel = idel | (ind >= ind[i] - mpd) & (ind <= ind[i] + mpd) \ & (x[ind[i]] > x[ind] if kpsh else True) idel[i] = 0 # Keep current peak
conditional_block
feature_extraction.py
edge='rising', kpsh=False, valley=False, show=False, ax=None): """Detect peaks in data based on their amplitude and other features. Parameters ---------- x : 1D array_like data. mph : {None, number}, optional (default = None) detect peaks that are greater than mini...
if ind.size and ind[-1] == x.size - 1: ind = ind[:-1] # remove peaks < minimum peak height if ind.size and mph is not None: ind = ind[x[ind] >= mph] # remove peaks - neighbors < threshold if ind.size and threshold > 0: dx = np.min(np.vstack([x[ind] - x[ind - 1], x[ind] - x[in...
if ind.size and ind[0] == 0: ind = ind[1:]
random_line_split
feature_extraction.py
edge='rising', kpsh=False, valley=False, show=False, ax=None):
valley : bool, optional (default = False) if True (1), detect valleys (local minima) instead of peaks. show : bool, optional (default = False) if True (1), plot data in matplotlib figure. ax : a matplotlib.axes.Axes instance, optional (default = None). Returns ------- ind : 1D a...
"""Detect peaks in data based on their amplitude and other features. Parameters ---------- x : 1D array_like data. mph : {None, number}, optional (default = None) detect peaks that are greater than minimum peak height. mpd : positive integer, optional (default = 1) detect pe...
identifier_body
main.js
entries.forEach(function(entry) { graph.addNode({ id: entry.name, label: entry.name, x: entry.name.charCodeAt(0), // Positions are refined below y: entry.name.charCodeAt(1), size: 5 + Math.pow(entry.students ? entry.students.length : 0, 0.8) // TODO: Assign node colors i...
outMap[name].forEach(function(student) { newHTML += '<li>' + student + '</li>'; }); newHTML += '</ul>'; } $('#info').innerHTML = newHTML; $('#info').style.display = 'block'; }; var filterByCourse = function(course) { if ($('#filter').value !== course) { $('#filter').value = cou...
}); newHTML += '</ul>'; } if (outMap[name] && outMap[name].length) { newHTML += '<p>Students:<ul>';
random_line_split
main.js
entries.forEach(function(entry) { graph.addNode({ id: entry.name, label: entry.name, x: entry.name.charCodeAt(0), // Positions are refined below y: entry.name.charCodeAt(1), size: 5 + Math.pow(entry.students ? entry.students.length : 0, 0.8) // TODO: Assign node colors i...
else { activeFilter = ''; s.graph.edges().forEach(function(edge) { var idParts = edge.id.split(':'); edge.color = classToColor(idParts[2]); edge.size = 1; }); s.refresh(); $('#layout-wrapper').style.display = 'inline'; $('#search-wrapper').style.display = 'inline'; ...
{ activeFilter = course; s.graph.edges().forEach(function(edge) { var idParts = edge.id.split(':'); if (idParts[2] !== course) { edge.color = 'transparent'; edge.size = 1; } else { edge.color = classToColor(idParts[2]); edge.size = 1; } }); ...
conditional_block
Trade.go
_service_district,omitempty"` // o2oServiceTown O2oServiceTown string `json:"o2o_service_town,omitempty" xml:"o2o_service_town,omitempty"` // o2oServiceAddress O2oServiceAddress string `json:"o2o_service_address,omitempty" xml:"o2o_service_address,omitempty"` // o2oSt...
// 同城购订单source
random_line_split
asistencia.component.ts
this.showContents = false } }) this.searchCriteria['value']= `${this.searchCriteria['start']} - ${this.searchCriteria['end']}` this._dateRangeOptions.settings = { autoUpdateInput: true, locale: { format: 'YYYY-MM-DD' } } this.loadDeps() moment.locale('es-MX') } ...
( time ){ let td = moment(time) if( td < moment(`${moment().format('YYYY-MM-DD')} 05:00:00`)){ return td.add(1, 'days') }else{ return td } } showDom(rac, date, block){ if(this.checkSet(rac, date, block)){ this.shownDom[`${rac}_${date}_${block}`] = undefined }else{ th...
timeDateXform
identifier_name
asistencia.component.ts
this.showContents = false } }) this.searchCriteria['value']= `${this.searchCriteria['start']} - ${this.searchCriteria['end']}` this._dateRangeOptions.settings = { autoUpdateInput: true, locale: { format: 'YYYY-MM-DD' } } this.loadDeps() moment.locale('es-MX') } ...
else{ this.loading = true } }else{ this.loading = true } this._api.restfulPut( params, 'Asistencia/pya' ) .subscribe( res =>{ if( asesor && !flag){ // console.log( res ) this.singleUpdate( res ) ...
{ this.asistData[asesor]['data'][inicio]['loading'] = true }
conditional_block
asistencia.component.ts
.showContents = false } }) this.searchCriteria['value']= `${this.searchCriteria['start']} - ${this.searchCriteria['end']}` this._dateRangeOptions.settings = { autoUpdateInput: true, locale: { format: 'YYYY-MM-DD' } } this.loadDeps() moment.locale('es-MX') } sea...
checkSet(rac, date, block){ if(this.isset(this.shownDom,`${rac}_${
{ if(this.checkSet(rac, date, block)){ this.shownDom[`${rac}_${date}_${block}`] = undefined }else{ this.shownDom[`${rac}_${date}_${block}`] = true } }
identifier_body
asistencia.component.ts
this.showContents = false } }) this.searchCriteria['value']= `${this.searchCriteria['start']} - ${this.searchCriteria['end']}` this._dateRangeOptions.settings = { autoUpdateInput: true, locale: { format: 'YYYY-MM-DD' } } this.loadDeps() moment.locale('es-MX') } ...
let cunTime = time.clone().tz('America/Bogota') return cunTime.format(format) } orderNames( data, ord=1 ){ // console.log(data) let sortArray:any = [] let tmpSlot:any = [] let flag:boolean let pushFlag:boolean let x:number let lastInput:any let compare:any = [] ...
formatDate(datetime, format){ let time = moment.tz(datetime, 'this._zh.defaultZone')
random_line_split
simple-handler.go
asmExecJsOnce sync.Once wasmExecJsContent []byte wasmExecJsTs time.Time lastBuildTime time.Time // time of last successful build lastBuildContentGZ []byte // last successful build gzipped mu sync.RWMutex } // New returns an SimpleHandler ready to serve using the specified directory. // The dev f...
{ http.Error(w, "failed to run `go env GOROOT`: "+err.Error(), 500) return }
conditional_block
simple-handler.go
StaticHandler http.Handler // returns static assets from Dir with appropriate filtering or appropriate error wasmExecJsOnce sync.Once wasmExecJsContent []byte wasmExecJsTs time.Time lastBuildTime time.Time // time of last successful build lastBuildContentGZ []byte // last successful build gzip...
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { w.Header().Set("Content-Encoding", "gzip") w.Header().Set("X-Gzipped-Size", fmt.Sprint(len(lastBuildContentGZ))) http.ServeContent(w, r, h.MainWasmPath, lastBuildTime, bytes.NewReader(lastBuildContentGZ)) return } // no gzip, we decompress inter...
// w.Header().Set("Last-Modified", lastBuildTime.Format(http.TimeFormat)) // handled by http.ServeContent // if client supports gzip response (the usual case), we just set the gzip header and send back
random_line_split
simple-handler.go
, "GOOS=js", "GOARCH=wasm") b, err := cmd.CombinedOutput() return b, err } b, err := runCommand("go", "mod", "tidy") if err == nil { b, err = runCommand("go", "build", "-o", fpath, ".") } w.Header().Set("X-Go-Build-Duration", time.Since(startTime).String()) if err != nil { msg := fmt.Sprintf("Er...
{ dirf, err := os.Open(dir) if err != nil { return ts, err } defer dirf.Close() fis, err := dirf.Readdir(-1) if err != nil { return ts, err } for _, fi := range fis { if fi.Name() == "." || fi.Name() == ".." { continue } // for directories we recurse
identifier_body
simple-handler.go
(w, msg, 500) return } } // GOOS=js GOARCH=wasm go build -o main.wasm . startTime = time.Now() runCommand := func(args ...string) ([]byte, error) { cmd := exec.Command(args[0], args[1:]...) cmd.Dir = h.Dir cmd.Env = append(cmd.Env, os.Environ()...) cmd.Env = append(cmd.Env, "GOOS=js", "GOARC...
dirTimestamp
identifier_name
parse_dwarf.py
<s>" result = 0 shift = 0 i = 0 while 1: byte = ord (s[i]); i += 1 result |= (byte & 0x7f) << shift if byte & 0x80: shift += 7 else: break return result def read_string (f): "read null-terminated string from <f>" r = [] while 1: ...
compile_unit
identifier_name
parse_dwarf.py
read_udata (f): return read_uleb128 (f) def read_flag_present (f): return True def decode_location (x): # interpret form if x[0] == '#': return decode_uleb128 (x[1:]) elif x[0] == '\x91': # XXX signed, but we'll cheat return decode_uleb128 (x[1:]) elif x[0] == '\x03': ...
"""read (<path>, <elf_info>) => <iterator> generate a list of <compile_unit> objects for file <path>""" ehdr, phdrs, shdrs, syms, core_info = elf_info info = abbrev = strings = None for shdr in shdrs: if shdr['name'] == '.debug_info': info = shdr['offset'], shdr['size'] if sh...
identifier_body
parse_dwarf.py
0 while 1: byte = ord (f.read (1)) result |= (byte & 0x7f) << shift if byte & 0x80: shift += 7 else: break return result def decode_uleb128 (s): "parse an 'unsigned little-endian base 128' from string <s>" result = 0 shift = 0 i = 0 w...
children = None
conditional_block
parse_dwarf.py
= 0x02 DW_AT_name = 0x03 DW_AT_ordering = 0x09 DW_AT_subscr_data = 0x0a DW_AT_byte_size = 0x0b DW_AT_bit_offset = 0x0c DW_AT_bit_size = 0x0d DW_AT_element_list = 0x0f DW_AT_stmt_list = 0x10 DW_AT_low_pc = 0x...
DW_ATE_boolean = 0x02 DW_ATE_complex_float = 0x03 DW_ATE_float = 0x04 DW_ATE_signed = 0x05 DW_ATE_signed_char = 0x06 DW_ATE_unsigned = 0x07 DW_ATE_unsigned_char = 0x08 DW_ATE_imaginary_float = 0x09 DW_ATE_packed_decimal = 0x0a DW_ATE_numeric_string = 0x0b DW_ATE_edited ...
random_line_split
report.go
FailReasonSummary `json:"failSummary"` } type NodeMap map[string]*framework.NodeInfo type ClusterCapacityNodeResult struct { NodeName string `json:"nodeName"` Labels map[string]string `json:"labels"` PodCount int `json:"podCount"` Allocatable *framework.Resource `json:"al...
return result } func newResources() *Resources { return &Resources{ PrimaryResources: v1.ResourceList{ v1.ResourceName(v1.ResourceCPU): *resource.NewMilliQuantity(0, resource.DecimalSI), v1.ResourceName(v1.ResourceMemory): *resource.NewQuantity(0, resource.BinarySI), v1.ResourceName...
}
random_line_split
report.go
Resources = map[v1.ResourceName]int64{} } dest.ScalarResources[rName] += rQuantity.Value() } } } } func parseNodesReview(nodes NodeMap) []*ClusterCapacityNodeResult { // sort nodes by name nodeNames := make([]string, len(nodes), len(nodes)) nodeIdx := 0 for key, _ := range nodes { nodeNames[nodeIdx...
{ cap := float64(requested) / float64(allocatable) * 100 fmt.Printf("\t- %s requested: %v%s/%v%s %.2f%% allocated\n", label, requested, unit, allocatable, unit, cap) commit := float64(limit) / float64(allocatable) * 100 fmt.Printf("\t- %s limited: %v%s/%v%s %.2f%% allocated\n", label, limit, unit, allocatable, ...
identifier_body
report.go
FailReasonSummary `json:"failSummary"` } type NodeMap map[string]*framework.NodeInfo type ClusterCapacityNodeResult struct { NodeName string `json:"nodeName"` Labels map[string]string `json:"labels"` PodCount int `json:"podCount"` Allocatable *framework.Resource `json:"al...
return resultSlc } func getPodsRequirements(pods []*v1.Pod) []*Requirements { result := make([]*Requirements, 0) for _, pod := range pods { podRequirements := &Requirements{ PodName: pod.Name, Resources: getResourceRequest(pod), Limits: getResourceLimit(pod), NodeSelectors: pod.Spec....
{ resultSlc = append(resultSlc, v) }
conditional_block
report.go
FailReasonSummary `json:"failSummary"` } type NodeMap map[string]*framework.NodeInfo type ClusterCapacityNodeResult struct { NodeName string `json:"nodeName"` Labels map[string]string `json:"labels"` PodCount int `json:"podCount"` Allocatable *framework.Resource `json:"al...
(pod *v1.Pod) *Resources { result := newResources() for _, container := range pod.Spec.Containers { appendResources(result, container.Resources.Requests) } return result } func getResourceLimit(pod *v1.Pod) *Resources { result := newResources() for _, container := range pod.Spec.Containers { appendResources(...
getResourceRequest
identifier_name
lib.rs
conversion of Balance -> `u64`. This is used for /// staking's election calculation. pub struct CurrencyToVoteHandler; impl CurrencyToVoteHandler { fn factor() -> Balance
} impl Convert<Balance, u64> for CurrencyToVoteHandler { fn convert(x: Balance) -> u64 { (x / Self::factor()) as u64 } } impl Convert<u128, Balance> for CurrencyToVoteHandler { fn convert(x: u128) -> Balance { x * Self::factor() } } parameter_types! { pub const SessionsPerEra: sp_staking::SessionIndex = 3;...
{ (Balances::total_issuance() / u64::max_value() as Balance).max(1) }
identifier_body
lib.rs
conversion of Balance -> `u64`. This is used for /// staking's election calculation. pub struct CurrencyToVoteHandler; impl CurrencyToVoteHandler { fn factor() -> Balance { (Balances::total_issuance() / u64::max_value() as Balance).max(1) } } impl Convert<Balance, u64> for CurrencyToVoteHandler { fn
(x: Balance) -> u64 { (x / Self::factor()) as u64 } } impl Convert<u128, Balance> for CurrencyToVoteHandler { fn convert(x: u128) -> Balance { x * Self::factor() } } parameter_types! { pub const SessionsPerEra: sp_staking::SessionIndex = 3; // 3 hours pub const BondingDuration: pallet_staking::EraIndex = 4; ...
convert
identifier_name
lib.rs
EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>; type ExternalDefaultOrigin = pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>; /// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote /// be tabled immediately and with a shorter voting...
type AccountStore = System; // type Event = Event;
random_line_split
paxos.go
.ENOENT && err1.Err != syscall.ECONNREFUSED { fmt.Printf("paxos Dial() failed: %v\n", err1) } return false } defer c.Close() // fmt.Printf("Call srv:%s name:%s\n", srv, name) err = c.Call(name, args, reply) // fmt.Printf("After Call %s, err:%v, rpl:%v\n", srv, err, reply) if err == nil { return true }...
(seq int, v interface{}) { for idx, peer := range px.peers { args := &DecdidedArgs{} reply := &DecidedReply{} args.Seq = seq args.V = v if idx == px.me { px.Decided(args, reply) } else { call(peer, "Paxos.Decided", args, reply) } } } /* Learner * handler for decide notification */ func (px *P...
send_decided
identifier_name
paxos.go
OENT && err1.Err != syscall.ECONNREFUSED { fmt.Printf("paxos Dial() failed: %v\n", err1) } return false } defer c.Close() // fmt.Printf("Call srv:%s name:%s\n", srv, name) err = c.Call(name, args, reply) // fmt.Printf("After Call %s, err:%v, rpl:%v\n", srv, err, reply) if err == nil { return true } r...
/* Proposer * send decided value to all */ func (px *Paxos) send_decided(seq int, v interface{}) { for idx, peer := range px.peers { args := &DecdidedArgs{} reply := &DecidedReply{} args.Seq = seq args.V = v if idx == px.me { px.Decided(args, reply) } else { call(peer, "Paxos.Decided", args, re...
{ if args.Proposal.PNum >= px.APp[args.Seq] { px.APp[args.Seq] = args.Proposal.PNum px.APa[args.Seq] = args.Proposal reply.Err = OK } else { reply.Err = Reject } return nil }
identifier_body
paxos.go
OENT && err1.Err != syscall.ECONNREFUSED
return false } defer c.Close() // fmt.Printf("Call srv:%s name:%s\n", srv, name) err = c.Call(name, args, reply) // fmt.Printf("After Call %s, err:%v, rpl:%v\n", srv, err, reply) if err == nil { return true } return false } /* clog(bool, func_name, format) */ func (px *Paxos) clog(dbg bool, funcname, fo...
{ fmt.Printf("paxos Dial() failed: %v\n", err1) }
conditional_block
paxos.go
.ENOENT && err1.Err != syscall.ECONNREFUSED { fmt.Printf("paxos Dial() failed: %v\n", err1) } return false } defer c.Close() // fmt.Printf("Call srv:%s name:%s\n", srv, name) err = c.Call(name, args, reply) // fmt.Printf("After Call %s, err:%v, rpl:%v\n", srv, err, reply) if err == nil { return true }...
px.clog(DBG_PROPOSER, "Start", "decided") break } }() } // // the application on this machine is done with // all instances <= seq. // // see the comments for Min() for more explanation. // func (px *Paxos) Done(seq int) { // Your code here. px.clog(DBG_DONE, "Done", "Done: %d", seq) if seq <= px.local_...
px.clog(DBG_PROPOSER, "Start", "accept OK") px.send_decided(seq, new_p.Value)
random_line_split
event.rs
, Eq, Default, Hash)] pub struct EventId(pub usize); impl From<usize> for EventId { fn from(x: usize) -> Self { Self(x) } } lazy_static! { pub static ref EVENT_ID_MAPPINGS: Mutex<Mappings<TypeId, EventId>> = Mutex::new(Mappings::new()); } /// Returns the event ID for the given type. pub f...
let ptr: *mut E = self .ctx .bump .get_or_default() .alloc_layout(Layout::for_value(self.queued.as_slice())) .cast::<E>() .as_ptr();
{ return; // Nothing to do }
conditional_block
event.rs
APPINGS.lock().get_or_alloc(TypeId::of::<E>()) } /// Marker trait for types which can be triggered as events. pub trait Event: Send + Sync + 'static {} impl<T> Event for T where T: Send + Sync + 'static {} /// Strategy used to handle an event. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum HandleStrateg...
trigger
identifier_name
event.rs
, Eq, Default, Hash)] pub struct EventId(pub usize); impl From<usize> for EventId { fn from(x: usize) -> Self { Self(x) } } lazy_static! { pub static ref EVENT_ID_MAPPINGS: Mutex<Mappings<TypeId, EventId>> = Mutex::new(Mappings::new()); } /// Returns the event ID for the given type. pub f...
/// Returns the unique ID of this event handler, as allocated by `system_id_for::<T>()`. fn id(&self) -> SystemId; /// Returns the name of this event handler. fn name(&self) -> &'static str; /// Returns the ID of the event which is handled by this handler. fn event_id(&self) -> EventId; /...
pub unsafe trait RawEventHandler: Send + Sync + 'static {
random_line_split
tutorial.js
specifics of Gremlin, its good to know what you are getting yourself into. Moreover, its important to know if Gremlin can be of use to you. Below is a list of a few key benefits of Gremlin:") + BR() + DIV(LIST( [ '1. Gremlin is useful for manually working with your gr...
return P("Chapter 2c - Using Gremlin build-in functions and data structures (maps, lists).") + BR() + P("&nbsp;Gremlin provides build-in functions and data structures which will be very useful while working with graphs.") + BR() + P("To execute a function you should call it using special...
random_line_split
main_classes.py
if random.randint(0, results[rarity]) == 1: quantity += 1 countdown -= 1 return quantity def drop_building(dictionary, p, limit=None): limit = limit or len(adjectives) drops_i = [] for k, v in dictionary.items(): quantity = dropper(v['rarity']) quantity = q...
'super common': 2} quantity = 0 countdown = random.randint(0, 10) while countdown > 0:
random_line_split
main_classes.py
(formatted) else: return "nothing" def pretty_inventory(self): w = self.equipped_weapon major = self.major_armor.defense if self.major_armor else 0 minor = self.minor_armor.defense if self.minor_armor else 0 armor_defense = (major + minor) * 5 armors = [...
self.inventory.remove(nice_weapons[0]) return nice_weapons[0]
conditional_block
main_classes.py
self.name = name self.unique_mob_names = [] self.unique_building_names = [] self.unique_house_names = [] mobs = [] items = [] buildings = [] def generate_items(self): self.items = drop_item(add_dicts_together(items["master"], items[self.square_type])) def g...
__init__
identifier_name
main_classes.py
0] drops_i.append(Mob(name=f"{k} named {name}", p=p, **v)) return drops_i def drop_item(dictionary): """ Randomly generates objects based on rarity """ drops_i = [] for k, v in dictionary.items(): quantity = dropper(v['rarity']) if quantity: drops_i.app...
def view_hit_list(self): if self.hit_list: print(f"If you ever run across these shady characters, be sure to take their names off your list: {comma_separated(self.hit_list)}") else: print("Looks like you don't know of anyone who needs to be dead.") def increase_skill(s...
print(f"You have killed {self.body_count} mobs.") print(f"You have ran away from {self.run_away_count} battles.") print(f"You have eaten {self.food_count} items.") print(f"You have performed {self.assassination_count} assassinations.") print(f"You have talked to mobs {self.greeting_count...
identifier_body
tanzania-improved.py
() # In[9]: #dropping the labels that you are supposed to predict and the excess from train_head cols = ['ID','mobile_money', 'savings', 'borrowing','insurance'] train_data = train_data.drop(cols, axis=1) x_test = test_data.drop(['ID'], axis=1) # In[10]: #looking at the unique classification classes train_data[...
# In[
df_pred.head()
random_line_split
tanzania-improved.py
.head() # In[9]: #dropping the labels that you are supposed to predict and the excess from train_head cols = ['ID','mobile_money', 'savings', 'borrowing','insurance'] train_data = train_data.drop(cols, axis=1) x_test = test_data.drop(['ID'], axis=1) # In[10]: #looking at the unique classification classes train_...
# In[18]: from pprint import pprint # Look at parameters used by our current forest print('Parameters currently in use:\n') pprint(rf.get_params()) # In[19]: from sklearn.model_selection import RandomizedSearchCV # Number of trees in random forest n_estimators = [int(x) for x in np.linspace(start = 200, stop =...
print("Train Index: ", train_index, "\n") print("Test Index: ", test_index) X_train, X_test, y_train, y_test = X2[train_index], X2[test_index], y[train_index], y[test_index] rf.fit(X_train, y_train) scores.append(rf.score(X_test, y_test))
conditional_block
main.js
id; this.nombre = nombre; this.costo = costo; this.tipo = tipo; this.descripcion = descripcion; this.selected = selected; this.cantidadPersonas = cantidadPersonas; } } const servicios = []; servicios.push( new Servicio( 1, 'Cabalgata', 600, 'Recreacion',
servicios.push( new Servicio( 2, 'Tirolesa', 800, 'Recreacion', 'Deslizamiento por cable entre las copas de los arboles.', false, 0 ) ); servicios.push( new Servicio( 3, 'Trekking', 800, 'Recreacion', 'Caminata guiada por el bosque.', false, 0 ) ); servici...
'Tour a caballo guiado por el bosque.', false, 0 ) );
random_line_split
main.js
; this.nombre = nombre; this.costo = costo; this.tipo = tipo; this.descripcion = descripcion; this.selected = selected; this.cantidadPersonas = cantidadPersonas; } } const servicios = []; servicios.push( new Servicio( 1, 'Cabalgata', 600, 'Recreacion', 'Tour a caballo gu...
function Cabaña(id, nombre, precio, selected) { this.id = id; this.nombre = nombre; this.precio = precio; this.selected = selected; } const cabins = []; cabins.push(new Cabaña(1, 'Cabaña simple', simpleIVA, false)); cabins.push(new Cabaña(2, 'Cabaña doble', dobleIVA, false)); cabins.push(new Cabaña(3, 'Caba...
cabanasimple.style.display = 'none'; cabanadoble.style.display = 'none'; cabanasuite.style.display = 'initial'; aparecerDoble.style.display = 'none'; aparecerSimple.style.display = 'none'; } };
conditional_block
main.js
id; this.nombre = nombre; this.costo = costo; this.tipo = tipo; this.descripcion = descripcion; this.selected = selected; this.cantidadPersonas = cantidadPersonas; } } const servicios = []; servicios.push( new Servicio( 1, 'Cabalgata', 600, 'Recreacion', 'Tour a caballo...
url: 'https://randomuser.me/api/?results=4&nat=us
$.ajax({
identifier_name
main.js
} const servicios = []; servicios.push( new Servicio( 1, 'Cabalgata', 600, 'Recreacion', 'Tour a caballo guiado por el bosque.', false, 0 ) ); servicios.push( new Servicio( 2, 'Tirolesa', 800, 'Recreacion', 'Deslizamiento por cable entre las copas de los arboles.'...
{ this.id = id; this.nombre = nombre; this.costo = costo; this.tipo = tipo; this.descripcion = descripcion; this.selected = selected; this.cantidadPersonas = cantidadPersonas; }
identifier_body
nginx_controller.go
rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch // +kubebuilder:rbac:groups=networking.k8s.io,resources=ingresses,verbs=get;list;watch;create;update;delete // +kubebuilder:rbac:groups="",resources=services,verbs=get;list;watch;create;update;patch // +kubebuilder:rbac:groups="",resources=...
(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { log := r.Log.WithValues("nginx", req.NamespacedName) var instance nginxv1alpha1.Nginx err := r.Client.Get(ctx, req.NamespacedName, &instance) if err != nil { if errors.IsNotFound(err) { log.Info("Nginx resource not found, skipping reconcile") r...
Reconcile
identifier_name
nginx_controller.go
{ return nil } replicas := currentDeploy.Spec.Replicas patch := client.StrategicMergeFrom(currentDeploy.DeepCopy()) currentDeploy.Spec = newDeploy.Spec if newDeploy.Spec.Replicas == nil { // NOTE: replicas field is set to nil whenever it's managed by some // autoscaler controller e.g HPA. currentDeploy...
{ return nil, err }
conditional_block
nginx_controller.go
rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch // +kubebuilder:rbac:groups=networking.k8s.io,resources=ingresses,verbs=get;list;watch;create;update;delete // +kubebuilder:rbac:groups="",resources=services,verbs=get;list;watch;create;update;patch // +kubebuilder:rbac:groups="",resources=...
func (r *NginxReconciler) reconcileDeployment(ctx context.Context, nginx *nginxv1alpha1.Nginx) error { newDeploy, err := k8s.NewDeployment(nginx) if err != nil { return fmt.Errorf("failed to build Deployment from Nginx: %w", err) } var currentDeploy appsv1.Deployment err = r.Client.Get(ctx, types.NamespacedNa...
{ if err := r.reconcileDeployment(ctx, nginx); err != nil { return err } if err := r.reconcileService(ctx, nginx); err != nil { return err } if err := r.reconcileIngress(ctx, nginx); err != nil { return err } return nil }
identifier_body
nginx_controller.go
"k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/record" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/contr...
networkingv1 "k8s.io/api/networking/v1"
random_line_split
provider.go
v.(*constructInput) for i := 0; i < typ.NumField(); i++ { fieldV := argsV.Field(i) if !fieldV.CanSet() { continue } field := typ.Field(i) tag, has := field.Tag.Lookup("pulumi") if !has || tag != k { continue } handleField := func(typ reflect.Type, value resource.PropertyValue, deps [...
callArgsSelf
identifier_name
provider.go
// Deserialize the inputs and apply appropriate dependencies. inputDependencies := req.GetInputDependencies() deserializedInputs, err := plugin.UnmarshalProperties( req.GetInputs(), plugin.MarshalOptions{KeepSecrets: true, KeepResources: true, KeepUnknowns: req.GetDryRun()}, ) if err != nil { return nil, e...
{ return nil, errors.Wrap(err, "constructing run context") }
conditional_block
provider.go
() { aliases[i] = Alias{URN: URN(urn)} } dependencyURNs := urnSet{} for _, urn := range req.GetDependencies() { dependencyURNs.add(URN(urn)) } providers := make(map[string]ProviderResource, len(req.GetProviders())) for pkg, ref := range req.GetProviders() { resource, err := createProviderResource(pulumiCtx,...
if typ.Kind() != reflect.Ptr || typ.Elem().Kind() != reflect.Struct { return errors.New("args must be a pointer to a struct") } argsV, typ = argsV.Elem(), typ.Elem() for k, v := range inputs { ci := v.(*constructInput) for i := 0; i < typ.NumField(); i++ { fieldV := argsV.Field(i) if !fieldV.CanSet() {...
} argsV := reflect.ValueOf(args) typ := argsV.Type()
random_line_split
provider.go
.Context) (urnSet, error){ func(ctx context.Context) (urnSet, error) { return dependencyURNs, nil }, } ro.Protect = req.GetProtect() ro.Providers = providers ro.Parent = parent }) urn, state, err := constructF(pulumiCtx, req.GetType(), req.GetName(), inputs, opts) if err != nil { return nil, err...
{ if resource == nil { return nil, nil, errors.New("resource must not be nil") } resourceV := reflect.ValueOf(resource) typ := resourceV.Type() if typ.Kind() != reflect.Ptr || typ.Elem().Kind() != reflect.Struct { return nil, nil, errors.New("resource must be a pointer to a struct") } resourceV, typ = resou...
identifier_body
build_server.go
-> "net/http" } } wsparams.Query = q.String() b, err := json.Marshal(wsparams) if err != nil { return nil, err } req.Params = (*json.RawMessage)(&b) } if req.Method == "workspace/xreferences" { // Parse the parameters and if a dirs hint is present, rewrite the // URIs. var p lsp...
{ var result error for _, closer := range h.closers { err := closer.Close() if err != nil { result = multierror.Append(result, err) } } return result }
identifier_body
build_server.go
po"). span.SetTag("originalRootPath", params.OriginalRootURI) fs, closer, err := RemoteFS(ctx, params) if err != nil { return nil, err } h.closers = append(h.closers, closer) langInitParams, err := determineEnvironment(ctx, fs, params) if err != nil { return nil, err } log.Printf("Detected root...
random_line_split
build_server.go
(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) { // Prevent any uncaught panics from taking the entire server down. defer func() { if r := recover(); r != nil { err = fmt.Errorf("unexpected panic: %v", r) // Same as net/http const size = 64 << 10 buf :...
Handle
identifier_name
build_server.go
== nil { h.mu.Unlock() return nil, errors.New("server must be initialized") } h.mu.Unlock() if err := h.CheckReady(); err != nil { if req.Method == "exit"
return nil, err } h.InitTracer(conn) span, ctx, err := h.SpanForRequest(ctx, "build", req, opentracing.Tags{"mode": "go"}) if err != nil { return nil, err } defer func() { if err != nil { ext.Error.Set(span, true) span.LogFields(otlog.Error(err)) } span.Finish() }() if Debug && h.init != nil ...
{ err = nil }
conditional_block
cdn_log.go
) { s.waitingJobs(ctx) }) go func() { for { conn, err := listener.Accept() if err != nil { telemetry.Record(ctx, Errors, 1) log.Error(ctx, "unable to accept connection: %v", err) return } sdk.GoRoutine(ctx, "cdn-logServer", func(ctx context.Context) { telemetry.Record(ctx, Hits, 1) ...
if err != nil { log.Error(ctx, "unable to check canDequeue %s: %v", jobQueue
{ for { select { case <-ctx.Done(): return default: // List all queues keyListQueue := cache.Key(keyJobLogQueue, "*") listKeys, err := s.Cache.Keys(keyListQueue) if err != nil { log.Error(ctx, "unable to list jobs queues %s", keyListQueue) continue } // For each key, check if heartb...
identifier_body
cdn_log.go
.Accept() if err != nil { telemetry.Record(ctx, Errors, 1) log.Error(ctx, "unable to accept connection: %v", err) return } sdk.GoRoutine(ctx, "cdn-logServer", func(ctx context.Context) { telemetry.Record(ctx, Hits, 1) s.handleConnection(ctx, conn) }) } }() } func (s *Service) handleC...
{ continue }
conditional_block
cdn_log.go
StepOrder: signature.Worker.StepOrder, Val: m.Full, } if !strings.HasSuffix(logs.Val, "\n") { logs.Val += "\n" } var lvl string switch m.Level { case int32(hook.LOG_DEBUG): lvl = "DEBUG" case int32(hook.LOG_INFO): lvl = "INFO" case int32(hook.LOG_NOTICE): lvl = "NOTICE" case int32(hook.LO...
// if key exist, that mean that someone is already dequeuing
random_line_split
cdn_log.go
) { s.waitingJobs(ctx) }) go func() { for { conn, err := listener.Accept() if err != nil { telemetry.Record(ctx, Errors, 1) log.Error(ctx, "unable to accept connection: %v", err) return } sdk.GoRoutine(ctx, "cdn-logServer", func(ctx context.Context) { telemetry.Record(ctx, Hits, 1) ...
(ctx context.Context, hatcheryID int64, hatcheryName string) (*rsa.PublicKey, error) { h, err := services.LoadByNameAndType(ctx, s.Db, hatcheryName, services.TypeHatchery) if err != nil { return nil, err } if h.ID != hatcheryID { return nil, sdk.WithStack(sdk.ErrWrongRequest) } // Verify signature pk, err ...
getHatchery
identifier_name
test_runner.go
t *testing.T imsis map[string]bool activePCRFs []string activeOCSs []string startTime time.Time } // imsi -> ruleID -> record type RecordByIMSI map[string]map[string]*lteprotos.RuleRecord // NewTestRunner initializes a new TestRunner by making a UESim client and // and setting the next IMSI. f...
seq := getRandSeq() ue := makeUE(imsi, key, opc, seq) sub := makeSubscriber(imsi, key, opc, seq+1) err = uesim.AddUE(ue) if err != nil { return nil, errors.Wrap(err, "Error adding UE to UESimServer") } err = addSubscriberToHSS(sub) if err != nil { return nil, errors.Wrap(err, "Error adding Subs...
{ return nil, err }
conditional_block
test_runner.go
Error adding Subscriber to PCRF") } err = addSubscriberToOCSPerInstance(ocsInstance, sub.GetSid()) if err != nil { return nil, errors.Wrap(err, "Error adding Subscriber to OCS") } ues = append(ues, ue) fmt.Printf("Added UE to Simulator, %s, %s, and %s:\n"+ "\tIMSI: %s\tKey: %x\tOpc: %x\tSeq: %d\n", M...
generateRandomIMSIS
identifier_name
test_runner.go
Service(PipelinedRemote, CwagIP, PipelinedPort) fmt.Printf("Adding Redis service at %s:%d\n", CwagIP, RedisPort) registry.AddService(RedisRemote, CwagIP, RedisPort) fmt.Printf("Adding Directoryd service at %s:%d\n", CwagIP, DirectorydPort) registry.AddService(DirectorydRemote, CwagIP, DirectorydPort) testRunner :...
func (tr *TestRunner) WaitForPoliciesToSync() { // TODO load this value from sessiond.yml (rule_update_interval_sec) ruleUpdatePeriod := 1 * time.Second time.Sleep(4 * ruleUpdatePeriod) }
random_line_split
test_runner.go
and 2 OCS // Used in scenarios that run 2 PCRFs and 2 OCSs func NewTestRunnerWithTwoPCRFandOCS(t *testing.T) *TestRunner { tr := NewTestRunner(t) fmt.Printf("Adding Mock PCRF #2 service at %s:%d\n", CwagIP, PCRFPort2) registry.AddService(MockPCRFRemote2, CwagIP, PCRFPort2) fmt.Printf("Adding Mock OCS #2 service a...
{ // Wait until the ruleIDs show up for the IMSI return func() bool { fmt.Printf("Waiting until %s, %v shows up in enforcement stats...\n", imsi, ruleIDs) records, err := tr.GetPolicyUsage() if err != nil { return false } if records[prependIMSIPrefix(imsi)] == nil { return false } for _, ruleID :=...
identifier_body
dt.py
ia/arrhythmia.data" df = pd.read_csv(url, header = None, na_values="?") dsmall = df.iloc[0:10, list(range(3)) + [279]] class Node(object): def __init__(self, name, node_type, data, label=None, split=None): self.name = name self.node_type = node_type self.label = label self.data = d...
class Split(object): def __init__(self, data, class_column, split_column, point=None): self.data = data self.class_column = class_column self.split_column = split_column self.info_gain = None self.point = point self.partition_list...
data = self.data if self.node_type != 'leaf': s = (f"{self.name} Internal node with {data[data.columns[0]].count()} rows; split" f" {self.split.split_column} at {self.split.point:.2f} for children with" f" {[p[p.columns[0]].count() for p in self.split.partitions()]}...
identifier_body
dt.py
ia/arrhythmia.data" df = pd.read_csv(url, header = None, na_values="?") dsmall = df.iloc[0:10, list(range(3)) + [279]] class Node(object): def __init__(self, name, node_type, data, label=None, split=None): self.name = name self.node_type = node_type self.label = label self.data = d...
res.append(node.label) return res def plurality_value(self, data): #return data[self.class_column].value_counts().idxmax() return np.argmax(np.bincount(data[self.class_column].astype(int).values)) def print(self): self.recursive_print(self.root)...
node = node.children[1]
conditional_block
dt.py
ia/arrhythmia.data" df = pd.read_csv(url, header = None, na_values="?") dsmall = df.iloc[0:10, list(range(3)) + [279]] class Node(object): def __init__(self, name, node_type, data, label=None, split=None): self.name = name self.node_type = node_type self.label = label self.data = d...
for depth in range(MAX_DEPTH + 1)[2::2]: # initialize the tree dt = DecisionTree(depth) training_error_ratio_sum = 0 test_error_ratio_sum = 0 for sets in [[0,1,2],[1,2,0],[0,2,1]]: # get the training data and test data training_data =...
# initilize the correct ratio of training data and test data training_error_ratio = [] test_error_ratio = []
random_line_split
dt.py
ia/arrhythmia.data" df = pd.read_csv(url, header = None, na_values="?") dsmall = df.iloc[0:10, list(range(3)) + [279]] class Node(object): def __init__(self, name, node_type, data, label=None, split=None): self.name = name self.node_type = node_type self.label = label self.data = d...
(self, neg, pos): data = self.data[self.class_column].values.astype(int) H0 = self.compute_entropy(data) p_neg = len(neg) / len(data) p_pos = len(pos) / len(data) H_n = p_neg * self.compute_entropy(neg) H_p = p_pos * self.compute_entropy(pos) Ha = H_p + H...
compute_info_gain
identifier_name
main.go
m.InitMain() m.InitMysqlDB() m.InitMysqlTable() m.InitConnPooling() if isUpdated { // save mysql proxy. err := redis.UpdateDB("main", redis.EncodeData(m), "MysqlProxy") CheckError(err) } // panic(fmt.Sprintf("OK: %#v", m)) } // get the table status. func (m *Mys...
dLogHostStatus() return proxy } // To init the necessary data. func (m *MysqlProxy) Init() {
identifier_body
main.go
", redis.EncodeData(m), "MysqlProxy") CheckError(err) } // panic(fmt.Sprintf("OK: %#v", m)) } // get the table status. func (m *MysqlProxy) GetStatus() (map[string]interface{}, error) { result := map[string]interface{}{} result["main"] = redis.EncodeData(m) tables := []string{} sha...
schema.MysqlShardTable{} for _, id := range ids { tbs, err := redis.ReadDB("MysqlShardTable", id) if err != nil { return nil, err } if len(tbs) != 1 { return nil, errors.New("no found the shard table for id: " + id) } tb := tbs[0][id].(map[string]interface {}) sha...
tables := []*
identifier_name
main.go
redis.EncodeData(m), "MysqlProxy") CheckError(err) } // panic(fmt.Sprintf("OK: %#v", m)) } // get the table status. func (m *MysqlProxy) GetStatus() (map[string]interface{}, error) { result := map[string]interface{}{} result["main"] = redis.EncodeData(m) tables := []string{} shard...
m.ShardDBs = shardDBs // add shard dbs map. schema.Sdbs = shardDBs } // listen the sharddb change status. locker := &sync.Mutex{} go func() { for { newShardDB := <-schema.NewShardDBCh locker.Lock() defer locker.Unl...
if len(dbs) != 1 { panic("no found relation shard db for id:" + sid) } sdb := dbs[0][sid].(map[string]interface {}) groupId := sdb["HostGroupId"].(string) curGroup, err := host.GetHostGroupById(groupId) CheckError(err) shardDB := &sch...
conditional_block
main.go
Group: curGroup, } shardDBs = append(shardDBs, shardDB) } m.ShardDBs = shardDBs // add shard dbs map. schema.Sdbs = shardDBs } // listen the sharddb change status. locker := &sync.Mutex{} go func() { for { ...
schema.Tables = tables m.TableIds = tableIds return m.UpdateToRedisDB()
random_line_split
test_framework.py
out"])): vout = txraw["vout"][vout_idx] if vout["value"] == MASTERNODE_COLLATERAL: collateral_vout = vout_idx self.nodes[0].lockunspent(False, [{'txid': txid, 'vout': collateral_vout}]) # send to same address to reserve some funds for fees self.nodes[0].s...
if s[check_received_messages] < check_received_messages_count: all_ok = False break
conditional_block
test_framework.py
for j in range(25): set_node_times(self.nodes, block_time) self.nodes[peer].generate(1) block_time += 156 # Must sync before next peer starts generating blocks sync_blocks(self.nodes) ...
create_raw_tx
identifier_name
test_framework.py
oshutdown and success != TestStatus.FAILED: self.log.info("Cleaning up") shutil.rmtree(self.options.tmpdir) else: self.log.warning("Not cleaning up dir %s" % self.options.tmpdir) if os.getenv("PYTHON_DEBUG", ""): # Dump the end of the debug logs, t...
assert num_nodes <= MAX_NODES create_cache = False for i in range(MAX_NODES): if not os.path.isdir(os.path.join(cachedir, 'node' + str(i))): create_cache = True break if create_cache: self.log.debug("Creating data directories from...
Create a cache of a 200-block-long chain (with wallet) for MAX_NODES Afterward, create num_nodes copies from the cache."""
random_line_split
test_framework.py
def run_test(self): raise NotImplementedError # Main function. This should not be overridden by the subclass test scripts. def main(self): parser = optparse.OptionParser(usage="%prog [options]") parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true...
extra_args = None if hasattr(self, "extra_args"): extra_args = self.extra_args self.nodes = _start_nodes(self.num_nodes, self.options.tmpdir, extra_args, stderr=stderr)
identifier_body