file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
MessageSigner.go
// Package messaging for signing and encryption of messages package messaging import ( "crypto/ecdsa" "crypto/rand" "crypto/sha256" "encoding/asn1" "encoding/base64" "encoding/json" "errors" "fmt" "reflect" "github.com/iotdomain/iotdomain-go/types" "github.com/sirupsen/logrus" "gopkg.in/square/go-jose.v2"...
(message string, publicKey *ecdsa.PublicKey) (serialized string, err error) { var jwe *jose.JSONWebEncryption recpnt := jose.Recipient{Algorithm: jose.ECDH_ES, Key: publicKey} encrypter, err := jose.NewEncrypter(jose.A128CBC_HS256, recpnt, nil) if encrypter != nil { jwe, err = encrypter.Encrypt([]byte(message)...
EncryptMessage
identifier_name
MessageSigner.go
// Package messaging for signing and encryption of messages package messaging import ( "crypto/ecdsa" "crypto/rand" "crypto/sha256" "encoding/asn1" "encoding/base64" "encoding/json" "errors" "fmt" "reflect" "github.com/iotdomain/iotdomain-go/types" "github.com/sirupsen/logrus" "gopkg.in/square/go-jose.v2"...
// Unsubscribe to messages on the given address func (signer *MessageSigner) Unsubscribe( address string, handler func(address string, message string) error) { signer.messenger.Unsubscribe(address, handler) } // PublishEncrypted sign and encrypts the payload and publish the resulting message on the given address ...
{ signer.messenger.Subscribe(address, handler) }
identifier_body
main.rs
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use anyhow; use fuchsia_async; use futures::future::join_all; use io::BufWriter; use json5format::{Json5Format, ParsedDocument}; use std::{ ffi::OsStri...
let filter = String::from("{foo: .foo, baz: .bar}"); let json5_string = String::from( r##"{ //Foo foo: 0, //Bar bar: 42 }"##, ); let format = Json5Format::new().unwrap(); let (parsed_json5, json_string) = reader::read_json5(json5_string).unwrap(); let ...
); } #[fuchsia_async::run_singlethreaded(test)] async fn run_jq5_deconstruct_filter() {
random_line_split
main.rs
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use anyhow; use fuchsia_async; use futures::future::join_all; use io::BufWriter; use json5format::{Json5Format, ParsedDocument}; use std::{ ffi::OsStri...
#[fuchsia_async::run_singlethreaded(test)] async fn run_jq5_deconstruct_filter() { let filter = String::from("{foo: .foo, baz: .bar}"); let json5_string = String::from( r##"{ //Foo foo: 0, //Bar bar: 42 }"##, ); let format = Json5Format::new().unwrap(); ...
{ let filter = String::from("{foo2: .foo1, bar2: .bar1}"); let input = String::from(r#"{"foo1": 0, "bar1": 42}"#); let jq_path = Some(PathBuf::from(JQ_PATH_STR)); assert_eq!( run_jq(&filter, input, &jq_path).await.unwrap(), r##"{ "foo2": 0, "bar2": 42 } "## ...
identifier_body
main.rs
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use anyhow; use fuchsia_async; use futures::future::join_all; use io::BufWriter; use json5format::{Json5Format, ParsedDocument}; use std::{ ffi::OsStri...
( filter: &String, file: &PathBuf, jq_path: &Option<PathBuf>, ) -> Result<String, anyhow::Error> { let (parsed_json5, json_string) = reader::read_json5_fromfile(&file)?; run_jq5(&filter, parsed_json5, json_string, jq_path).await } async fn run( filter: String, files: Vec<PathBuf>, jq_pa...
run_jq5_on_file
identifier_name
main.rs
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use anyhow; use fuchsia_async; use futures::future::join_all; use io::BufWriter; use json5format::{Json5Format, ParsedDocument}; use std::{ ffi::OsStri...
else { Err(anyhow::anyhow!("jq returned exit code 0 but no output or error message")) } } /// Calls jq on the provided json and then fills back comments at correct places. async fn run_jq5( filter: &String, parsed_json5: ParsedDocument, json_string: String, jq_path: &Option<PathBuf>, ) -> ...
{ Err(anyhow::anyhow!("jq returned with non-zero exit code but no error message")) }
conditional_block
DAQClient.py
#!/usr/bin/env python import os, socket, sys, threading from CnCLogger import CnCLogger from DAQRPC import RPCClient from RunSet import RunSet from UniqueID import UniqueID from exc_string import exc_string, set_exc_string_encoding set_exc_string_encoding("ascii") # Find install location via $PDAQ_HOME, otherwise u...
def mbeanPort(self): return self.__mbeanPort def monitor(self): "Return the monitoring value" return self.state() def order(self): return self.__cmdOrder def port(self): return self.__port def prepareSubrun(self, subrunNum): "Start marking events...
return { "id" : self.__id, "compName" : self.name(), "compNum" : self.num(), "host" : self.__host, "rpcPort" : self.__port, "mbeanPort" : self.__mbeanPort }
identifier_body
DAQClient.py
#!/usr/bin/env python import os, socket, sys, threading from CnCLogger import CnCLogger from DAQRPC import RPCClient from RunSet import RunSet from UniqueID import UniqueID from exc_string import exc_string, set_exc_string_encoding set_exc_string_encoding("ascii") # Find install location via $PDAQ_HOME, otherwise u...
return attrs def getBeanNames(self): return self.__beanList def getBeanFields(self, bean): if bean not in self.__beanList: msg = "Bean %s not in list of beans for %s" % \ (bean, self.__compName) raise BeanFieldNotFoundException(msg) ret...
attrs[k] = self.__unFixValue(attrs[k])
conditional_block
DAQClient.py
#!/usr/bin/env python import os, socket, sys, threading from CnCLogger import CnCLogger from DAQRPC import RPCClient from RunSet import RunSet from UniqueID import UniqueID from exc_string import exc_string, set_exc_string_encoding set_exc_string_encoding("ascii") # Find install location via $PDAQ_HOME, otherwise u...
def getSingleBeanField(self, name, field): if self.__mbean is None: return None return self.__mbean.get(name, field) def host(self): return self.__host def id(self): return self.__id def isSource(self): "Is this component a source of data?" ...
else: csStr += ']' return csStr
random_line_split
DAQClient.py
#!/usr/bin/env python import os, socket, sys, threading from CnCLogger import CnCLogger from DAQRPC import RPCClient from RunSet import RunSet from UniqueID import UniqueID from exc_string import exc_string, set_exc_string_encoding set_exc_string_encoding("ascii") # Find install location via $PDAQ_HOME, otherwise u...
(self): "Reset component back to the idle state" self.__log.resetLog() return self.__client.xmlrpc.resetLogging() def setOrder(self, orderNum): self.__cmdOrder = orderNum def startRun(self, runNum): "Start component processing DAQ data" try: return s...
resetLogging
identifier_name
lib.rs
// Copyright 2020-2022 The NATS Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
( &self, subject: &str, maybe_headers: Option<&HeaderMap>, maybe_timeout: Option<Duration>, msg: impl AsRef<[u8]>, ) -> io::Result<Message> { // Publish a request. let reply = self.new_inbox(); let sub = self.subscribe(&reply)?; self.publish_wi...
request_with_headers_or_timeout
identifier_name
lib.rs
// Copyright 2020-2022 The NATS Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
unsafe_code, unused, unused_qualifications ) )] #![cfg_attr(feature = "fault_injection", deny( // over time, consider enabling the following commented-out lints: // clippy::else_if_without_else, // clippy::indexing_slicing, // clippy::multiple_crate_versions, // clippy::m...
missing_docs, nonstandard_style, rust_2018_idioms, trivial_casts, trivial_numeric_casts,
random_line_split
lib.rs
// Copyright 2020-2022 The NATS Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
/// Returns the maximum payload size the most recently /// connected server will accept. /// /// # Example /// ```no_run /// # fn main() -> std::io::Result<()> { /// let nc = nats::connect("demo.nats.io")?; /// println!("max payload: {:?}", nc.max_payload()); /// # Ok(()) /// #...
{ self.0.client.publish(subject, reply, headers, msg.as_ref()) }
identifier_body
prebuilt.go
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
(name string) string { return strings.TrimPrefix(name, "prebuilt_") } func NewPrebuiltLibrary(hod android.HostOrDeviceSupported) (*Module, *libraryDecorator) { module, library := NewLibrary(hod) module.compiler = nil prebuilt := &prebuiltLibraryLinker{ libraryDecorator: library, } module.linker = prebuilt mo...
implementationModuleName
identifier_name
prebuilt.go
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
p.libraryDecorator.flagExporter.reexportDeps(deps.ReexportedDeps...) p.libraryDecorator.flagExporter.addExportedGeneratedHeaders(deps.ReexportedGeneratedHeaders...) p.libraryDecorator.flagExporter.setProvider(ctx) // TODO(ccross): verify shared library dependencies srcs := p.prebuiltSrcs(ctx) if len(srcs) > 0 {...
p.libraryDecorator.flagExporter.exportIncludes(ctx) p.libraryDecorator.flagExporter.reexportDirs(deps.ReexportedDirs...) p.libraryDecorator.flagExporter.reexportSystemDirs(deps.ReexportedSystemDirs...) p.libraryDecorator.flagExporter.reexportFlags(deps.ReexportedFlags...)
random_line_split
prebuilt.go
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
func (p *prebuiltLibraryLinker) linkerDeps(ctx DepsContext, deps Deps) Deps { return p.libraryDecorator.linkerDeps(ctx, deps) } func (p *prebuiltLibraryLinker) linkerFlags(ctx ModuleContext, flags Flags) Flags { return flags } func (p *prebuiltLibraryLinker) linkerProps() []interface{} { return p.libraryDecorato...
{}
identifier_body
prebuilt.go
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
if p.header() { ctx.SetProvider(HeaderLibraryInfoProvider, HeaderLibraryInfo{}) return nil } return nil } func (p *prebuiltLibraryLinker) prebuiltSrcs(ctx android.BaseModuleContext) []string { sanitize := ctx.Module().(*Module).sanitize srcs := p.properties.Srcs srcs = append(srcs, srcsForSanitizer(sanit...
{ builderFlags := flagsToBuilderFlags(flags) if len(srcs) > 1 { ctx.PropertyErrorf("srcs", "multiple prebuilt source files") return nil } p.libraryDecorator.exportVersioningMacroIfNeeded(ctx) in := android.PathForModuleSrc(ctx, srcs[0]) if p.static() { depSet := android.NewDepSetBuilder(android...
conditional_block
handTrack1.py
import cv2 import numpy as np import pickle import random from matplotlib import pyplot as plot import pyautogui import math import time #from object_tracker import startX, startY, endY, endX hand_hist = None traverse_point = [] total_rectangle = 16 hand_rect_one_x = None hand_rect_one_y = None hand_rect_two_x = None...
def main(): global hand_hist, resetCount, handFound #global background #global have_background global cx global cy,bx,by global defHands, newHands is_hand_hist_created = False capture = cv2.VideoCapture(0) while capture.isOpened(): if resetCount <=0: bx = i...
global lengthColec data = np.random.normal(0, 21, 100) bins = np.arange(0, 21, 1) plot.xlim([min(data)-.5, max(data)+.5]) plot.hist(data, bins=bins, alpha=0.5) plot.title('metaData plot') plot.xlabel('side lengths)') plot.ylabel('Number of occurance') plot.show()
identifier_body
handTrack1.py
import cv2 import numpy as np import pickle import random from matplotlib import pyplot as plot import pyautogui import math import time #from object_tracker import startX, startY, endY, endX hand_hist = None traverse_point = [] total_rectangle = 16 hand_rect_one_x = None hand_rect_one_y = None hand_rect_two_x = None...
(defects, contour, centroid): global bx, by if defects is not None and centroid is not None: s = defects[:, 0][:, 0] #cx, cy = centroid centroid x = np.array(contour[s][:, 0][:, 0], dtype=np.float) y = np.array(contour[s][:, 0][:, 1], dtype=np.float) xp = cv2.po...
farthest_point
identifier_name
handTrack1.py
import cv2 import numpy as np import pickle import random from matplotlib import pyplot as plot import pyautogui import math import time #from object_tracker import startX, startY, endY, endX hand_hist = None traverse_point = [] total_rectangle = 16 hand_rect_one_x = None hand_rect_one_y = None hand_rect_two_x = None...
cv2.destroyAllWindows() capture.release() if __name__ == '__main__': main()
if resetCount <=0: bx = int(fWidth/2) by = int(fHeight/2) #print("Reset data: " + str(bx) + " " + str(resetCount) + " " + str(by)) pressed_key = cv2.waitKey(1) _, frame = capture.read() if is_hand_hist_created==False: txtColor = [0,255,0] ...
conditional_block
handTrack1.py
import cv2 import numpy as np import pickle import random from matplotlib import pyplot as plot import pyautogui import math import time #from object_tracker import startX, startY, endY, endX hand_hist = None traverse_point = [] total_rectangle = 16 hand_rect_one_x = None hand_rect_one_y = None hand_rect_two_x = None...
pyautogui.keyDown('ctrl') pyautogui.press('-') pyautogui.keyUp('ctrl') ''' def plotHand(): global lengthColec data = np.random.normal(0, 21, 100) bins = np.arange(0, 21, 1) plot.xlim([min(data)-.5, max(data)+.5]) plot.hist(data, bins=bins, alpha=0...
random_line_split
histogramMatching.py
import cv2,urllib,sys,math, sys import numpy as np import inspect from matplotlib import pyplot as plt #FUNCTIONS #executes first part of the program. i.e to find the difference between two frames def getDifferenceHulls(imgFrame1,imgFrame2): #making duplicates of the above frames imgFrame1Copy = imgFrame1.copy...
(point1,point2): intX = abs(point1[0] - point2[0]) intY = abs(point1[1] - point2[1]) return math.sqrt(math.pow(intX, 2) + math.pow(intY, 2)) #matching algorithm to corelate two blob objects by matching it with the expected one def matchCurrentFrameBlobsToExistingBlobs(existingBlobs,currentFrameBlobs): ...
distanceBetweenPoints
identifier_name
histogramMatching.py
import cv2,urllib,sys,math, sys import numpy as np import inspect from matplotlib import pyplot as plt #FUNCTIONS #executes first part of the program. i.e to find the difference between two frames def getDifferenceHulls(imgFrame1,imgFrame2): #making duplicates of the above frames imgFrame1Copy = imgFrame1.copy...
#find the distance between two points p1 and p2 def distanceBetweenPoints(point1,point2): intX = abs(point1[0] - point2[0]) intY = abs(point1[1] - point2[1]) return math.sqrt(math.pow(intX, 2) + math.pow(intY, 2)) #matching algorithm to corelate two blob objects by matching it with the expected one def...
image = np.zeros(imageSize, dtype=np.uint8) contours = [] for blob in blobs: if blob.blnStillBeingTracked == True: contours.append(blob.currentContour) cv2.drawContours(image, contours, -1,(255,255,255), -1); cv2.imshow(strWindowsName, image);
identifier_body
histogramMatching.py
import cv2,urllib,sys,math, sys import numpy as np import inspect from matplotlib import pyplot as plt #FUNCTIONS #executes first part of the program. i.e to find the difference between two frames
#changing the colorspace to grayscale imgFrame1Copy = cv2.cvtColor(imgFrame1Copy,cv2.COLOR_BGR2GRAY) imgFrame2Copy = cv2.cvtColor(imgFrame2Copy,cv2.COLOR_BGR2GRAY) #applying gaussianblur imgFrame1Copy = cv2.GaussianBlur(imgFrame1Copy,(5,5),0) imgFrame2Copy = cv2.GaussianBlur(imgFrame2Copy,(5,5...
def getDifferenceHulls(imgFrame1,imgFrame2): #making duplicates of the above frames imgFrame1Copy = imgFrame1.copy() imgFrame2Copy = imgFrame2.copy()
random_line_split
histogramMatching.py
import cv2,urllib,sys,math, sys import numpy as np import inspect from matplotlib import pyplot as plt #FUNCTIONS #executes first part of the program. i.e to find the difference between two frames def getDifferenceHulls(imgFrame1,imgFrame2): #making duplicates of the above frames imgFrame1Copy = imgFrame1.copy...
else: addNewBlob(currentFrameBlob, existingBlobs) for existingBlob in existingBlobs: if (existingBlob.blnCurrentMatchFoundOrNewBlob == False): existingBlob.intNumOfConsecutiveFramesWithoutAMatch +=1; if (existingBlob.intNumOfConsecutiveFramesWithoutAMatch >= 5): ...
addBlobToExistingBlobs(currentFrameBlob, existingBlobs, intIndexOfLeastDistance)
conditional_block
chat.js
var chat_croomid = 0; var chat_croomsign = 0; var chat_availability = 0; var chat_lastmsgtime = 0; var chat_lastlineid = 0; function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toU...
} } function chat_show() { $("chatbox").style.visibility = 'visible'; $("chatntf").style.right = '310px'; setCookie("cards_chatbox", "1", 365); chat_resize(); post_center(); } function chat_hide() { $("chatbox").style.visibility = 'hidden'; $("chatntf").style.right = '10px'; setCookie("c...
{ return unescape(y); }
conditional_block
chat.js
var chat_croomid = 0; var chat_croomsign = 0; var chat_availability = 0; var chat_lastmsgtime = 0; var chat_lastlineid = 0; function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toU...
function chat_isopen() { if(getCookie("cards_chatbox") == "1") return 1; else return 0; } function showhide_chat(item) { if($(item).style.visibility != 'visible') { $(item).style.visibility = 'visible'; $("chatntf").style.right = '310px'; setCookie("cards_chatbox", "1", 365); }else...
{ $("chatbox").style.visibility = 'hidden'; $("chatntf").style.right = '10px'; setCookie("cards_chatbox", "0", 365); chat_resize(); post_center(); }
identifier_body
chat.js
var chat_croomid = 0; var chat_croomsign = 0; var chat_availability = 0; var chat_lastmsgtime = 0; var chat_lastlineid = 0; function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toU...
(users, userav, newcount, rid, csignature, usersloc) { var o = $('chatntf'); /* offline available busy away */ var avm = ["555555", "99cc66", "ff6633", "ffcc00"]; var nbv = ""; var ulist = ""; var maxut = o.getAttribute('data-maxt'); var cct = o.getAttribute('data-ccount'); var ppt ...
chatc_create
identifier_name
chat.js
var chat_croomid = 0; var chat_croomsign = 0; var chat_availability = 0; var chat_lastmsgtime = 0; var chat_lastlineid = 0; function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toU...
chat_resize(); post_center(); } function chat_isopen() { if(getCookie("cards_chatbox") == "1") return 1; else return 0; } function showhide_chat(item) { if($(item).style.visibility != 'visible') { $(item).style.visibility = 'visible'; $("chatntf").style.right = '310px'; setCookie("...
setCookie("cards_chatbox", "0", 365);
random_line_split
canvas_play.js
'use strict' let ws, x, y, w, h, ID, stopRendering = false; class Time { constructor() { this.one = 1800; } updateTime(newTime) { clearInterval(this.interval); this.nw = newTime.slice(0, -1); setTimeout(() => this.interval = setInterval(() => this.upOne(), this.one * 1000), (Math.fl...
loadImage(`/img/players?r=${raw.skin}`, async a => { this.skin = await this.combineSkin(a); stopRendering = false; }); game.cats.set(raw.id, this); game.all.push(this); } delete() { const i = game.all.findIndex(a => a == this); if (i != -1) game.all.splice(i, 1); game.cats.delete(...
this.hsc = Math.floor(this.h * this.size); this.customTextSize = 0; this.dir = raw.dir; //присвоивать дефолтную картинку, а потом подгружать новую this.skin = new Image();
random_line_split
canvas_play.js
'use strict' let ws, x, y, w, h, ID, stopRendering = false; class Time { constructor() { this.one = 1800; } updateTime(newTime) { clearInterval(this.interval); this.nw = newTime.slice(0, -1); setTimeout(() => this.interval = setInterval(() => this.upOne(), this.one * 1000), (Math.fl...
k.alpha = 1.0 - i * i / 81; this.shiftAlphaMsg(link); } }, i * 100); } } addMsg(msg) { if (this.msg.length > 2) this.extMsg(this.msg[this.msg.length-1]); const m = {} //m.alpha = 1.0; m.text = game.serveText(msg); this.drawMsg(m, 1); if (this.msg[0]) this.drawMsg(...
nt.createElement('img'); m.image.src = tmp.canvas.toDataURL(); m.image.onload = () => stopRendering = false; } */ console.time('draw') const tmp = game.layer[3], k = 0.8 + 0.2 * this.size + this.customTextSize, interval = 12 * k, rectHeight = m.text.length * interva...
identifier_body
canvas_play.js
'use strict' let ws, x, y, w, h, ID, stopRendering = false; class Time { constructor() { this.one = 1800; } updateTime(newTime) { clearInterval(this.interval); this.nw = newTime.slice(0, -1); setTimeout(() => this.interval = setInterval(() => this.upOne(), this.one * 1000), (Math.fl...
[1]) ? full[0] : full[1]), stepX = full[0] / larger, stepY = full[1] / larger; for (let i = 0, x = msg.to[0] - stepX, y = msg.to[1] - stepY; i <= larger; i++, x -= stepX, y-= stepY) { if (game.computeVector([x, y], msg.to)[2] / 16 * 1000 > msg.t - Date.now()) return [x, y]; } } */ game.openConnection(...
.abs(full
identifier_name
s_expressions.rs
//! In this tutorial, we will write parser //! and evaluator of arithmetic S-expressions, //! which look like this: //! ``` //! (+ (* 15 2) 62) //! ``` /// Currently, rowan doesn't have a hook to add your own interner, /// but `SmolStr` should be a "good enough" type for representing /// tokens. /// Additionally, rowa...
{ Eof, RParen, Ok, } impl Parser { fn parse(mut self) -> Parse { // Make sure that the root node covers all source self.builder.start_node(ROOT.into()); // Parse a list of S-expressions loop { match self.sexp() { ...
SexpRes
identifier_name
s_expressions.rs
//! In this tutorial, we will write parser //! and evaluator of arithmetic S-expressions, //! which look like this: //! ``` //! (+ (* 15 2) 62) //! ``` /// Currently, rowan doesn't have a hook to add your own interner, /// but `SmolStr` should be a "good enough" type for representing /// tokens. /// Additionally, rowa...
(+ (* 15 2) 62) "; let root = parse(sexps); let res = root.syntax().sexps().map(|it| it.eval()).collect::<Vec<_>>(); eprintln!("{:?}", res); assert_eq!(res, vec![Some(92), Some(92), None, None, Some(92),]) } fn lex(text: &str) -> Vec<(SyntaxKind, SmolStr)> { fn tok(t: SyntaxKind) -> m_lexer::TokenK...
let sexps = " 92 (+ 62 30) (/ 92 0) nan
random_line_split
s_expressions.rs
//! In this tutorial, we will write parser //! and evaluator of arithmetic S-expressions, //! which look like this: //! ``` //! (+ (* 15 2) 62) //! ``` /// Currently, rowan doesn't have a hook to add your own interner, /// but `SmolStr` should be a "good enough" type for representing /// tokens. /// Additionally, rowa...
/// So far, we've been working with a homogeneous untyped tree. /// It's nice to provide generic tree operations, like traversals, /// but it's a bad fit for semantic analysis. /// This crate itself does not provide AST facilities directly, /// but it is possible to layer AST on top of `SyntaxNode` API. /// Let's wri...
{ let text = "(+ (* 15 2) 62)"; let node = parse(text); assert_eq!( format!("{:?}", node), "ROOT@[0; 15)", // root node, spanning 15 bytes ); assert_eq!(node.children().count(), 1); let list = node.children().next().unwrap(); let children = list.children().map(|child| format!...
identifier_body
s_expressions.rs
//! In this tutorial, we will write parser //! and evaluator of arithmetic S-expressions, //! which look like this: //! ``` //! (+ (* 15 2) 62) //! ``` /// Currently, rowan doesn't have a hook to add your own interner, /// but `SmolStr` should be a "good enough" type for representing /// tokens. /// Additionally, rowa...
} fn kind(&self) -> SexpKind { Atom::cast(self.0.clone()) .map(SexpKind::Atom) .or_else(|| List::cast(self.0.clone()).map(SexpKind::List)) .unwrap() } } // Let's enhance AST nodes with ancillary functions and // eval. impl Root { fn sexps(&self) -> impl Ite...
{ None }
conditional_block
play.js
import api from '../../api/api.js' let app=getApp() let backgroundAudioManager = wx.getBackgroundAudioManager() console.log(backgroundAudioManager.src); if (backgroundAudioManager.src) { } backgroundAudioManager.title = wx.getStorageSync("musicList")[0]?wx.getStorageSync("musicList")[0].title:"Sour Candy" backgroun...
newIndex=null console.log(musicList); console.log(nowIndex); console.log(type); console.log(playType); if (musicList.length<=1) { return } //随机播放(点上一曲或者下一曲哪个按钮都没联系,随机切) if (playType=='random_play') { //获取一个小于播放列表length的随机数并且不等于当前播放的index let getRandomNum=fu...
playType=this.data.playType,
random_line_split
play.js
import api from '../../api/api.js' let app=getApp() let backgroundAudioManager = wx.getBackgroundAudioManager() console.log(backgroundAudioManager.src); if (backgroundAudioManager.src) { } backgroundAudioManager.title = wx.getStorageSync("musicList")[0]?wx.getStorageSync("musicList")[0].title:"Sour Candy" backgroun...
=>{ return { ...v, hidden:v.hanlderName==playType?false:true } }), playType:playType }) //改变自然播放完毕后的逻辑 app.globalData.backgroundAudioManager.onEnded(()=>{ console.log('in'); let nowIndex=this.getNowPlayIndex(), musicList=this.data....
ata({ playTypeList:playTypeList.map(v
conditional_block
controller.go
// Copyright 2018 The Kubeflow Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agr...
return true } utilruntime.HandleError(fmt.Errorf("Error syncing job: %v", err)) c.workQueue.AddRateLimited(key) return true } // syncCaffe2Job will sync the job with the given. This function is not meant to be invoked // concurrently with the same key. // // When a job is completely processed it will return t...
{ c.workQueue.Forget(key) }
conditional_block
controller.go
// Copyright 2018 The Kubeflow Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agr...
{ var newConditions []api.Caffe2JobCondition for _, c := range conditions { if c.Type == condType { continue } newConditions = append(newConditions, c) } return newConditions }
identifier_body
controller.go
// Copyright 2018 The Kubeflow Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agr...
// caffe2JobLister can list/get caffe2jobs from the shared informer's store. caffe2JobLister listers.Caffe2JobLister // podLister can list/get pods from the shared informer's store. podLister corelisters.PodLister // serviceLister can list/get services from the shared informer's store. serviceLister corelisters.S...
// caffe2JobClientSet is a clientset for CRD Caffe2Job. caffe2JobClient jobclient.Interface
random_line_split
controller.go
// Copyright 2018 The Kubeflow Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agr...
() bool { key, quit := c.workQueue.Get() if quit { return false } defer c.workQueue.Done(key) forget, err := c.syncHandler(key.(string)) if err == nil { if forget { c.workQueue.Forget(key) } return true } utilruntime.HandleError(fmt.Errorf("Error syncing job: %v", err)) c.workQueue.AddRateLimited(...
processNextWorkItem
identifier_name
featureFileReader.js
/* * The MIT License (MIT) * * Copyright (c) 2014 Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to u...
(chr, start, end) { // insure that header has been loaded -- tabix _blockLoader is initialized as side effect if(!this.dataURI && !this.header) { await this.readHeader() } //console.log("Using index" const config = this.config const parser = this.parser ...
loadFeaturesWithIndex
identifier_name
featureFileReader.js
/* * The MIT License (MIT) * * Copyright (c) 2014 Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to u...
export default FeatureFileReader
} } }
random_line_split
featureFileReader.js
/* * The MIT License (MIT) * * Copyright (c) 2014 Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to u...
getParser(config) { switch (config.format) { case "vcf": return new VcfParser(config) case "seg" : return new SegParser("seg") case "mut": return new SegParser("mut") case "maf": return new Se...
{ if (this.dataURI) { await this.loadFeaturesFromDataURI(this.dataURI) return this.header } else { if (this.config.indexURL) { const index = await this.getIndex() if (!index) { // Note - it should be impossible to ...
identifier_body
featureFileReader.js
/* * The MIT License (MIT) * * Copyright (c) 2014 Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to u...
//console.log("Using index" const config = this.config const parser = this.parser const tabix = this.index.tabix const refId = tabix ? this.index.sequenceIndexMap[chr] : chr if (refId === undefined) { return [] } const genome = this.genome ...
{ await this.readHeader() }
conditional_block
client.go
package metrics import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "strconv" "strings" "sync" "time" ) // TODO Instrumentation? To get statistics? // TODO Authorization / Authentication ? // More detailed error type HawkularClientError struct { msg string Code int } func (se...
u := &url.URL{ Host: p.Host, Path: p.Path, Scheme: "http", Opaque: fmt.Sprintf("//%s/%s", p.Host, p.Path), } return &Client{ url: u, Tenant: p.Tenant, client: &http.Client{ Timeout: timeout, }, }, nil } // Public functions // Older functions.. // Return a single definition func (self ...
{ p.Path = base_url }
conditional_block
client.go
package metrics import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "strconv" "strings" "sync" "time" ) // TODO Instrumentation? To get statistics? // TODO Authorization / Authentication ? // More detailed error type HawkularClientError struct { msg string Code int } func (se...
md := []*MetricDefinition{} if b != nil { if err = json.Unmarshal(b, &md); err != nil { return nil, err } } return md, err } else if r.StatusCode > 399 { return nil, self.parseErrorResponse(r) } return nil, nil } // Update tags func (self *Client) UpdateTags(t MetricType, id string, tags map[st...
b, err := ioutil.ReadAll(r.Body) if err != nil { return nil, err }
random_line_split
client.go
package metrics import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "strconv" "strings" "sync" "time" ) // TODO Instrumentation? To get statistics? // TODO Authorization / Authentication ? // More detailed error type HawkularClientError struct { msg string Code int } func (se...
func TagsEndpoint(tags map[string]string) Endpoint { return func(u *url.URL) { addToUrl(u, tagsEncoder(tags)) } } func DataEndpoint() Endpoint { return func(u *url.URL) { addToUrl(u, "data") } } func (self *Client) metricsUrl(metricType MetricType) *url.URL { mu := *self.url addToUrl(&mu, metricType.Strin...
{ return func(u *url.URL) { addToUrl(u, "tags") } }
identifier_body
client.go
package metrics import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "strconv" "strings" "sync" "time" ) // TODO Instrumentation? To get statistics? // TODO Authorization / Authentication ? // More detailed error type HawkularClientError struct { msg string Code int } func (se...
(url *url.URL, method string, data interface{}) ([]byte, error) { jsonb, err := json.Marshal(&data) if err != nil { return nil, err } return self.send(url, method, jsonb) } func (self *Client) send(url *url.URL, method string, json []byte) ([]byte, error) { // Have to replicate http.NewRequest here to avoid cal...
process
identifier_name
ifd.rs
//! Function for reading TIFF tags use std::io::{self, Read, Seek}; use std::collections::{HashMap}; use super::stream::{ByteOrder, SmartReader, EndianReader}; use self::Value::{Unsigned, List}; macro_rules! tags { {$( $tag:ident $val:expr; )*} => { /// TIFF tag #[derive(Clo...
(type_: Type, count: u32, offset: [u8; 4] ) -> Entry { Entry { type_: type_, count: count, offset: offset, } } /// Returns a mem_reader for the offset/value field pub fn r(&self, byte_order: ByteOrder) -> SmartReader<io::Cursor<Vec<u8>>> { SmartRe...
new
identifier_name
ifd.rs
//! Function for reading TIFF tags use std::io::{self, Read, Seek}; use std::collections::{HashMap}; use super::stream::{ByteOrder, SmartReader, EndianReader}; use self::Value::{Unsigned, List}; macro_rules! tags { {$( $tag:ident $val:expr; )*} => { /// TIFF tag #[derive(Clo...
// tags!{ // // Baseline tags: // Artist 315; // TODO add support // // grayscale images PhotometricInterpretation 1 or 3 // BitsPerSample 258; // CellLength 265; // TODO add support // CellWidth 264; // TODO add support // // palette-color images (PhotometricInterpretation 3) // ColorMa...
// Note: These tags appear in the order they are mentioned in the TIFF reference // https://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
random_line_split
client.py
import os from googleapiclient.discovery import build import httplib2 from oauth2client import gce from oauth2client.appengine import AppAssertionCredentials from oauth2client.file import Storage __author__ = 'ekampf' import json import logging import apiclient.errors from apiclient import http as apiclient_request...
(self, use_jwt_credentials_auth=False, jwt_account_name='', jwt_key_func=None, oauth_credentails_file=None, trace=None): """ :param trace: A value to add to all outgoing requests :return: """ super(BigQueryClient, self).__init__() self.trace = trace self.use_jwt_c...
__init__
identifier_name
client.py
import os from googleapiclient.discovery import build import httplib2 from oauth2client import gce from oauth2client.appengine import AppAssertionCredentials from oauth2client.file import Storage __author__ = 'ekampf' import json import logging import apiclient.errors from apiclient import http as apiclient_request...
@staticmethod def is_in_gce_machine(): try: metadata_uri = 'http://metadata.google.internal' http = httplib2.Http() http.request(metadata_uri, method='GET') return True except httplib2.ServerNotFoundError: return False @property...
'SERVER_SOFTWARE' in os.environ and os.environ['SERVER_SOFTWARE'].startswith('Google App Engine/')
identifier_body
client.py
import os from googleapiclient.discovery import build import httplib2 from oauth2client import gce from oauth2client.appengine import AppAssertionCredentials from oauth2client.file import Storage __author__ = 'ekampf' import json import logging import apiclient.errors from apiclient import http as apiclient_request...
@staticmethod def factory(bigquery_model): """Returns a function that creates a BigQueryHttp with the given model.""" def _create_bigquery_http_request(*args, **kwargs): captured_model = bigquery_model return BigQueryHttp(captured_model, *args, **kwargs) return _...
random_line_split
client.py
import os from googleapiclient.discovery import build import httplib2 from oauth2client import gce from oauth2client.appengine import AppAssertionCredentials from oauth2client.file import Storage __author__ = 'ekampf' import json import logging import apiclient.errors from apiclient import http as apiclient_request...
elif self.oauth_credentails_file: # Local oauth token http = httplib2.Http() storage = Storage(self.oauth_credentails_file) credentials = storage.get() if not credentials: raise EnvironmentError('No credential file present') http = c...
from google.appengine.api import memcache scope = 'https://www.googleapis.com/auth/bigquery' credentials = AppAssertionCredentials(scope=scope) logging.info("Using Standard appengine authentication") return credentials.authorize(httplib2.Http(memcache))
conditional_block
command.rs
// Copyright 2014 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
} } } #[allow(missing_docs)] #[derive(Debug)] pub struct AccessGuardBuffers<'a, R: Resources> { buffers: AccessInfoBuffers<'a, R> } impl<'a, R: Resources> Iterator for AccessGuardBuffers<'a, R> { type Item = (&'a handle::RawBuffer<R>, &'a mut R::Mapping); fn next(&mut self) -> Option<Self::It...
for buffer in self.inner.mapped_reads().chain(self.inner.mapped_writes()) { unsafe { buffer.mapping().unwrap().release_access(); }
random_line_split
command.rs
// Copyright 2014 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
(&self) -> AccessInfoBuffers<R> { self.mapped_reads.iter() } /// Returns the mapped buffers that The GPU will write to pub fn mapped_writes(&self) -> AccessInfoBuffers<R> { self.mapped_writes.iter() } /// Is there any mapped buffer reads ? pub fn has_mapped_reads(&self) -> bool...
mapped_reads
identifier_name
command.rs
// Copyright 2014 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
} /// Register a buffer write access pub fn buffer_write(&mut self, buffer: &handle::RawBuffer<R>) { if buffer.is_mapped() { self.mapped_writes.insert(buffer.clone()); } } /// Returns the mapped buffers that The GPU will read from pub fn mapped_reads(&self) -> Acce...
{ self.mapped_reads.insert(buffer.clone()); }
conditional_block
command.rs
// Copyright 2014 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
} /// Informations about what is accessed by a bunch of commands. #[derive(Clone, Debug, Eq, PartialEq)] pub struct AccessInfo<R: Resources> { mapped_reads: HashSet<handle::RawBuffer<R>>, mapped_writes: HashSet<handle::RawBuffer<R>>, } impl<R: Resources> AccessInfo<R> { /// Creates empty access informati...
{ ClearColor::Uint([v, 0, 0, 0]) }
identifier_body
xcapture.go
package main import ( "flag" "fmt" "log" "os" "reflect" "strconv" "strings" "sync" "time" "unsafe" "honnef.co/go/xcapture/internal/shm" "github.com/BurntSushi/xgb" "github.com/BurntSushi/xgb/composite" "github.com/BurntSushi/xgb/damage" xshm "github.com/BurntSushi/xgb/shm" "github.com/BurntSushi/xgb/...
unc milliseconds(di int64) float64 { d := time.Duration(di) sec := d / time.Millisecond nsec := d % time.Millisecond return float64(sec) + float64(nsec)*1e-6 }
if m <= 0 { return d } r := d % m if r < 0 { r = -r if r+r < m { return d + r } if d1 := d - m + r; d1 < d { return d1 } return d // overflow } if r+r < m { return d - r } if d1 := d + m - r; d1 > d { return d1 } return d // overflow } f
identifier_body
xcapture.go
package main import ( "flag" "fmt" "log" "os" "reflect" "strconv" "strings" "sync" "time" "unsafe" "honnef.co/go/xcapture/internal/shm" "github.com/BurntSushi/xgb" "github.com/BurntSushi/xgb/composite" "github.com/BurntSushi/xgb/damage" xshm "github.com/BurntSushi/xgb/shm" "github.com/BurntSushi/xgb/...
() el := NewEventLoop(xu.Conn()) res := NewResizeMonitor(el, win) var other chan CaptureEvent captureEvents := make(chan CaptureEvent, 1) if *cfr { other = make(chan CaptureEvent) go func() { for { other <- CaptureEvent{} } }() } else { if err := damage.Init(xu.Conn()); err != nil { // XXX f...
{ if rhist.TotalCount()%int64(*fps) == 0 { chistMu.Lock() var cbracket hdrhistogram.Bracket var wbracket hdrhistogram.Bracket var rbracket hdrhistogram.Bracket brackets := chist.CumulativeDistribution() for _, bracket := range brackets { if bracket.ValueAt > int64(d) { break }...
conditional_block
xcapture.go
package main import ( "flag" "fmt" "log" "os" "reflect" "strconv" "strings" "sync" "time" "unsafe" "honnef.co/go/xcapture/internal/shm" "github.com/BurntSushi/xgb" "github.com/BurntSushi/xgb/composite" "github.com/BurntSushi/xgb/damage" xshm "github.com/BurntSushi/xgb/shm" "github.com/BurntSushi/xgb/...
size := b.PageSize return b.Data[offset : offset+size : offset+size] } type BitmapInfoHeader struct { Size uint32 Width int32 Height int32 Planes uint16 BitCount uint16 Compression [4]byte SizeImage uint32 XPelsPerMeter int32 YPelsPerMeter int32 ClrUsed uint3...
} func (b Buffer) Page(idx int) []byte { offset := b.PageOffset(idx)
random_line_split
xcapture.go
package main import ( "flag" "fmt" "log" "os" "reflect" "strconv" "strings" "sync" "time" "unsafe" "honnef.co/go/xcapture/internal/shm" "github.com/BurntSushi/xgb" "github.com/BurntSushi/xgb/composite" "github.com/BurntSushi/xgb/damage" xshm "github.com/BurntSushi/xgb/shm" "github.com/BurntSushi/xgb/...
(xs ...int) int { if len(xs) == 0 { return 0 } m := xs[0] for _, x := range xs[1:] { if x < m { m = x } } return m } // TODO(dh): this definition of a window is specific to Linux. On // Windows, for example, we wouldn't have an integer specifier for the // window. type Window struct { ID int mu ...
min
identifier_name
converter.rs
use spirv_cross::{ glsl, spirv, }; use shaderc; use std::{ iter, path::{Path, PathBuf}, fs::File, io::Read, collections::HashMap, }; use GlslVersion; use Stage; use ConvertedShader; use error::Error; #[derive(Debug, Clone)] pub struct ConverterOptions { /// Additional directories to ...
() -> Self { ConverterOptions { include_search_paths: Vec::new(), macros: HashMap::new(), target_version: GlslVersion::V1_00Es, } } } impl ConverterOptions { pub fn new() -> Self { Self::default() } fn resolve_include(&self, ...
default
identifier_name
converter.rs
use spirv_cross::{ glsl, spirv, }; use shaderc; use std::{ iter, path::{Path, PathBuf}, fs::File, io::Read, collections::HashMap, }; use GlslVersion; use Stage; use ConvertedShader; use error::Error; #[derive(Debug, Clone)] pub struct ConverterOptions { /// Additional directories to ...
fn hlsl_to_spirv(&mut self, source: &str, source_filename: &str, stage: Stage, entry_point: &str, options: &ConverterOptions) -> Result<Vec<u32>, Error> { let mut opts = shaderc::CompileOptions::new()....
{ let source_path = source_path.into(); let source_filename = source_path.to_string_lossy(); let mut source = String::new(); File::open(&source_path)?.read_to_string(&mut source)?; let spirv = self.hlsl_to_spirv(&source, source_filename.as...
identifier_body
converter.rs
use spirv_cross::{ glsl, spirv, }; use shaderc; use std::{ iter, path::{Path, PathBuf}, fs::File, io::Read, collections::HashMap, }; use GlslVersion; use Stage; use ConvertedShader; use error::Error; #[derive(Debug, Clone)] pub struct ConverterOptions { /// Additional directories to ...
})) .collect(); find_source_file(name, &search_paths_and_parent)? } _ => find_source_file(name, &self.include_search_paths)? }; let mut content = String::new(); File::open(&path) .and_then(|mut include...
let path = match (include_type, PathBuf::from(name).parent()) { (shaderc::IncludeType::Relative, Some(parent_path)) => { let mut search_paths_and_parent: Vec<_> = iter::once(parent_path) .chain(self.include_search_paths.iter().map(|path_buf_ref| { ...
random_line_split
controllers.js
angular.module('app.controllers', []) /* 00-settings */ .controller('SettingsCtrl', function( $scope, $rootScope, $state, Dropbox, Dialogs) { console.log('```` Rendering Settings'); $rootScope.isWelcomePage = false; $scope.confirmEvent = function() { localStorage['event_folder'] = $rootScope.sett...
animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0 }); $ionicSlideBoxDelegate.slide(0, 500); $timeout(function() { Dropbox.getImages(function() { $rootScope.gallery = $rootScope.gallery.chunk(6); $ionicSlideBoxDelegate.update(); // Upd...
$scope.refreshGallery = function() { console.log('refreshing gallery'); $ionicLoading.show({
random_line_split
main.rs
#![no_std] #![no_main] // pick a panicking behavior // extern crate panic_halt; // you can put a breakpoint on `rust_begin_unwind` to catch panics // extern crate panic_abort; // requires nightly // extern crate panic_itm; // logs messages over ITM; requires ITM support extern crate panic_semihosting; // logs messages...
loop { if can1.tx[0].tir.read().txrq().bit_is_clear() { break; } } loop { led.set_high().unwrap(); delay.delay_ms(1000_u32); led.set_low().unwrap(); delay.delay_ms(1000_u32); } } loop { ...
random_line_split
main.rs
#![no_std] #![no_main] // pick a panicking behavior // extern crate panic_halt; // you can put a breakpoint on `rust_begin_unwind` to catch panics // extern crate panic_abort; // requires nightly // extern crate panic_itm; // logs messages over ITM; requires ITM support extern crate panic_semihosting; // logs messages...
pub fn setup_can_gpio<X, Y>(rx: PD0<X>, tx: PD1<Y>) { // CAN1 RX - PG0, TX - PG1 // CAN1 RX - PA11, TX - PA12 // CAN1 RX - PD0, TX - PD1 --- // CAN1 RX - PB8, TX - PB9 // CAN2 RX - PB12, TX - PB13 // CAN2 RX - PG11, TX - PG12 // CAN2 RX - PB5, TX - PB6 // CAN3 RX - PA8, TX - PA15 /...
{ if let (Some(dp), Some(cp)) = ( stm32::Peripherals::take(), cortex_m::peripheral::Peripherals::take(), ) { let gpiob = dp.GPIOB.split(); let mut led = gpiob.pb7.into_push_pull_output(); let rcc = dp.RCC.constrain(); let clocks = rcc.cfgr.sysclk(100.mhz()).freez...
identifier_body
main.rs
#![no_std] #![no_main] // pick a panicking behavior // extern crate panic_halt; // you can put a breakpoint on `rust_begin_unwind` to catch panics // extern crate panic_abort; // requires nightly // extern crate panic_itm; // logs messages over ITM; requires ITM support extern crate panic_semihosting; // logs messages...
delay.delay_ms(1000_u32); write_string_to_serial(&mut tx, "Waiting for INAK to be cleared\n"); } write_string_to_serial(&mut tx, "INAK cleared\n"); // Set to standard identifier unsafe { can1.tx[0] .tir .modify(|_, w|...
{ break; }
conditional_block
main.rs
#![no_std] #![no_main] // pick a panicking behavior // extern crate panic_halt; // you can put a breakpoint on `rust_begin_unwind` to catch panics // extern crate panic_abort; // requires nightly // extern crate panic_itm; // logs messages over ITM; requires ITM support extern crate panic_semihosting; // logs messages...
<X, Y>( uart: USART3, tx: PD8<X>, rx: PD9<Y>, baudrate: Bps, clocks: Clocks, ) -> hal::serial::Tx<stm32f4::stm32f413::USART3> { let config = Config { baudrate, ..Config::default() }; let tx = tx.into_alternate_af7(); let rx = rx.into_alternate_af7(); let serial =...
configure
identifier_name
cfg.py
# cfg.py HOST = "irc.chat.twitch.tv" # the Twitch IRC server PORT = 6667 # always use port 6667 NICK = "lautrecbot" # your Twitch username, lowercase PASS = "REDACTED" # your Twitch OAuth token CHAN = "#REDACTED" # the channel you want to join RATE...
'ritual', 'contact', 'encounter', 'evolution', 'oath', 'corruption', 'execution', 'cleansing', 'prayer', 'defilement', 'sinister', 'courage', 'respect', 'inquisitiveness', 'pity', 'grief', 'wrath', 'sanity', 'madness', 'fervor', 'seduction', 'feasting', 'tastiness', 'tonsil', 'metamorphosis', '...
'nightmare', 'cosmos', 'oedon', 'communion', 'donation',
random_line_split
automaton.go
package automaton import ( "fmt" "github.com/bits-and-blooms/bitset" "github.com/geange/lucene-go/core/util" "sort" ) // Automaton Represents an automaton and all its states and transitions. States are integers and must be // created using createState. Mark a state as an accept state using setAccept. Add transiti...
func (r *Automaton) growTransitions() { if r.nextTransition+3 > len(r.transitions) { r.transitions = util.Grow(r.transitions, r.nextTransition+3) } } // Sorts transitions by dest, ascending, then min label ascending, then max label ascending type destMinMaxSorter struct { from, to int *Automaton } func (r *de...
{ if r.nextState+2 > len(r.states) { r.states = util.Grow(r.states, r.nextState+2) } }
identifier_body
automaton.go
package automaton import ( "fmt" "github.com/bits-and-blooms/bitset" "github.com/geange/lucene-go/core/util" "sort" ) // Automaton Represents an automaton and all its states and transitions. States are integers and must be // created using createState. Mark a state as an accept state using setAccept. Add transiti...
(source, dest, min, max int) error { //bounds := r.nextState / 2 r.growTransitions() if r.curState != source { if r.curState != -1 { r.finishCurrentState() } // Move to next source: r.curState = source if r.states[2*r.curState] != -1 { return fmt.Errorf("from state (%d) already had transitions adde...
AddTransition
identifier_name
automaton.go
package automaton import ( "fmt" "github.com/bits-and-blooms/bitset" "github.com/geange/lucene-go/core/util" "sort" ) // Automaton Represents an automaton and all its states and transitions. States are integers and must be // created using createState. Mark a state as an accept state using setAccept. Add transiti...
return false } func (r *destMinMaxSorter) Swap(i, j int) { iStart, jStart := 3*i, 3*j r.swapOne(iStart, jStart) r.swapOne(iStart+1, jStart+1) r.swapOne(iStart+2, jStart+2) } func (r *destMinMaxSorter) swapOne(i, j int) { r.transitions[i], r.transitions[j] = r.transitions[j], r.transitions[i] } // Sorts tra...
{ return false }
conditional_block
automaton.go
package automaton import ( "fmt" "github.com/bits-and-blooms/bitset" "github.com/geange/lucene-go/core/util" "sort" ) // Automaton Represents an automaton and all its states and transitions. States are integers and must be // created using createState. Mark a state as an accept state using setAccept. Add transiti...
func NewAutomatonV1(numStates, numTransitions int) *Automaton { return &Automaton{ curState: -1, deterministic: true, states: make([]int, numStates*2), isAccept: bitset.New(uint(numStates)), transitions: make([]int, numTransitions*3), } } // CreateState Create a new state. func (r *Automaton)...
random_line_split
main.rs
#![feature(array_windows)] #![feature(format_args_capture)] #![feature(total_cmp)] use clap::App; use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; use liblinear::util::TrainingInput; use liblinear::{Builder as LiblinearBuilder, LibLinearModel as _, SolverType}; use regex::Regex; use serde::{Deserialize, Seria...
let mut feature_map = FeatureMap { map: mem::take(&mut model.features), features: Vec::new() }; // Classify tests that are not yet classified using the model. let mut files = HashMap::default(); for dir in &[&root.join("issues"), root] { for entry in fs::read_dir(dir)? { let entry =...
let mut model: Model = serde_json::from_str(&model_str)?;
random_line_split
main.rs
#![feature(array_windows)] #![feature(format_args_capture)] #![feature(total_cmp)] use clap::App; use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; use liblinear::util::TrainingInput; use liblinear::{Builder as LiblinearBuilder, LibLinearModel as _, SolverType}; use regex::Regex; use serde::{Deserialize, Seria...
} impl ClassifiedTest { fn max_score(&self) -> f64 { self.class_scores[0].1 } } fn is_id_start(c: char) -> bool { // This is XID_Start OR '_' (which formally is not a XID_Start). // We also add fast-path for ascii idents ('a'..='z').contains(&c) || ('A'..='Z').contains(&c) ...
{ if let Some(index) = self.map.get(&*feature) { Some(*index) } else if read_only { None } else { let new_index = u32::try_from(self.features.len()).unwrap(); self.features.push(feature.clone().into_owned()); self.map.insert(feature.int...
identifier_body
main.rs
#![feature(array_windows)] #![feature(format_args_capture)] #![feature(total_cmp)] use clap::App; use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; use liblinear::util::TrainingInput; use liblinear::{Builder as LiblinearBuilder, LibLinearModel as _, SolverType}; use regex::Regex; use serde::{Deserialize, Seria...
lse if let prefix @ Some(_) = name.strip_suffix(".stderr") { prefix } else if let prefix @ Some(_) = name.strip_suffix(".stdout") { prefix } else if let prefix @ Some(_) = name.strip_suffix(".fixed") { prefix } else { None }; if let...
prefix } e
conditional_block
main.rs
#![feature(array_windows)] #![feature(format_args_capture)] #![feature(total_cmp)] use clap::App; use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; use liblinear::util::TrainingInput; use liblinear::{Builder as LiblinearBuilder, LibLinearModel as _, SolverType}; use regex::Regex; use serde::{Deserialize, Seria...
(s: &str) -> &str { const KEYWORDS: &[&str] = &[ "_", "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop"...
generalize
identifier_name
lib.rs
#![allow(dead_code)] extern crate libc; extern crate zmq_ffi; #[macro_use] extern crate cfg_if; mod socket; mod errno; pub use socket::*; pub use errno::*; use std::ops::{ Deref, DerefMut }; use std::ffi; use std::vec::Vec; use std::slice; use std::mem::transmute; use libc::{ c_int, c_void, size_t }; pub const ZMQ_...
() -> c_int { unsafe { zmq_ffi::zmq_errno() } } fn strerror(errnum: c_int) -> String { unsafe { let s = zmq_ffi::zmq_strerror(errnum); ffi::CStr::from_ptr(s).to_str().unwrap().to_string() } } /// Report 0MQ library version /// /// Binding of `void zmq_version (int *major, int *...
errno
identifier_name
lib.rs
#![allow(dead_code)] extern crate libc; extern crate zmq_ffi; #[macro_use] extern crate cfg_if; mod socket; mod errno; pub use socket::*; pub use errno::*; use std::ops::{ Deref, DerefMut }; use std::ffi; use std::vec::Vec; use std::slice; use std::mem::transmute; use libc::{ c_int, c_void, size_t }; pub const ZMQ_...
pub fn has_capability(capability: &str) -> bool { let capability_cstr = ffi::CString::new(capability).unwrap(); let rc = unsafe { zmq_ffi::zmq_has(capability_cstr.as_ptr()) }; rc == 1 } // Encryption functions /* Encode data with Z85 encoding. Returns encoded data */ //ZMQ_EXPORT ch...
/// Bindng of `int zmq_has (const char *capability);` /// /// The function shall report whether a specified capability is available in the library
random_line_split
lib.rs
#![allow(dead_code)] extern crate libc; extern crate zmq_ffi; #[macro_use] extern crate cfg_if; mod socket; mod errno; pub use socket::*; pub use errno::*; use std::ops::{ Deref, DerefMut }; use std::ffi; use std::vec::Vec; use std::slice; use std::mem::transmute; use libc::{ c_int, c_void, size_t }; pub const ZMQ_...
/// Move content of a message to another message. /// /// Binding of `int zmq_msg_move (zmq_msg_t *dest, zmq_msg_t *src);`. /// /// Move the content of the message object referenced by src to the message object referenced by dest. /// No actual copying of message content is performed, /// dest...
unsafe { let mut msg = try!(Message::with_capcity(data.len())); std::ptr::copy_nonoverlapping(data.as_ptr(), msg.as_mut_ptr(), data.len()); Ok(msg) } }
identifier_body
lib.rs
#![allow(dead_code)] extern crate libc; extern crate zmq_ffi; #[macro_use] extern crate cfg_if; mod socket; mod errno; pub use socket::*; pub use errno::*; use std::ops::{ Deref, DerefMut }; use std::ffi; use std::vec::Vec; use std::slice; use std::mem::transmute; use libc::{ c_int, c_void, size_t }; pub const ZMQ_...
e { unsafe { Some(ffi::CStr::from_ptr(returned_str_ptr).to_str().unwrap()) } } } } impl Deref for Message { type Target = [u8]; fn deref<'a>(&'a self) -> &'a [u8] { unsafe { let ptr = self.get_const_data_ptr(); let len = self.len() as usize; ...
None } els
conditional_block
ui.js
//-------------------------------------------------- // /* UI.js - Handles the drawing of the main UI */ //---------------------------------------------------// (function ($){ var Interface = function(getLayerContext, state){ //some constants this.LAYER_ID = game.UI; this.LEFT_CLICK = 1; this.layercontext...
switch(this.state){ case "starting": $(".ui").css({ "z-index": this.LAYER_ID+1 }); break; case "running": break; case "loading": //check if images finish loading before starting game var allLoaded = true; for(var i=0; i<game.system.entities.length; i++){ ...
} }; this.update = function(){
random_line_split
ui.js
//-------------------------------------------------- // /* UI.js - Handles the drawing of the main UI */ //---------------------------------------------------// (function ($){ var Interface = function(getLayerContext, state){ //some constants this.LAYER_ID = game.UI; this.LEFT_CLICK = 1; this.layercontext...
this.score.css("z-index", this.LAYER_ID+1); game.system.layermanager.clearLayer(this.LAYER_ID); game.system.state = this.state = "running"; break; default: break; } }; this.draw = function(){ switch(this.state){ case "starting": this.score.html("High Score:...
{ break; }
conditional_block
input.go
package termui import ( "github.com/nsf/termbox-go" "strconv" "strings" ) // default mappings between /sys/kbd events and multi-line inputs var multiLineCharMap = map[string]string{ "<space>": " ", "<tab>": "\t", "<enter>": "\n", "<escape>": "", } // default mappings between /sys/kbd events and single li...
func (i *Input) moveRight() { // if we are at the end of the line move to the next if i.cursorLinePos >= len(i.lines[i.cursorLineIndex]) { origLine := i.cursorLineIndex i.moveDown() if origLine < len(i.lines)-1 { i.cursorLinePos = 0 } return } i.cursorLinePos++ } // Buffer implements Bufferer inter...
{ // if we are at the beginning of the line move the cursor to the previous line if i.cursorLinePos == 0 { origLine := i.cursorLineIndex i.moveUp() if origLine > 0 { i.cursorLinePos = len(i.lines[i.cursorLineIndex]) } return } i.cursorLinePos-- }
identifier_body
input.go
package termui import ( "github.com/nsf/termbox-go" "strconv" "strings" ) // default mappings between /sys/kbd events and multi-line inputs var multiLineCharMap = map[string]string{ "<space>": " ", "<tab>": "\t", "<enter>": "\n", "<escape>": "", } // default mappings between /sys/kbd events and single li...
// append a newline in the current position with the content we computed in the previous if statement i.lines = append( i.lines[:i.cursorLineIndex+1], append( []string{newString}, i.lines[i.cursorLineIndex+1:]..., )..., ) } // increment the line index, reset the cursor to ...
{ newString = i.lines[i.cursorLineIndex][i.cursorLinePos:] i.lines[i.cursorLineIndex] = i.lines[i.cursorLineIndex][:i.cursorLinePos] }
conditional_block
input.go
package termui import ( "github.com/nsf/termbox-go" "strconv" "strings" ) // default mappings between /sys/kbd events and multi-line inputs var multiLineCharMap = map[string]string{ "<space>": " ", "<tab>": "\t", "<enter>": "\n", "<escape>": "", } // default mappings between /sys/kbd events and single li...
termbox.SetCursor(i.cursorLinePos+cursorXOffset, cursorYOffset) } /* if i.DebugMode { position := fmt.Sprintf("%s li: %d lp: %d n: %d", i.debugMessage, i.cursorLineIndex, i.cursorLinePos, len(i.lines)) for idx, char := range position { buf.Set(i.innerArea.Min.X+i.innerArea.Dx()-len(position) + idx, ...
cursorYOffset += i.cursorLineIndex } if i.IsCapturing { i.CursorX = i.cursorLinePos+cursorXOffset i.CursorY = cursorYOffset
random_line_split
input.go
package termui import ( "github.com/nsf/termbox-go" "strconv" "strings" ) // default mappings between /sys/kbd events and multi-line inputs var multiLineCharMap = map[string]string{ "<space>": " ", "<tab>": "\t", "<enter>": "\n", "<escape>": "", } // default mappings between /sys/kbd events and single li...
(text string) { i.lines = strings.Split(text, NEW_LINE) } // Lines returns the slice of strings with the content of the input field. By default lines are separated by \n func (i *Input) Lines() []string { return i.lines } // Private methods for the input field // TODO: handle delete key func (i *Input) backspace()...
SetText
identifier_name
blk_device.rs
//! //! This module implements the list_block_devices() gRPC method //! for listing available disk devices on the current host. //! //! The relevant information is obtained via udev. //! The method works by iterating through udev records and selecting block //! (ie. SUBSYSTEM=block) devices that represent either disks ...
( parent: Option<&str>, disk: &Device, mounts: &HashMap<OsString, MountInfo>, ) -> Result<Vec<BlockDevice>, Error> { let mut list: Vec<BlockDevice> = Vec::new(); let mut enumerator = Enumerator::new()?; enumerator.match_parent(disk)?; enumerator.match_property("DEVTYPE", "partition")?; ...
get_partitions
identifier_name
blk_device.rs
//! //! This module implements the list_block_devices() gRPC method //! for listing available disk devices on the current host. //! //! The relevant information is obtained via udev. //! The method works by iterating through udev records and selecting block //! (ie. SUBSYSTEM=block) devices that represent either disks ...
Some(Filesystem { fstype: fstype.unwrap_or_else(|| String::from("")), label: label.unwrap_or_else(|| String::from("")), uuid: uuid.unwrap_or_else(|| String::from("")), mountpoint: mountinfo .map(|m| String::from(m.dest.to_string_lossy())) .unwrap_or_else(|| ...
{ return None; }
conditional_block
blk_device.rs
//! //! This module implements the list_block_devices() gRPC method //! for listing available disk devices on the current host. //! //! The relevant information is obtained via udev. //! The method works by iterating through udev records and selecting block //! (ie. SUBSYSTEM=block) devices that represent either disks ...
// Iterate through udev to generate a list of all (block) devices // with DEVTYPE == "disk" fn get_disks( all: bool, mounts: &HashMap<OsString, MountInfo>, ) -> Result<Vec<BlockDevice>, Error> { let mut list: Vec<BlockDevice> = Vec::new(); let mut enumerator = Enumerator::new()?; enumerator.matc...
{ let mut table: HashMap<OsString, MountInfo> = HashMap::new(); for mount in (MountIter::new()?).flatten() { table.insert(OsString::from(mount.source.clone()), mount); } Ok(table) }
identifier_body
blk_device.rs
//! //! This module implements the list_block_devices() gRPC method //! for listing available disk devices on the current host. //! //! The relevant information is obtained via udev. //! The method works by iterating through udev records and selecting block //! (ie. SUBSYSTEM=block) devices that represent either disks ...
// Get the list of current filesystem mounts. fn get_mounts() -> Result<HashMap<OsString, MountInfo>, Error> { let mut table: HashMap<OsString, MountInfo> = HashMap::new(); for mount in (MountIter::new()?).flatten() { table.insert(OsString::from(mount.source.clone()), mount); } Ok(table) } /...
}); } None }
random_line_split
tpm.rs
// SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Keylime Authors #[macro_use] use log::*; use std::convert::{TryFrom, TryInto}; use std::io::prelude::*; use std::str::FromStr; use crate::{ common::config_get, quotes_handler::KeylimeIdQuote, Error as KeylimeError, QuoteData, Result, }; use actix_web:...
23 => PcrSlot::Slot23, bit => return Err(KeylimeError::Other(format!("malformed mask in integrity quote: only pcrs 0-23 can be included, but mask included pcr {:?}", bit))), }, ) } } Ok(pcrs) } // This encodes a quote string as input ...
20 => PcrSlot::Slot20, 21 => PcrSlot::Slot21, 22 => PcrSlot::Slot22,
random_line_split
tpm.rs
// SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Keylime Authors #[macro_use] use log::*; use std::convert::{TryFrom, TryInto}; use std::io::prelude::*; use std::str::FromStr; use crate::{ common::config_get, quotes_handler::KeylimeIdQuote, Error as KeylimeError, QuoteData, Result, }; use actix_web:...
// Reads a mask in the form of some hex value, ex. "0x408000", // translating bits that are set to pcrs to include in the list. // // The masks are sent from the tenant and cloud verifier to indicate // the PCRs to include in a Quote. The LSB in the mask corresponds to // PCR0. For example, keylime.conf specifies PCR...
{ let mut keydigest = DigestValues::new(); let keybytes = match pubkey.id() { Id::RSA => pubkey.rsa()?.public_key_to_pem()?, other_id => { return Err(KeylimeError::Other(format!( "Converting to digest value for key type {:?} is not yet implemented", other_id ...
identifier_body
tpm.rs
// SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Keylime Authors #[macro_use] use log::*; use std::convert::{TryFrom, TryInto}; use std::io::prelude::*; use std::str::FromStr; use crate::{ common::config_get, quotes_handler::KeylimeIdQuote, Error as KeylimeError, QuoteData, Result, }; use actix_web:...
() -> Self { TpmSigScheme::AlgNull } } // Returns TSS struct corresponding to a signature scheme. pub(crate) fn get_sig_scheme( scheme: TpmSigScheme, ) -> Result<TPMT_SIG_SCHEME> { match scheme { // The TPM2_ALG_NULL sig scheme can be filled out with placeholder data // in the detai...
default
identifier_name
size_cache_fs.go
package kafero import ( "encoding/json" "fmt" "github.com/wangjia184/sortedset" "io" "math" "os" "path/filepath" "sync" "syscall" "time" ) // The SizeCacheFS is a cache file system composed of a cache layer and a base layer // the cache layer has a maximal size, and files get evicted relative to their // la...
uf := NewSizeCacheFile(bfile, lfile, os.O_RDONLY, u, info) return uf, nil } func (u *SizeCacheFS) Mkdir(name string, perm os.FileMode) error { err := u.base.Mkdir(name, perm) if err != nil { return err } return u.cache.MkdirAll(name, perm) // yes, MkdirAll... we cannot assume it exists in the cache } func (...
{ return nil, err }
conditional_block
size_cache_fs.go
package kafero import ( "encoding/json" "fmt" "github.com/wangjia184/sortedset" "io" "math" "os" "path/filepath" "sync" "syscall" "time" ) // The SizeCacheFS is a cache file system composed of a cache layer and a base layer // the cache layer has a maximal size, and files get evicted relative to their // la...
func (u *SizeCacheFS) Open(name string) (File, error) { // Very important, remove from cache to prevent eviction while opening info := u.getCacheFile(name) if info != nil { u.removeFromCache(name) } st, fi, err := u.cacheStatus(name) if err != nil { return nil, err } switch st { case cacheLocal, cacheH...
{ // Very important, remove from cache to prevent eviction while opening info := u.getCacheFile(name) if info != nil { u.removeFromCache(name) } st, _, err := u.cacheStatus(name) if err != nil { return nil, err } switch st { case cacheLocal, cacheHit: default: exists, err := Exists(u.base, name) if...
identifier_body