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
trab05.py
] = counts return mat #Função que constrói o descritor a partir das 5 métricas da matriz de co-ocorrências def haralick_texture_descriptor(image, b): c = diag_coocurrence_mat(image, b) c = c / np.sum(c) #Normalizando a matriz descriptors = [] #Energy descriptors.append( np.sum(np.sq...
nces[i, j] = np.sqrt( np.sum( np.square(object_descriptor - ld) ) ) coords = np.where(distances == distances.min()) #Distância mínima é onde assumimos que o programa e
conditional_block
trab05.py
mage, bits): return image >> (8-bits) #Função que constrói o descritor do histograma de cores normalizado def normalized_histogram_descriptor(image, bits): hist, _ = np.histogram(image, bins=2 ** bits) norm_hist = hist / np.sum(hist) return norm_hist / np.linalg.norm(norm_hist) #Função que constrói a...
antize(i
identifier_name
game.rs
transform::update_transforms; use crate::core::window::WindowDim; use crate::event::GameEvent; use crate::gameplay::collision::CollisionWorld; use crate::gameplay::delete::GarbageCollector; use crate::render::path::debug::DebugQueue; use crate::render::ui::gui::GuiContext; use crate::render::Renderer; use crate::resour...
(mut self) -> Game<'a, A> { let renderer = Renderer::new(self.surface, &self.gui_context); // Need some input :D let input: Input<A> = { let (key_mapping, btn_mapping) = self .input_config .unwrap_or((A::get_default_key_mapping(), A::get_default_mouse_...
build
identifier_name
game.rs
::transform::update_transforms; use crate::core::window::WindowDim; use crate::event::GameEvent; use crate::gameplay::collision::CollisionWorld; use crate::gameplay::delete::GarbageCollector; use crate::render::path::debug::DebugQueue; use crate::render::ui::gui::GuiContext; use crate::render::Renderer; use crate::reso...
let scene_result = if let Some(scene) = self.scene_stack.current_mut() { let scene_res = scene.update(dt, &mut self.world, &self.resources); { let chan = self.resources.fetch::<EventChannel<GameEvent>>().unwrap(); for ev in chan.read(&...
random_line_split
game.rs
transform::update_transforms; use crate::core::window::WindowDim; use crate::event::GameEvent; use crate::gameplay::collision::CollisionWorld; use crate::gameplay::delete::GarbageCollector; use crate::render::path::debug::DebugQueue; use crate::render::ui::gui::GuiContext; use crate::render::Renderer; use crate::resour...
pub fn build(mut self) -> Game<'a, A> { let renderer = Renderer::new(self.surface, &self.gui_context); // Need some input :D let input: Input<A> = { let (key_mapping, btn_mapping) = self .input_config .unwrap_or((A::get_default_key_mapping(), A::...
{ self.seed = Some(seed); self }
identifier_body
mod.rs
various shell surfaces defined by the //! clients by handling the `wl_shell` protocol. //! //! It allows you to easily access a list of all shell surfaces defined by your clients //! access their associated metadata and underlying `wl_surface`s. //! //! This handler only handles the protocol exchanges with the client ...
/// Send a ping request to this shell surface /// /// You'll receive the reply as a [`ShellRequest::Pong`] request /// /// A typical use is to start a timer at the same time you send this ping /// request, and cancel it when you receive the pong. If the timer runs /// down to 0 before a po...
{ if self.alive() { Some(&self.wl_surface) } else { None } }
identifier_body
mod.rs
various shell surfaces defined by the //! clients by handling the `wl_shell` protocol. //! //! It allows you to easily access a list of all shell surfaces defined by your clients //! access their associated metadata and underlying `wl_surface`s. //! //! This handler only handles the protocol exchanges with the client ...
<R> { wl_surface: wl_surface::WlSurface, shell_surface: wl_shell_surface::WlShellSurface, token: CompositorToken<R>, } impl<R> ShellSurface<R> where R: Role<ShellSurfaceRole> + 'static, { /// Is the shell surface referred by this handle still alive? pub fn alive(&self) -> bool { self.sh...
ShellSurface
identifier_name
mod.rs
various shell surfaces defined by the //! clients by handling the `wl_shell` protocol. //! //! It allows you to easily access a list of all shell surfaces defined by your clients //! access their associated metadata and underlying `wl_surface`s. //! //! This handler only handles the protocol exchanges with the client ...
else { Err(()) } } /// Send a configure event to this toplevel surface to suggest it a new configuration pub fn send_configure(&self, size: (u32, u32), edges: wl_shell_surface::Resize) { self.shell_surface.configure(edges, size.0 as i32, size.1 as i32) } /// Signal a p...
{ self.shell_surface.ping(serial); Ok(()) }
conditional_block
mod.rs
the various shell surfaces defined by the //! clients by handling the `wl_shell` protocol. //! //! It allows you to easily access a list of all shell surfaces defined by your clients //! access their associated metadata and underlying `wl_surface`s. //! //! This handler only handles the protocol exchanges with the cli...
/// /// You'll receive the reply as a [`ShellRequest::Pong`] request /// /// A typical use is to start a timer at the same time you send this ping /// request, and cancel it when you receive the pong. If the timer runs /// down to 0 before a pong is received, mark the client as unresponsive. ...
} /// Send a ping request to this shell surface
random_line_split
azuremachine_controller.go
.Result{}, nil } return reconcile.Result{}, err } // Fetch the Machine. machine, err := util.GetOwnerMachine(ctx, r.Client, azureMachine.ObjectMeta) if err != nil { return reconcile.Result{}, err } if machine == nil { logger.Info("Machine Controller has not yet set OwnerRef") return reconcile.Result{},...
{ machineScope.Info("Handling deleted AzureMachine") if err := newAzureMachineService(machineScope, clusterScope).Delete(); err != nil { return reconcile.Result{}, errors.Wrapf(err, "error deleting AzureCluster %s/%s", clusterScope.Namespace(), clusterScope.Name()) } defer func() { if reterr == nil { // VM...
identifier_body
azuremachine_controller.go
" "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" ) // AzureMachineReconciler reconciles a AzureMachine object type AzureMachineReconciler struct { client.Client Log logr.Logger Recorder record.EventRecorder } func (r *AzureMachineReconciler) SetupWithManager(mgr c...
(scope *scope.MachineScope, ams *azureMachineService) (*infrav1.VM, error) { var vm *infrav1.VM // If the ProviderID is populated, describe the VM using its name and resource group name. vm, err := ams.VMIfExists(scope.GetVMID()) if err != nil { return nil, errors.Wrapf(err, "failed to query AzureMachine VM") }...
findVM
identifier_name
azuremachine_controller.go
" "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" ) // AzureMachineReconciler reconciles a AzureMachine object type AzureMachineReconciler struct { client.Client Log logr.Logger Recorder record.EventRecorder } func (r *AzureMachineReconciler) SetupWithManager(mgr c...
reterr = err } }() // Handle deleted machines if !azureMachine.ObjectMeta.DeletionTimestamp.IsZero() { return r.reconcileDelete(machineScope, clusterScope) } // Handle non-deleted machines return r.reconcileNormal(ctx, machineScope, clusterScope) } // findVM queries the Azure APIs and retrieves the VM i...
random_line_split
azuremachine_controller.go
" "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" ) // AzureMachineReconciler reconciles a AzureMachine object type AzureMachineReconciler struct { client.Client Log logr.Logger Recorder record.EventRecorder } func (r *AzureMachineReconciler) SetupWithManager(mgr c...
logger = logger.WithValues("machine", machine.Name) // Fetch the Cluster. cluster, err := util.GetClusterFromMetadata(ctx, r.Client, machine.ObjectMeta) if err != nil { logger.Info("Machine is missing cluster label or cluster does not exist") return reconcile.Result{}, nil } logger = logger.WithValues("cl...
{ logger.Info("Machine Controller has not yet set OwnerRef") return reconcile.Result{}, nil }
conditional_block
contour.py
[0] - contour[set_idx_convDefs[i], 0, 0] #calcul x opposites[1,i] = 2*center[1] - contour[set_idx_convDefs[i], 0, 1] #calcul y total = np.sum(opposites, axis = 1) #print total x = int(total[0]/n) y = int(total[1]/n) wrist = (x, y) #print 'wrist = ', wrist return wrist ''' simpl...
hull_nbPts = hull.shape[0
max4dist = dist_order[0:4] max4points = convDefs[max4dist,0,2] for i in max4points: cv2.circle(drawing, tuple(cnt[i,0]), 5, [255,255,0], 2)
random_line_split
contour.py
#check whether two points are too near from each other def points_not_similar(x, y, x_neighb, y_neighb, threshold): no_same_point = (fabs(x - x_neighb) + fabs(y - y_neighb) > 2*threshold) return no_same_point def good_points(x, y, x_next, y_next, img_height, img_width, threshold): no_same_poin...
no_at_edge = ( (x > threshold) and (y > threshold) and ( fabs(x - img_width) > threshold ) and ( fabs(y - img_height) > threshold ) ) return no_at_edge
identifier_body
contour.py
[0] - contour[set_idx_convDefs[i], 0, 0] #calcul x opposites[1,i] = 2*center[1] - contour[set_idx_convDefs[i], 0, 1] #calcul y total = np.sum(opposites, axis = 1) #print total x = int(total[0]/n) y = int(total[1]/n) wrist = (x, y) #print 'wrist = ', wrist return wrist ''' simpl...
cnt = contours[ci] hull = cv2.convexHull(cnt) hull_idx = cv2.convexHull(cnt, returnPoints = False) return cnt, hull, hull_idx def draws_contour_hull(img, cnt, hull): #draws the image with only the contour and its convex hull drawing = np.zeros(img.shape, np.uint8) cv2.drawContours(drawin...
cnt = contours[i] area = cv2.contourArea(cnt) if(area > max_area): max_area = area ci = i
conditional_block
contour.py
0] - contour[set_idx_convDefs[i], 0, 0] #calcul x opposites[1,i] = 2*center[1] - contour[set_idx_convDefs[i], 0, 1] #calcul y total = np.sum(opposites, axis = 1) #print total x = int(total[0]/n) y = int(total[1]/n) wrist = (x, y) #print 'wrist = ', wrist return wrist ''' simple...
(img, backGround, thres_diff): height, width, depth = img.shape for i in range(height): for j in range(width): erase = True for k in range(depth): if(fabs(img[i,j,k] - backGround[i,j,k]) > thres_diff): erase = False if erase: ...
eliminate_background
identifier_name
app.js
setTimeout(function() { $(".alert").hide(); }, 2000); } /** * @function * @name loaderFadeOut * @description Disable loader **/ function loaderFadeOut() { setTimeout(function() { $("#overlay").fadeOut(300); }, 500); } /** * @function * @name restrictUsage * @description restrict bl...
**/ function formatItem(item) { return ( "<td>" + removeSingleQuotes(item.objectName) + "</td> <td> " + removeSingleQuotes(item.speed) + " </td> <td> " + removeSingleQuotes(item.lastEngineOnTime) + ' </td> <td class="objectID" style="display:none"> ' + ...
*
random_line_split
app.js
(function() { $(".alert").hide(); }, 2000); } /** * @function * @name loaderFadeOut * @description Disable loader **/ function loaderFadeOut() { setTimeout(function() { $("#overlay").fadeOut(300); }, 500); } /** * @function * @name restrictUsage * @description restrict blocks **/ f...
/** * @function * @name onError * @description Append dynamic error messages based on the API call **/ function onError(data) { loaderFadeOut(); var validateText = "Either API Key / Date is empty"; if (data.responseText == "") { data.responseText = validateText; } $("#ajax-alert").html...
{ $("#dateInput").css("display", "none"); $("#tbdata").hide(); $("#vcdata").empty(); $("#ajax-alert").css("display", "block"); }
identifier_body
app.js
var h = Math.floor((seconds % (3600 * 24)) / 3600); var m = Math.floor((seconds % 3600) / 60); var s = Math.floor(seconds % 60); var dDisplay = d > 0 ? d + (d == 1 ? " day ago " : " days ago ") : ""; var hDisplay = h > 0 ? h + (h == 1 ? "h ago " : "h ago ") : ""; var mDisplay = m > 0 ? m + (m ==...
addPolylineToMap
identifier_name
controller_commitstatus.go
o.onCommitStatusObj(obj, jxClient, ns) }, UpdateFunc: func(oldObj, newObj interface{}) { o.onCommitStatusObj(newObj, jxClient, ns) }, DeleteFunc: func(obj interface{}) { }, }, ) stop := make(chan struct{}) go commitstatusController.Run(stop) podListWatch := cache.NewListWatchFromClient(ku...
sourceUrl := "" branch := "" containers, _, _ := kube.GetContainersWithStatusAndIsInit(pod) for _, container := range containers { for _, e := range container.Env { switch e.Name { case "REPO_OWNER": org = e.Value case "REPO_NAME": repo = e.Value case "PULL_NU...
{ if pod != nil { labels := pod.Labels if labels != nil { buildName := labels[builds.LabelBuildName] if buildName == "" { buildName = labels[builds.LabelOldBuildName] } if buildName == "" { buildName = labels[builds.LabelPipelineRunName] } if buildName != "" { org := "" repo := ""...
identifier_body
controller_commitstatus.go
o.onCommitStatusObj(obj, jxClient, ns) }, UpdateFunc: func(oldObj, newObj interface{}) { o.onCommitStatusObj(newObj, jxClient, ns) }, DeleteFunc: func(obj interface{}) { }, }, ) stop := make(chan struct{}) go commitstatusController.Run(stop) podListWatch := cache.NewListWatchFromClient(ku...
case "PULL_NUMBER": pullRequest = fmt.Sprintf("PR-%s", e.Value) case "PULL_PULL_SHA": pullPullSha = e.Value case "PULL_BASE_SHA": pullBaseSha = e.Value case "JX_BUILD_NUMBER": jxBuildNumber = e.Value case "BUILD_NUMBER": buildNumber = e.Value case "...
{ org := "" repo := "" pullRequest := "" pullPullSha := "" pullBaseSha := "" buildNumber := "" jxBuildNumber := "" buildId := "" sourceUrl := "" branch := "" containers, _, _ := kube.GetContainersWithStatusAndIsInit(pod) for _, container := range containers { for _,...
conditional_block
controller_commitstatus.go
Number(v.PipelineActivity.Name)) if err != nil { return err } if lastBuildNumber < buildNumber { last = v } } err := o.update(&last, jxClient, ns) if err != nil { gitProvider, gitRepoInfo, err1 := o.getGitProvider(last.Commit.GitURL) if err1 != nil { return err1 } _, err1 = ext...
"lastCommitSha": sha, }, }, Spec: jenkinsv1.CommitStatusSpec{ Items: []jenkinsv1.CommitStatusDetails{
random_line_split
controller_commitstatus.go
_, err := jxClient.JenkinsV1().PipelineActivities(ns).PatchUpdate(act) if err != nil { // We can safely return this error as it will just get logged return err } } if org != "" && repo != "" && buildNumber != "" && (pullBaseSha != "" || pullPullSha != "") { log.Logger().Debugf("pod w...
getBuildNumber
identifier_name
touyou_case.py
1GC') #conf.set("spark.sql.warehouse.dir", warehouse_location) spark = SparkSession \ .builder \ .config(conf=conf) \ .enableHiveSupport() \ .getOrCreate() path_prefix = '/phoebus/_fileservice/users/slmp/shulianmingpin/midfile/qq' root_path = '/phoebus/_fileservice/users/slmp/shulianmingpin/wa_data/t...
'''写 parquet''' df.write.mode("overwrite").parquet(path=os.path.join(path_prefix,'parquet/',path)) def write_orc(df, path,mode='overwrite'): df.write.format('orc').mode(mode).save(path) logger.info('write success') def add_save_path(tablename, cp='', root='extenddir'): ''' 保存hive外表文件,分区默认为cp=...
uet(df,path):
identifier_name
touyou_case.py
(1) as num from zjhms where all.%s = zjhms.zjhm) != 0 '''%(start_key,end_key) res = spark.sql(sql) return res def inner_df_zjhm(df, zjhms, all_key='sfzh',find_key='zjhm'): ''' 是否存在 ''' df.createOrReplaceTempView('all') zjhms.createOrReplaceTempView('zjhms') sql = ''' select /*+ BROADCAST (zj...
write_orc(exists_travel_zjhm(trainline_travel,zjhms),root_path+'edge_person_with_trainline_travel/cp=2020') write_orc(exists_travel_zjhm(same_hotel_house,zjhms),root_path+'edge_same_hotel_house/cp=2020')
random_line_split
touyou_case.py
1GC') #conf.set("spark.sql.warehouse.dir", warehouse_location) spark = SparkSession \ .builder \ .config(conf=conf) \ .enableHiveSupport() \ .getOrCreate() path_prefix = '/phoebus/_fileservice/users/slmp/shulianmingpin/midfile/qq' root_path = '/phoebus/_fileservice/users/slmp/shulianmingpin/wa_data/t...
rson_smz_phone_top')) # # smz_res = smz.join(phones,phones['phone']==smz['end_phone'],'inner') \ # .selectExpr('start_person','end_phone','0 start_time','0 end_time') # # write_orc(smz_res, root_path + 'edge_person_smz_phone/cp=2020', ) def vertex_case_info(): cols = ['ajbh asjbh','...
reateOrReplaceTempView('dw') sql = ''' select /*+ BROADCAST (phones)*/ dw.* from dw inner join phones on dw.phone=phones.phone ''' res = spark.sql(sql) write_orc(res,root_path+'case_one_degree_dw/cp=%s'%cp) logger.info('%s dw down'%cp) phones.unpersist() # smz = read_orc(add_sav...
conditional_block
touyou_case.py
.createOrReplaceTempView('zjhms') sql = ''' select /*+ BROADCAST (zjhms)*/all.* from all inner join zjhms on all.%s=zjhms.%s''' % (all_key,find_key) res = spark.sql(sql) return res def find_one_degree_call(): phone_schema = StructType([ StructField("phone", StringType(), True) ]) p...
## 同出行信息,同房 airline_travel = read_orc(add_save_path('edge_person_with_airline_travel')) trainline_travel = read_orc(add_save_path('edge_person_with_trainline_travel')) same_hotel_house = read_orc(add_save_path('edge_same_hotel_house')) write_orc(exists_travel_zjhm(airline_travel,zjhms),root_path+'edge_...
identifier_body
gui_imageviewer.py
async def ViewImage(self, thefile="", url=""): """Loads url or file and sets .bmp and .bmp_transparent_ori, the img is discarded""" self.error_msg = None if thefile: img = wx.Image(thefile, wx.BITMAP_TYPE_ANY) bmp = wx.Bitmap(img) # ANDY added 2019 elif url...
if rendering: self.error_msg = "" self.fetching_msg = PLANTUML_VIEW_FETCHING_MSG self.fetching_started_time = datetime.datetime.utcnow() else: self.fetching_msg = "" # Update PlantUML view, guarding against the situation where when shutting down app ...
identifier_body
gui_imageviewer.py
x = int(self.maxWidth / newstep * self.zoomscale) newvirty = int(self.maxHeight / newstep * self.zoomscale) if printinfo: print(f"OUT step {newstep} new scroll {newscrollx}, {newscrolly} virt {newvirtx}, {newvirty} q {q}") self.SetScrollbars(...
OnMove
identifier_name
gui_imageviewer.py
size int(newscrollx), int(newscrolly), # new scroll positions noRefresh=True) # self.Refresh() if printinfo: print(self.GetVirtualSize()) def onKeyChar(self, event): if event.GetKeyCode() >= 256: event.Skip() ...
random_line_split
gui_imageviewer.py
scroll {oldscrollx}, {oldscrolly} virt {oldvirtx}, {oldvirty}") if newstep is not None: if oldstep == newstep: if printinfo: print(f"Nothing to do, step of {newstep} already set.") else: q = newstep / oldstep # min(1, newstep) ...
event.Skip() return
conditional_block
api_op_UpdateAnomalySubscription.go
AnomalySubscriptionInput, optFns ...func(*Options)) (*UpdateAnomalySubscriptionOutput, error) { if params == nil { params = &UpdateAnomalySubscriptionInput{} } result, metadata, err := c.invokeOperation(ctx, "UpdateAnomalySubscription", params, optFns, c.addOperationUpdateAnomalySubscriptionMiddlewares) if err !...
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { return err } if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = v4.AddComputePayloadSHA256Middleware(stack);...
return err }
conditional_block
api_op_UpdateAnomalySubscription.go
00,000,000 in string format. You can specify either Threshold or // ThresholdExpression, but not both. The following are examples of valid // ThresholdExpressions: // - Absolute threshold: { "Dimensions": { "Key": // "ANOMALY_TOTAL_IMPACT_ABSOLUTE", "MatchOptions": [ "GREATER_THAN_OR_EQUAL" ], // "Values": [...
dUpdateAnomalySubscriptionResolveEndpointMiddleware(s
identifier_name
api_op_UpdateAnomalySubscription.go
UpdateAnomalySubscriptionInput, optFns ...func(*Options)) (*UpdateAnomalySubscriptionOutput, error) { if params == nil { params = &UpdateAnomalySubscriptionInput{} } result, metadata, err := c.invokeOperation(ctx, "UpdateAnomalySubscription", params, optFns, c.addOperationUpdateAnomalySubscriptionMiddlewares) if...
} if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { return err } if err = addRetryMiddlewares(stack, options); err != nil { return err } if err = addHTTPSignerV4Middleware(stack, options); err != nil { retu...
random_line_split
api_op_UpdateAnomalySubscription.go
Percentage threshold: { "Dimensions": { "Key": // "ANOMALY_TOTAL_IMPACT_PERCENTAGE", "MatchOptions": [ "GREATER_THAN_OR_EQUAL" ], // "Values": [ "100" ] } } // - AND two thresholds together: { "And": [ { "Dimensions": { "Key": // "ANOMALY_TOTAL_IMPACT_ABSOLUTE", "MatchOptions": [ "GREATER_THAN_OR_EQUAL" ],...
return stack.Serialize.Insert(&opUpdateAnomalySubscriptionResolveEndpointMiddleware{ EndpointResolver: options.EndpointResolverV2, BuiltInResolver: &builtInResolver{ Region: options.Region, UseDualStack: options.EndpointOptions.UseDualStackEndpoint, UseFIPS: options.EndpointOptions.UseFIPSEndpo...
identifier_body
post_processing_gw.py
#only 1 separator data_array = re.split("#|/", ldata) #if the first item has length > 1 then we assume that it is a channel write key if len(data_array[0])>1: #insert '' to indicate default field data_array.insert(1,''); else: #insert '' to indicate default chann...
random_line_split
post_processing_gw.py
add_document(doc) def dht22_target(): while True: print "Getting gateway temperature" save_dht22_values() sys.stdout.flush() global _gw_dht22 time.sleep(_gw_dht22) #------------------------------------------------------------ #for managing the input data when we can have aes encryption #-------------...
#//////////////////////////////////////////////////////////// # ADD HERE OPTIONS THAT YOU MAY WANT TO ADD # BE CAREFUL, IT IS NOT ADVISED TO REMOVE OPTIONS UNLESS YOU # REALLY KNOW WHAT YOU ARE DOING #//////////////////////////////////////////////////////////// #-----------------------------------------------------...
global _linebuf_idx _linebuf_idx = 0 global _has_linebuf _has_linebuf = 1 global _linebuf # fill in our _linebuf from stdin _linebuf=sys.stdin.read(n)
identifier_body
post_processing_gw.py
s2value, ...] data_array = re.split("#|/", ldata) #just in case we have an ending CR or 0 data_array[len(data_array)-1] = data_array[len(data_array)-1].replace('\n', '') data_array[len(data_array)-1] = data_array[len(data_array)-1].replace('\0', '') #test if there are characters at th...
print("--> DATA encrypted: encrypted payload size is %d" % datalen) _hasClearData=0 if _aes==1: print("--> decrypting") decrypt_handler = AES.new(aes_key, AES.MODE_CBC, aes_iv) # decrypt s = decrypt_handler.decrypt(_linebuf) for i in range(0, len(s)): print ...
conditional_block
post_processing_gw.py
document add_document(doc) def dht22_target(): while True: print "Getting gateway temperature" save_dht22_values() sys.stdout.flush() global _gw_dht22 time.sleep(_gw_dht22) #------------------------------------------------------------ #for managing the input data when we can have aes encryption #----...
(): global _has_linebuf # if we have a valid _linebuf then read from _linebuf if _has_linebuf==1: global _linebuf_idx global _linebuf if _linebuf_idx < len(_linebuf): _linebuf_idx = _linebuf_idx + 1 return _linebuf[_linebuf_idx-1] else: # no more character from _linebuf, so read from stdin _has_l...
getSingleChar
identifier_name
edid.rs
Section 3.10.3. The // addresses and the contents of the four 18 byte descriptors are shown in Table 3.20. // // We leave the bottom 6 bytes of this block purposefully empty. let horizontal_blanking_lsb: u8 = (info.horizontal_blanking & 0xFF) as u8; let horizontal_blanking_msb: u8 = ((info.horizont...
{ edid[18] = 1; edid[19] = 4; }
identifier_body
edid.rs
{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.bytes[..].fmt(f) } } impl PartialEq for EdidBytes { fn eq(&self, other: &EdidBytes) -> bool { self.bytes[..] == other.bytes[..] } } #[derive(Copy, Clone)] pub struct Resolution { width: u32, height: u32, } impl Res...
(width: u32, height: u32) -> Resolution { Resolution { width, height } } fn get_aspect_ratio(&self) -> (u32, u32) { let divisor = gcd(self.width, self.height); (self.width / divisor, self.height / divisor) } } fn gcd(x: u32, y: u32) -> u32 { match y { 0 => x, _ ...
new
identifier_name
edid.rs
{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.bytes[..].fmt(f) } } impl PartialEq for EdidBytes { fn eq(&self, other: &EdidBytes) -> bool { self.bytes[..] == other.bytes[..] } } #[derive(Copy, Clone)] pub struct Resolution { width: u32, height: u32, } impl Res...
} } fn populate_display_name(edid_block: &mut [u8]) { // Display Product Name String Descriptor Tag edid_block[0..5].clone_from_slice(&[0x00, 0x00, 0x00, 0xFC, 0x00]); edid_block[5..].clone_from_slice("CrosvmDisplay".as_bytes()); } fn populate_detailed_timing(edid_block: &mut [u8], info: &DisplayInfo)...
calculate_checksum(&mut edid); Ok(OkEdid(Self { bytes: edid }))
random_line_split
edid.rs
; let horizontal_blanking_msb: u8 = ((info.horizontal_blanking >> 8) & 0x0F) as u8; let vertical_blanking_lsb: u8 = (info.vertical_blanking & 0xFF) as u8; let vertical_blanking_msb: u8 = ((info.vertical_blanking >> 8) & 0x0F) as u8; // The pixel clock is what controls the refresh timing information. ...
{ checksum = 255 - checksum + 1; }
conditional_block
off.rs
a>( num: usize, dim: usize, toks: &mut impl Iterator<Item = &'a str>, ) -> Vec<Point> { // Reads all vertices. let mut vertices = Vec::with_capacity(num); // Add each vertex to the vector. for _ in 0..num { let mut vert = Vec::with_capacity(dim); for _ in 0..dim { ...
rse_vertices<'
identifier_name
off.rs
list. for _ in 0..num_faces { let face_sub_num = next_tok(toks); let mut face = Element::new(); let mut face_verts = Vec::with_capacity(face_sub_num); // Reads all vertices of the face. for _ in 0..face_sub_num { face_verts.push(next_tok(toks)); } ...
/// A set of options to be used when saving the OFF file. #[derive(Clone, Copy)] pub struct OffOptions { /// Whether the OFF file should have comments specifying each face type. pub comments: bool, } impl Default for OffOptions { fn default() -> Self { OffOptions { comments: true } } } fn writ...
Ok(from_src(String::from_utf8(std::fs::read(fp)?).unwrap())) }
identifier_body
off.rs
else if c == '\n' { comment = false; } comment || c.is_whitespace() }) .filter(|s| !s.is_empty()) } /// Reads the next integer or float from the OFF file. fn next_tok<'a, T>(toks: &mut impl Iterator<Item = &'a str>) -> T where T: FromStr, <T as FromStr>::Err: std::fmt::Debu...
{ comment = true; }
conditional_block
off.rs
list. for _ in 0..num_faces { let face_sub_num = next_tok(toks); let mut face = Element::new(); let mut face_verts = Vec::with_capacity(face_sub_num); // Reads all vertices of the face. for _ in 0..face_sub_num { face_verts.push(next_tok(toks)); } ...
// Reads all sub-elements of the d-element. for _ in 0..el_sub_num { let el_sub = toks.next().expect("OFF file ended unexpectedly."); subs.push(el_sub.parse().expect("Integer parsing failed!")); } els_subs.push(Element { subs }); } els_subs } /// Build...
let el_sub_num = next_tok(toks); let mut subs = Vec::with_capacity(el_sub_num);
random_line_split
plan.py
Optional[bool] = True @property def point(self) -> Point: """The coordinate of this starting location.""" return Point.from_np_array(self.position) @classmethod def from_pose(cls, pose: Pose): """Convert to a starting location from a pose.""" return cls( po...
# now check its heading to ensure it was going in roughly the right direction for this lane end_vec = nl.vector_at_offset(nl.length - 0.1) end_heading = vec_to_radians(end_vec[:2]) heading_err = min_angles_difference_signed(end_heading, veh_heading) return abs(heading_err) < mat...
if nl.outgoing_lanes or dist < 0.5 * nl_width + 1e-1: return False # the last lane it was in was not a dead-end, or it's still in a lane if offset < nl.length - 2 * nl_width: return False # it's no where near the end of the lane
conditional_block
plan.py
: Optional[bool] = True @property def point(self) -> Point: """The coordinate of this starting location.""" return Point.from_np_array(self.position) @classmethod def from_pose(cls, pose: Pose): """Convert to a starting location from a pose.""" return cls( p...
class TraverseGoal(Goal): """A TraverseGoal is satisfied whenever an Agent-driven vehicle successfully finishes traversing a non-closed (acyclic) map It's a way for the vehicle to exit the simulation successfully, for example, driving across from one side to the other on a straight road and then con...
random_line_split
plan.py
Optional[bool] = True @property def point(self) -> Point: """The coordinate of this starting location.""" return Point.from_np_array(self.position) @classmethod def from_pose(cls, pose: Pose): """Convert to a starting location from a pose.""" return cls( po...
nearest_lanes = self.road_map.nearest_lanes(veh_pos) if not nearest_lanes: return False # we can't tell anything here nl, dist = nearest_lanes[0] offset = nl.to_lane_coord(veh_pos).s nl_width, conf = nl.width_at_offset(offset) if conf > 0.5: if nl...
"""A TraverseGoal is satisfied whenever an Agent-driven vehicle successfully finishes traversing a non-closed (acyclic) map It's a way for the vehicle to exit the simulation successfully, for example, driving across from one side to the other on a straight road and then continuing off the map. This goal...
identifier_body
plan.py
Optional[bool] = True @property def point(self) -> Point: """The coordinate of this starting location.""" return Point.from_np_array(self.position) @classmethod def
(cls, pose: Pose): """Convert to a starting location from a pose.""" return cls( position=pose.as_position2d(), heading=pose.heading, from_front_bumper=False, ) @dataclass(frozen=True, unsafe_hash=True) class Goal: """Describes an expected end state for ...
from_pose
identifier_name
__init__.py
Template('((THPTensor*)$arg)->cdata') For a simpler type, such as a long, we could do: Template('PyLong_AsLong($arg)') though in practice we will use our own custom unpacking code. Once again, $arg must be used as the identifier. Args: arg: a Python objec...
corresponding C types. The type is once again accessible via arg['type']. This time we return a Template string that unpacks an object. For a THTensor*, we know that the corresponding PyTorch type is a THPTensor*, so we need to get the cdata from the object. So we would return:
random_line_split
__init__.py
object. For a THTensor*, we know that the corresponding PyTorch type is a THPTensor*, so we need to get the cdata from the object. So we would return: Template('((THPTensor*)$arg)->cdata') For a simpler type, such as a long, we could do: Template('PyLong_AsLong($arg)')...
def process_single_check(self, code, arg, arg_accessor): """Used to postprocess a type check. Above we defined a function get_type_check that returns a Template string that allows for type checking a PyObject * for a specific type. In this function, the passed "code" is a combinat...
"""Used to modify the code for the entire output file. The last thing any plugin can do. Code contains the results of wrapping all the declarations. The plugin can do things like adding header guards, include statements, etc. Args: code: a string source code for the wrapped...
identifier_body
__init__.py
object. For a THTensor*, we know that the corresponding PyTorch type is a THPTensor*, so we need to get the cdata from the object. So we would return: Template('((THPTensor*)$arg)->cdata') For a simpler type, such as a long, we could do: Template('PyLong_AsLong($arg)') ...
(self, declaration): """Used to create a code template to wrap the options. This function returns a Template string that contains the function call for the overall declaration, including the method definition, opening and closing brackets, and any additional code within the method body....
get_wrapper_template
identifier_name
lib.rs
sky_t: Vec<f32>, phantom: PhantomData<&'a f32>, } // ``` // Documentation // Creation function // ``` impl <'a> Obs <'a> { pub fn new( start: String, stop: String, detector: Vec<String>, mc_id: u8, alpha: f32, f_knee: f32, tod: Vec<Vec<f32>>, ...
pub fn get_pix(&self) -> &Vec<Vec<i32>> { &self.pix } pub fn get_tod(&self) -> &Vec<Vec<f32>> { &self.tod } } // Mitigation of the systematic effects // Starting from the binning, to the // implementation of a de_noise model impl <'a> Obs <'a>{ pub fn binning(&self) -> (Vec<f32>, ...
{ &self.mc_id }
identifier_body
lib.rs
sky_t: Vec<f32>, phantom: PhantomData<&'a f32>, } // ``` // Documentation // Creation function // ``` impl <'a> Obs <'a> { pub fn new( start: String, stop: String, detector: Vec<String>, mc_id: u8, alpha: f32, f_knee: f32, tod: Vec<Vec<f32>>, ...
(&self) -> &Vec<Vec<i32>> { &self.pix } pub fn get_tod(&self) -> &Vec<Vec<f32>> { &self.tod } } // Mitigation of the systematic effects // Starting from the binning, to the // implementation of a de_noise model impl <'a> Obs <'a>{ pub fn binning(&self) -> (Vec<f32>, Vec<i32>) { ...
get_pix
identifier_name
lib.rs
sky_t: Vec<f32>, phantom: PhantomData<&'a f32>, } // ``` // Documentation // Creation function // ``` impl <'a> Obs <'a> { pub fn new( start: String, stop: String, detector: Vec<String>, mc_id: u8, alpha: f32, f_knee: f32, tod: Vec<Vec<f32>>, ...
} return Obs { start, stop, detector, mc_id, alpha, f_knee, pix, tod: tod_final, sky_t: sky, phantom: PhantomData, ...
tod_final.push(tmp);
random_line_split
timeline.js
if(Player.active && !Player.active.on && Player.active.getVideoBytesLoaded && Player.activeData) { var rateStart = 1e10, stats, dtime, ctime, frac; if(!isMobile) { dtime = Player.active.getDuration() || 0; ctime = Player.active.getCurrentTime() ...
if(Scrubber.real.attach(entry.jquery.timeline)) { entry.jquery.timeline.css('display','block'); } } else { Scrubber.real.remove(); } // For some reason it appears that this value can // toggle back to different quality sometimes. So // ...
{ var time = Player.active.getCurrentTime(), prevOffset = _offset; if(Player.activeData) { localStorage[ev.db.id + 'offset'] = [Player.activeData.ytid, time].join(' '); } if (time > 0 && Player.activeData) { // This generates the scrubber in the results tab below. ...
conditional_block
timeline.js
() { // This is the "clock" that everything is rated by. var // The tick is the clock-time ... this is different from the // _offset which is where we should be in the playlist tick = ev.incr('tick'), scrubberPosition = 0; // Make sure we aren't the backup player if(Player.act...
updateytplayer
identifier_name
timeline.js
if(Player.active && !Player.active.on && Player.active.getVideoBytesLoaded && Player.activeData) { var rateStart = 1e10, stats, dtime, ctime, frac; if(!isMobile) { dtime = Player.active.getDuration() || 0; ctime = Player.active.getCurrentTime() ...
log('set-quality'); /Player.active.setPlaybackQuality(_quality); } */ // There's this YouTube bug (2013/05/11) that can sometimes report // totally incorrect values for the duration. If it's more than // 20 seconds off and greater than 0, then we try to rel...
random_line_split
timeline.js
if(Player.active && !Player.active.on && Player.active.getVideoBytesLoaded && Player.activeData) { var rateStart = 1e10, stats, dtime, ctime, frac; if(!isMobile) { dtime = Player.active.getDuration() || 0; ctime = Player.active.getCurrentTime() ...
self.onPlayerStateChange = function(e) { if(e.target === Player.eager) { return; } if(e.data === 1) { if(_offsetRequest) { if( e.target.getVideoUrl && e.target.getVideoUrl().search(_offsetRequest.id) !== -1 && Math.abs(_offsetRequest.offset - e.target.getCu...
{ _.each(Player.eventList, function(what) { Player.controls.addEventListener("on" + what, 'ytDebug_' + what); }); }
identifier_body
geneOverlap.v01.py
## Column for coding or non-coding, if info not available then mention 99 makeDB = 0 ## If DB for GTF file is not present in present directory then make : 1 else: 0 ## IMPORTS ############################################ import os,sys import sqlite3 ## FUNCTION...
## Test DB cur = conn.cursor() ## Test # cur.execute("PRAGMA table_info(%s)" % (annotable)) # desc = cur.fetchall() # print(desc) # cur.execute("SELECT geneName FROM %s LIMIT 10" % (annotable)) # test = cur.fetchall() # print(test) outFile = "%s.overlap.txt" % summary.rpartition...
print("Function: overlapCheck")
random_line_split
geneOverlap.v01.py
## Column for coding or non-coding, if info not available then mention 99 makeDB = 0 ## If DB for GTF file is not present in present directory then make : 1 else: 0 ## IMPORTS ############################################ import os,sys import sqlite3 ## FUNCTION...
(summary): '''Create a a list of summary file''' print("\nFunction: summParser") fh_in = open(summary,'r') if head == 'Y': fh_in.readline() summRead = fh_in.readlines() geneSet = set() # for i in summRead: # ent = i.split("\t") # agene = ent[gene-1] # ...
summParser
identifier_name
geneOverlap.v01.py
## Column for coding or non-coding, if info not available then mention 99 makeDB = 0 ## If DB for GTF file is not present in present directory then make : 1 else: 0 ## IMPORTS ############################################ import os,sys import sqlite3 ## FUNCTION...
## Protein coding gene with a version number gid = info[0].split()[1].replace('"','') gVer = info[1].split()[1].replace('"','') gSource = info[2].split()[1].replace('"','') gType = info[3].split()[1].replace('"','') ...
print("Function: gtfParser") ## file I/O fh_in = open(gtf,'r') gtfRead = fh_in.readlines() parsedGTF = [] ## List to hold parsed GTF entries for i in gtfRead: if i[0].isdigit(): ent = i.split("\t") if ent[2] == "gene": # print(ent) a...
identifier_body
geneOverlap.v01.py
## Column for coding or non-coding, if info not available then mention 99 makeDB = 0 ## If DB for GTF file is not present in present directory then make : 1 else: 0 ## IMPORTS ############################################ import os,sys import sqlite3 ## FUNCTION...
fh_out.close() fh_in.close() print("Exiting function - overlapCheck\n") return outFile def gtfParser(gtf): print("Function: gtfParser") ## file I/O fh_in = open(gtf,'r') gtfRead = fh_in.readlines() parsedGTF = [] ## List to hold parsed GTF entries for i in gtfRead: ...
fh_out.write("%s\tNA\tNA\tNA\n" % (trans))
conditional_block
AntUtils.go
Col Atom = 0x15003 Colgroup Atom = 0x15008 Color Atom = 0x15d05 Cols Atom = 0x16204 Colspan Atom = 0x16207 Command Atom = 0x17507 Content Atom = 0x42307 Contenteditable Atom = 0x4230f Contextmenu At...
Class Atom = 0x4de05 Code Atom = 0x14904
random_line_split
AntUtils.go
func ConvertUTF8(text1 string) string { data, _ := ioutil.ReadAll(transform.NewReader(bytes.NewReader([]byte(text1)), simplifiedchinese.GBK.NewEncoder())) text := string(data) return text } func GetAtomByString(a string) atom.Atom { switch a { case "A": return atom.A case "Abbr": return atom.Abbr case "A...
{ data, _ := ioutil.ReadAll(transform.NewReader(bytes.NewReader([]byte(text1)), simplifiedchinese.GBK.NewDecoder())) text := string(data) return text }
identifier_body
AntUtils.go
(text1 string) string { data, _ := ioutil.ReadAll(transform.NewReader(bytes.NewReader([]byte(text1)), simplifiedchinese.GBK.NewEncoder())) text := string(data) return text } func GetAtomByString(a string) atom.Atom { switch a { case "A": return atom.A case "Abbr": return atom.Abbr case "Accept": return a...
ConvertUTF8
identifier_name
info_frames.py
uple[str, ValueEle, Any, Any]]: for key, (original_val, val_ele) in self._tag_vals_and_eles.items(): if (value := val_ele.value) != original_val: yield key, val_ele, original_val, value def reset_tag_values(self): for key, val_ele, original_val, value in self._iter_chang...
def disable(self): if self.disabled: return super().disable() self.edit_buttons_frame.hide() self.view_buttons_frame.show() def _update_numbered_type(self, var_name, unknown, action): # Registered as a change_cb for `type` and `number` num_ele: Inpu...
if not self.disabled: return super().enable() self.view_buttons_frame.hide() self.edit_buttons_frame.show()
identifier_body
info_frames.py
uple[str, ValueEle, Any, Any]]: for key, (original_val, val_ele) in self._tag_vals_and_eles.items(): if (value := val_ele.value) != original_val: yield key, val_ele, original_val, value def reset_tag_values(self): for key, val_ele, original_val, value in self._iter_chang...
(self): if not self.disabled: return super().enable() self.view_buttons_frame.hide() self.edit_buttons_frame.show() def disable(self): if self.disabled: return super().disable() self.edit_buttons_frame.hide() self.view_buttons_...
enable
identifier_name
info_frames.py
uple[str, ValueEle, Any, Any]]: for key, (original_val, val_ele) in self._tag_vals_and_eles.items(): if (value := val_ele.value) != original_val: yield key, val_ele, original_val, value def reset_tag_values(self): for key, val_ele, original_val, value in self._iter_chang...
val_ele = _genre_list_box(value, self.album_info, disabled, key=key) elif key in {'mp4', 'solo_of_group'}: kwargs['disabled'] = True if key == 'mp4' else disabled val_ele = CheckBox('', default=value, pad=(0, 0), key=key, **kwargs) else: ...
types.append(value) val_ele = Combo( types, value, size=(48, None), disabled=disabled, key=key, change_cb=self._update_numbered_type ) elif key == 'genre':
random_line_split
info_frames.py
uple[str, ValueEle, Any, Any]]: for key, (original_val, val_ele) in self._tag_vals_and_eles.items(): if (value := val_ele.value) != original_val: yield key, val_ele, original_val, value def reset_tag_values(self): for key, val_ele, original_val, value in self._iter_chang...
super().disable() self.edit_buttons_frame.hide() self.view_buttons_frame.show() def _update_numbered_type(self, var_name, unknown, action): # Registered as a change_cb for `type` and `number` num_ele: Input = self._tag_vals_and_eles['number'][1] value = '' t...
return
conditional_block
input_subset_image_labels.py
3, # motorcycle '/m/07jdr': 4, # train '/m/07r04': 5, # truck '/m/01g317': 6, # human (person originally but may include also rider) '/m/04yx4': 7, # man '/m/03bt1vf': 8, # woman '/m/01bl7v': 9, # boy '/m/05r655': 10, # girl...
(filepath): """outputs an image (np.float32, 3D) and the generated weak labels from image-level labels (np.float32, 3D) """ with open(filepath, 'rb') as fp: imageid2mids = pickle.load(fp) for imageid, mids in imageid2mids.items(): Np = MAX_N_MIDS - len(mids) if Np < 0: tf.logging.warn(...
_imageid_and_mids_generator
identifier_name
input_subset_image_labels.py
(person originally but may include also rider) '/m/04yx4': 7, # man '/m/03bt1vf': 8, # woman '/m/01bl7v': 9, # boy '/m/05r655': 10, # girl '/m/015qff': 11, # traffic light '/m/01mqdt': 12, # traffic sign '/m/02pv19': 13, # stop sign...
# dataset = dataset.batch(params.Nb) # def _grouping(rim, rla, pim, pla, imp, lap): # # group dataset elements as required by estimator
random_line_split
input_subset_image_labels.py
3, # motorcycle '/m/07jdr': 4, # train '/m/07r04': 5, # truck '/m/01g317': 6, # human (person originally but may include also rider) '/m/04yx4': 7, # man '/m/03bt1vf': 8, # woman '/m/01bl7v': 9, # boy '/m/05r655': 10, # girl...
def _generate_rla(imageid, mids, rim_size): # mids: binary np.string, (Nlabels,) # coords_normalized: np.float32, (Nlabels, 4) # rim_size: np.int32, (2,) mids = list(mids) # zeros_slice = np.zeros(rim_size, dtype=np.float32) # ones_slice = np.ones(rim_size, dtype=np.float32) # mid_column = np.zeros((len...
"""outputs an image (np.float32, 3D) and the generated weak labels from image-level labels (np.float32, 3D) """ with open(filepath, 'rb') as fp: imageid2mids = pickle.load(fp) for imageid, mids in imageid2mids.items(): Np = MAX_N_MIDS - len(mids) if Np < 0: tf.logging.warn(f'Np = {Np}.')...
identifier_body
input_subset_image_labels.py
3, # motorcycle '/m/07jdr': 4, # train '/m/07r04': 5, # truck '/m/01g317': 6, # human (person originally but may include also rider) '/m/04yx4': 7, # man '/m/03bt1vf': 8, # woman '/m/01bl7v': 9, # boy '/m/05r655': 10, # girl...
# if empty change the void cid to one if turn_on_void: rla[-1] = 1. # per-pixel normalize rla to a dense multinomial distribution rla /= np.sum(rla) # let TF do the tiling as it is faster # rla = np.tile(rla, (*rim_size, 1)) # assert np.all(np.abs(np.sum(rla, axis=2) - np.ones(rla.shape[:2], dtype=np...
rla[cid] = 1. turn_on_void = False
conditional_block
models.py
1 = nn.Conv1d(hidden_units, hidden_units, kernel_size=1) self.dropout1 = nn.Dropout(p=dropout_rate) self.relu = nn.ReLU() self.conv2 = nn.Conv1d(hidden_units, hidden_units, kernel_size=1) self.dropout2 = nn.Dropout(p=dropout_rate) def forward(self, inputs): outputs = self.dr...
inputs,pos,xtsy = data[:,:,3],data[:,:,5],data[:,:,6] # unbatch indices ci = torch.nonzero(inputs, as_tuple=False) flat_xtsy = xtsy[ci[:,0],ci[:,1]] av = self.args.av_tens[flat_xtsy,:] av_embs = self.item_embedding(av) # repeat consumption: time interval emb...
return None
conditional_block
models.py
.conv1 = nn.Conv1d(hidden_units, hidden_units, kernel_size=1) self.dropout1 = nn.Dropout(p=dropout_rate) self.relu = nn.ReLU() self.conv2 = nn.Conv1d(hidden_units, hidden_units, kernel_size=1) self.dropout2 = nn.Dropout(p=dropout_rate) def forward(self, inputs): outputs = se...
av = torch.LongTensor(self.args.ts[step]).to(self.args.device) av_embs = self.item_embedding(av) if self.args.fr_ctx: ctx_expand = torch.zeros(self.args.av_tens.shape[1],self.args.K,device=self.args.device) ctx_expand[batch_inds[b,-1,:],:] =...
inputs = data[:,:,3] # inputs pos = data[:,:,5] # targets xtsy = data[:,:,6] # targets ts feats = self(inputs) # Add time interval embeddings if self.args.fr_ctx: ctx,batch_inds = self.get_ctx_att(data,feats) # identify repeated interactions ...
identifier_body
models.py
1 = nn.Conv1d(hidden_units, hidden_units, kernel_size=1) self.dropout1 = nn.Dropout(p=dropout_rate) self.relu = nn.ReLU() self.conv2 = nn.Conv1d(hidden_units, hidden_units, kernel_size=1) self.dropout2 = nn.Dropout(p=dropout_rate) def forward(self, inputs): outputs = self.dr...
(self, data, use_ctx=False): # for training inputs,pos = data[:,:,3],data
train_step
identifier_name
models.py
.attention_layers = nn.ModuleList() self.forward_layernorms = nn.ModuleList() self.forward_layers = nn.ModuleList() self.last_layernorm = nn.LayerNorm(args.K, eps=1e-8) for _ in range(num_att): new_attn_layernorm = nn.LayerNorm(args.K, eps=1e-8) self.atte...
def get_av_rep(self,data): bs = data.shape[0] inputs = data[:,:,3] # inputs xtsb = data[:,:,2] # inputs ts xtsy = data[:,:,6] # targets ts
random_line_split
bindings.rs
for details of how `xmodmap` is used. pub fn parse_keybindings_with_xmodmap<S, X>( str_bindings: HashMap<S, Box<dyn KeyEventHandler<X>>>, ) -> Result<KeyBindings<X>> where S: AsRef<str>, X: XConn, { let m = keycodes_from_xmodmap()?; str_bindings .into_iter() .map(|(s, v)| parse_bin...
{ self.button.into() }
identifier_body
bindings.rs
[keycodes_from_xmodmap] for details of how `xmodmap` is used. pub fn parse_keybindings_with_xmodmap<S, X>( str_bindings: HashMap<S, Box<dyn KeyEventHandler<X>>>, ) -> Result<KeyBindings<X>> where S: AsRef<str>, X: XConn, { let m = keycodes_from_xmodmap()?; str_bindings .into_iter() ...
random_line_split
bindings.rs
)? .lines() .flat_map(|l| { let mut words = l.split_whitespace(); // keycode <code> = <names ...> let key_code: u8 = match words.nth(1) { Some(word) => match word.parse() { Ok(val) => val, Err(e) => panic!("{}", e), ...
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("KeyEventHandler").finish() } } impl<F, X> MouseEventHandler<X> for F where F: FnMut(&MouseEvent, &mut State<X>, &X) -> Result<()>, X: XConn, { fn call(&mut self, evt: &MouseEvent, state: &mut State<X>, x: &X) -> Result<()> { ...
fmt
identifier_name
pulseoxLoader.py
_data = self.csv_to_data(fpath, **kwargs) data_candidates.append(temp_data) self.data = np.concatenate(data_candidates) self.data = normalize(self.data) return self.data def csv_to_data(self, fpath, **kwargs): ''' convert the passed file path fpath to a...
if args['plot']: plt.clf() wave = np.array(result, copy=True) self.impute_wave(wave) if args['smoothing'] == 'gaussian': wave = gaussian_filter1d(wave, args['sigma']) else: self.moving_avg(wave, args['sigma']) ...
''' Pre-process the given dataframe df (obtained using the day_to_df function) to space all points into time buckets so FFT output is meaningful. Then perform imputation to create the envalope of the waveform, and run a amoving average filter kernel of size avg_size on it. p...
identifier_body
pulseoxLoader.py
) for index, row in label_df.iterrows(): state = row['Label'] if state == 'eating': ate = True labels[row['Start_min']:row['End_min']] = eat elif state == 'break' and not ate: labels[row['Start_min']:row['End_min']] = pre...
plot_fft
identifier_name
pulseoxLoader.py
_data = self.csv_to_data(fpath, **kwargs) data_candidates.append(temp_data) self.data = np.concatenate(data_candidates) self.data = normalize(self.data) return self.data def csv_to_data(self, fpath, **kwargs): ''' convert the passed file path fpath to a...
result = np.zeros(np.max(df['DateTime'])+1) # TODO: fix this, DateTimes come in duplicate pairs result[df['DateTime']] = df['Data/Duration'] if args['plot']: plt.clf() wave = np.array(result, copy=True) self.impute_wave(wave) i...
if key in args: args[key] = value
conditional_block
pulseoxLoader.py
temp_data = self.csv_to_data(fpath, **kwargs) data_candidates.append(temp_data) self.data = np.concatenate(data_candidates) self.data = normalize(self.data) return self.data def csv_to_data(self, fpath, **kwargs): ''' convert the passed file...
if fpath == self.label_path: continue
random_line_split
pack.rs
, Debug, Serialize, Deserialize)] pub struct PackHeader { /// Valid pack headers have this value set to [`PACK_HEADER_MAGIC`]. magic: u64, /// The list of frames in the pack file, sorted by their byte offsets. frames: Vec<PackFrame>, } impl PackHeader { /// Create a new pack header. pub fn new(...
{ return Err(PackError::ChecksumMismatch(*exp_checksum, checksum).into()); }
conditional_block
pack.rs
} } /// Verifies the header magic. pub fn is_valid(&self) -> bool { self.magic == PACK_HEADER_MAGIC } } impl Default for PackHeader { fn default() -> Self { Self { magic: PACK_HEADER_MAGIC, frames: vec![], } } } /// Represents an pack fil...
compute_frame_offsets
identifier_name
pack.rs
_time = std::time::Instant::now(); let results = run_in_parallel( num_workers as usize, tasks.into_iter(), |(frame_reader, entries)| extract_files(frame_reader, &entries, &output_dir, verify), ); // Collect stats let stats = results .into_i...
assert!(!PackId::is_valid("Some Text")); // non-latin alphabets assert!(!PackId::is_valid("това-е-тест"));
random_line_split
app.py
ElementEmbedder def _retrieve_token(request): """Retrieve NEXUS token from the request header.""" auth_string = request.headers.get('Authorization') try: match = re.match("Bearer (.+)", auth_string) except TypeError: match = None if match: return match.groups()[0] def dig...
result = [ {point: dist[i].tolist()[j] for j, point in enumerate(el)} for i, el in enumerate(similar_points) ]
conditional_block
app.py
"""Main embedding service app.""" import json import os import shutil import re import time from flask import Flask, request from kgforge.core import KnowledgeGraphForge from bluegraph import PandasPGFrame from bluegraph.downstream import EmbeddingPipeline from bluegraph.core import GraphElementEmbedder def _retri...
for i, points in enumerate(similar_points) } else: result = { indices[i]: list(points) if points is not None else None for i, points in enumerate(similar_points) } else: content = request.get_json() vectors =...
"""Handle request of similar points to provided resources.""" if model_name not in app.models: return _respond_not_found() pipeline = app.models[model_name]["object"] params = request.args.to_dict(flat=False) k = int(params["k"][0]) values = ( params["values"][0] == "True" if "value...
identifier_body
app.py
"""Main embedding service app.""" import json import os import shutil import re import time from flask import Flask, request from kgforge.core import KnowledgeGraphForge from bluegraph import PandasPGFrame from bluegraph.downstream import EmbeddingPipeline from bluegraph.core import GraphElementEmbedder def _retri...
else: content = request.get_json() vectors = content["v
indices[i]: list(points) if points is not None else None for i, points in enumerate(similar_points) }
random_line_split
app.py
Main embedding service app.""" import json import os import shutil import re import time from flask import Flask, request from kgforge.core import KnowledgeGraphForge from bluegraph import PandasPGFrame from bluegraph.downstream import EmbeddingPipeline from bluegraph.core import GraphElementEmbedder def _retrieve...
(model_name): """Handle request of embedding vectors for provided resources.""" if model_name in app.models: pipeline = app.models[model_name]["object"] if request.method == "GET": params = request.args.to_dict(flat=False) indices = params["resource_ids"] embe...
handle_embeddings_request
identifier_name
RealSolver.py
''' Kaden Archibald Created: Oct 11, 2018 Revised: Jul 13, 2019 Version: IPython 7.2.0 (Anaconda distribution) with Python 3.7.1 Module for numerically solving arbitrary real-valued functions in a single vairable. ''' import const #import data ''' Driver function to hide object intialization from en...
if abs(self.f(root)) < const.maxError: break else: if signCheck > 0: lowerBound = root if signCheck < 0: upperBound = root except (ValueError, ZeroDivisionEr...
# estimated root to decide which bound to discard. try:
random_line_split
RealSolver.py
''' Kaden Archibald Created: Oct 11, 2018 Revised: Jul 13, 2019 Version: IPython 7.2.0 (Anaconda distribution) with Python 3.7.1 Module for numerically solving arbitrary real-valued functions in a single vairable. ''' import const #import data ''' Driver function to hide object intialization from en...
''' Employ Newton's Method of numerically converging on a root using a function's derivative: X(i+1) = X(i) - f(X(i))/g(X(i)) Where f is the target function, g is that function's derivative, and i is the current iteration. ''' def newtonRaphson(self) -> flo...
isVerified = False try: if abs(self.f(potentialRoot)) <= const.maxError: self.opLog.append(name + ' verified\n') isVerified = True else: self.opLog.append(name + ' converged to incorrect value\n') except V...
identifier_body
RealSolver.py
''' Kaden Archibald Created: Oct 11, 2018 Revised: Jul 13, 2019 Version: IPython 7.2.0 (Anaconda distribution) with Python 3.7.1 Module for numerically solving arbitrary real-valued functions in a single vairable. ''' import const #import data ''' Driver function to hide object intialization from en...
: ''' Create an object that contains a function to be solved, one (or two) initial guesses, a function for the derivative, auxiliary precalculated arguements for a function, and data about the root solving problem itself: a maximum error, a maximum number of iterations, and a string array...
RealSolver
identifier_name
RealSolver.py
''' Kaden Archibald Created: Oct 11, 2018 Revised: Jul 13, 2019 Version: IPython 7.2.0 (Anaconda distribution) with Python 3.7.1 Module for numerically solving arbitrary real-valued functions in a single vairable. ''' import const #import data ''' Driver function to hide object intialization from en...
except ValueError: self.opLog.append(name + ' returned an undefined value\n') except TypeError: if self.root is None: self.opLog.append('root not updated in meta data\n') return isVerified ...
self.opLog.append(name + ' converged to incorrect value\n')
conditional_block
mod.rs
EffectType, FormatConverterType, GeneratorType, IOType, MixerType, MusicDeviceType, Type, }; #[cfg(target_os = "macos")] pub mod macos_helpers; pub mod audio_format; pub mod render_callback; pub mod sample_format; pub mod stream_format; pub mod types; /// The input and output **Scope**s. /// /// More info [here]...
pub use self::audio_format::AudioFormat; pub use self::sample_format::{Sample, SampleFormat}; pub use self::stream_format::StreamFormat; pub use self::types::{
random_line_split