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
DissertationScript.py
[0][1]) #name[1] is political affiliation because the txt file was organized in such a way except Exception as e: print("Problem with name in file: "+file) try: if file[0]=="H": a[name[0][0]].append(year[0] + " - House") if file...
date = datetime.datetime.strptime(date,"%Y-%m-%d") date = datetime.datetime.strftime(date, "%Y-%m-%d") return(date)
identifier_body
makesnapshots.py
6: Public release # version 2.0: Added daily, weekly and montly retention # version 3.0: Rewrote deleting functions, changed description # version 3.1: Fix a bug with the deletelist and added a pause in the volume loop # version 3.2: Tags of the volume are placed on the new snapshot # version 3.3: Merged IAM role addid...
(resource_id): resource_tags = {} if resource_id: tags = conn.get_all_tags({'resource-id': resource_id}) for tag in tags: # Tags starting with 'aws:' are reserved for internal use if not tag.name.startswith('aws:'): resource_tags[tag.name] = tag.value ...
get_resource_tags
identifier_name
makesnapshots.py
6: Public release # version 2.0: Added daily, weekly and montly retention # version 3.0: Rewrote deleting functions, changed description # version 3.1: Fix a bug with the deletelist and added a pause in the volume loop # version 3.2: Tags of the volume are placed on the new snapshot # version 3.3: Merged IAM role addid...
def set_resource_tags(resource, tags): for tag_key, tag_value in tags.items(): if tag_key not in resource.tags or resource.tags[tag_key] != tag_value: print('Tagging %(resource_id)s with [%(tag_key)s: %(tag_value)s]' % { 'resource_id': resource.id, 'tag_key': t...
resource_tags = {} if resource_id: tags = conn.get_all_tags({'resource-id': resource_id}) for tag in tags: # Tags starting with 'aws:' are reserved for internal use if not tag.name.startswith('aws:'): resource_tags[tag.name] = tag.value return resource_tag...
identifier_body
makesnapshots.py
6: Public release # version 2.0: Added daily, weekly and montly retention # version 3.0: Rewrote deleting functions, changed description # version 3.1: Fix a bug with the deletelist and added a pause in the volume loop # version 3.2: Tags of the volume are placed on the new snapshot # version 3.3: Merged IAM role addid...
try: count_total += 1 logging.info(vol) tags_volume = get_resource_tags(vol.id) description = '%(period)s_snapshot %(vol_id)s_%(period)s_%(date_suffix)s by snapshot script at %(date)s' % { 'period': period, 'vol_id': vol.id, 'date_suffix': date_suf...
for vol in vols: refresh_aws_credentials()
random_line_split
makesnapshots.py
6: Public release # version 2.0: Added daily, weekly and montly retention # version 3.0: Rewrote deleting functions, changed description # version 3.1: Fix a bug with the deletelist and added a pause in the volume loop # version 3.2: Tags of the volume are placed on the new snapshot # version 3.3: Merged IAM role addid...
time.sleep(10) current_snap.update(validate=True) print(' ' + current_snap.status) dest_conn = boto3.client( 'ec2', region_name=copy_region_name, aws_access_key_id=config['aws_ac...
break
conditional_block
parser.rs
it and /// get back produced [`Event`]s. #[derive(Clone)] pub(super) struct Parser { /// Number of bytes read from the source of data since the parser was created pub offset: usize, /// Defines how to process next byte pub state: ParseState, /// Expand empty element into an opening and closing elem...
<'b>(&mut self, bytes: &'b [u8]) -> Result<Event<'b>> { let mut content = bytes; if self.trim_text_end { // Skip the ending '<' let len = bytes .iter() .rposition(|&b| !is_whitespace(b)) .map_or_else(|| bytes.len(), |p| p + 1); ...
emit_text
identifier_name
parser.rs
it and /// get back produced [`Event`]s.
/// Defines how to process next byte pub state: ParseState, /// Expand empty element into an opening and closing element pub expand_empty_elements: bool, /// Trims leading whitespace in Text events, skip the element if text is empty pub trim_text_start: bool, /// Trims trailing whitespace in...
#[derive(Clone)] pub(super) struct Parser { /// Number of bytes read from the source of data since the parser was created pub offset: usize,
random_line_split
parser.rs
if [`Event::End`] nodes match last [`Event::Start`] node pub check_end_names: bool, /// Check if comments contains `--` (false per default) pub check_comments: bool, /// All currently Started elements which didn't have a matching /// End element yet. /// /// For an XML /// /// ```xm...
{ Decoder { #[cfg(feature = "encoding")] encoding: self.encoding.encoding(), } }
identifier_body
parser.rs
it and /// get back produced [`Event`]s. #[derive(Clone)] pub(super) struct Parser { /// Number of bytes read from the source of data since the parser was created pub offset: usize, /// Defines how to process next byte pub state: ParseState, /// Expand empty element into an opening and closing elem...
} Ok(Event::Decl(event)) } else { Ok(Event::PI(BytesText::wrap(&buf[1..len - 1], self.decoder()))) } } else { self.offset -= len; Err(Error::UnexpectedEof("XmlDecl".to_string())) } } /// Converts c...
{ self.encoding = EncodingRef::XmlDetected(encoding); }
conditional_block
api_consumer_mesh_suite.go
grpcServer *grpc.Server grpcListener net.Listener serviceToken string testService *namingpb.Service } //套件名字 func (t *ConsumerMeshTestingSuite) GetName() string { return "Consumer" } //SetUpSuite 启动测试套程序 func (t *ConsumerMeshTestingSuite) SetUpSuite(c *check.C) { grpcOptions := make([]grpc.ServerOption, 0) m...
Services: []*namingpb.MeshService{ { MeshName: &wrappers.StringValue{Value: meshname}, Service: &wrappers.StringValue{Value: "n"}, Namespace: &wrappers.StringValue{Value: "space"}, }, }, }) //request mreq := &api.GetMeshRequest{} //mreq.Namespace = "mesh" //mreq.Namespace = "" mreq.MeshId...
//Namespace: &wrappers.StringValue{Value: "mesh"}, Namespace: &wrappers.StringValue{Value: ""}, }, "", &namingpb.Mesh{ Id: &wrappers.StringValue{Value: meshname}, Owners: &wrappers.StringValue{Value: "bilinhe"},
random_line_split
api_consumer_mesh_suite.go
Server *grpc.Server grpcListener net.Listener serviceToken string testService *namingpb.Service } //套件名字 func (t *ConsumerMeshTestingSuite) GetName() string { return "Consumer" } //SetUpSuite 启动测试套程序 func (t *ConsumerMeshTestingSuite) SetUpSuite(c *check.C) { grpcOptions := make([]grpc.ServerOption, 0) maxSt...
gSuite) runWithMockTimeout(mockTimeout bool, handle func()) { t.mockServer.MakeOperationTimeout(mock.OperationDiscoverInstance, mockTimeout) t.mockServer.MakeOperationTimeout(mock.OperationDiscoverRouting, mockTimeout) defer func() { defer t.mockServer.MakeOperationTimeout(mock.OperationDiscover
辑 func (t *ConsumerMeshTestin
identifier_name
api_consumer_mesh_suite.go
Server *grpc.Server grpcListener net.Listener serviceToken string testService *namingpb.Service } //套件名字 func (t *ConsumerMeshTestingSuite) GetName() string { return "Consumer" } //SetUpSuite 启动测试套程序 func (t *ConsumerMeshTestingSuite) SetUpSuite(c *check.C) { grpcOptions := make([]grpc.ServerOption, 0) maxSt...
}, }) //request mreq := &api.GetMeshRequest{} //mreq.Namespace = "mesh" //mreq.Namespace = "" mreq.MeshId = meshname sdkContext, err := api.InitContextByFile("testdata/consumer.yaml") c.Assert(err, check.IsNil) consumer := api.NewConsumerAPIByContext(sdkContext) defer consumer.Destroy() time.Sleep(2 * tim...
).String() testService1 := &namingpb.Service{ Name: &wrappers.StringValue{Value: meshname}, Namespace: &wrappers.StringValue{Value: ""}, Token: &wrappers.StringValue{Value: serviceToken1}, } t.mockServer.RegisterService(testService1) //mesh t.mockServer.RegisterMesh(&namingpb.Service{ //Namespace:...
identifier_body
api_consumer_mesh_suite.go
grpcServer *grpc.Server grpcListener net.Listener serviceToken string testService *namingpb.Service } //套件名字 func (t *ConsumerMeshTestingSuite) GetName() string { return "Consumer" } //SetUpSuite 启动测试套程序 func (t *ConsumerMeshTestingSuite) SetUpSuite(c *check.C) { grpcOptions := make([]grpc.ServerOption, 0) m...
ervice) c.Assert(len(servicesRecived), check.Equals, 2) log.Printf("TestGetServices done", resp, len(servicesRecived)) time.Sleep(2 * time.Second) }) } //测试获取网格数据 func (t *ConsumerMeshTestingSuite) TestGetMesh(c *check.C) { log.Printf("Start TestGetMesh") meshname := "mesh001" //service serviceToken1 := uu...
icesRecived = resp.GetValue().([]*namingpb.S
conditional_block
context.rs
Def>> { self.ct_defs .get(&id) .filter(|cdef| cdef.is_populated()) .map(|cdef| &cdef.def) } pub fn defs(&self) -> impl Iterator<Item = (CtId, &Arc<CtDef>)> { self.ct_defs .iter() .filter(|(_, cdef)| cdef.is_populated()) .ma...
random_line_split
context.rs
ions: HashMap::new(), next_generation: Generation(0), } } pub fn def(&self, id: CtId) -> Option<&Arc<CtDef>> { self.ct_defs .get(&id) .filter(|cdef| cdef.is_populated()) .map(|cdef| &cdef.def) } pub fn defs(&self) -> impl Iterator<Item = ...
add_def
identifier_name
switching_jobmanager.py
import redis import simplejson import time import operator from cryptokit import bits_to_difficulty from gevent.event import Event from powerpool.lib import loop from powerpool.jobmanagers import Jobmanager from binascii import hexlify class MonitorNetworkMulti(Jobmanager): def __init__(self, config): se...
return False def update_profitability(self, currency): """ Recalculates the profitability for a specific currency """ jobmanager = self.jobmanagers[currency] last_job = jobmanager.latest_job pscore, ratio, _ = self.price_data[currency] # We can't update if we don't ...
job = self.jobmanagers[self.next_network].latest_job if job is None: self.logger.error( "Tried to switch network to {} that has no job!" .format(self.next_network)) return if self.current_network: self.logger...
conditional_block
switching_jobmanager.py
import redis import simplejson import time import operator from cryptokit import bits_to_difficulty from gevent.event import Event from powerpool.lib import loop from powerpool.jobmanagers import Jobmanager from binascii import hexlify class MonitorNetworkMulti(Jobmanager): def __init__(self, config): se...
(self): Jobmanager.start(self) self.config['jobmanagers'] = set(self.config['jobmanagers']) found_managers = set() for manager in self.manager.component_types['Jobmanager']: if manager.key in self.config['jobmanagers']: currency = manager.config['currency'] ...
start
identifier_name
switching_jobmanager.py
import redis import simplejson import time import operator from cryptokit import bits_to_difficulty from gevent.event import Event from powerpool.lib import loop from powerpool.jobmanagers import Jobmanager from binascii import hexlify class MonitorNetworkMulti(Jobmanager): def __init__(self, config): se...
"{} height {} is >= the configured maximum blockheight of {}, " "setting profitability to 0." .format(currency, last_job.block_height, max_blockheight)) return True block_value = last_job.total_value / 100000000.0 diff = bits_to_difficulty(hex...
self.profit_data[currency] = 0 self.logger.debug(
random_line_split
switching_jobmanager.py
import redis import simplejson import time import operator from cryptokit import bits_to_difficulty from gevent.event import Event from powerpool.lib import loop from powerpool.jobmanagers import Jobmanager from binascii import hexlify class MonitorNetworkMulti(Jobmanager): def __init__(self, config): se...
.format(currency)) self.check_best() def start(self): Jobmanager.start(self) self.config['jobmanagers'] = set(self.config['jobmanagers']) found_managers = set() for manager in self.manager.component_types['Jobmanager']: if mana...
if not hasattr('job', event): self.logger.info("No blocks mined yet, skipping switch logic") return currency = event.job.currency flush = event.job.type == 0 if currency == self.current_network: self.logger.info("Recieved new job on most profitable n...
identifier_body
kite.go
} //重连管理器 reconnManager := turbo.NewReconnectManager(true, 30*time.Second, 100, handshake) k.clientManager = turbo.NewClientManager(reconnManager) //构造pipeline的结构 pipeline := turbo.NewDefaultPipeline() ackHandler := NewAckHandler("ack", k.clientManager) accept := NewAcceptHandler("accept", k.listener) remot...
{ //只接收
identifier_name
kite.go
24, 10000, 10000, 10*time.Second, 50*10000) ctx, closed := context.WithCancel(parent) registryCenter := registry.NewRegistryCenter(ctx, registryUri) ga := turbo.NewGroupAuth(groupId, secretKey) ga.WarmingupSec = warmingupSec manager := &kite{ ga: ga, topicToAddress: &sync.Map{}, address...
f nil != err { //两秒后重试 time.Sleep(2 * time.Second) log.Warnf("kiteIO|handShake|FAIL|%s|%s", ga.GroupId, err) } else { authAck, ok := resp.(*protocol.ConnAuthAck) if !ok { return false, errors.New("Unmatches Handshake Ack Type! ") } else { if authAck.GetStatus() { log.Infof("kiteIO|handS...
} return conn, nil } //握手包 func handshake(ga *turbo.GroupAuth, remoteClient *turbo.TClient) (bool, error) { for i := 0; i < 3; i++ { p := protocol.MarshalConnMeta(ga.GroupId, ga.SecretKey, int32(ga.WarmingupSec)) rpacket := turbo.NewPacket(protocol.CMD_CONN_META, p) resp, err := remoteClient.WriteAndGet(*r...
identifier_body
kite.go
closed context.CancelFunc pools map[uint8]*turbo.GPool defaultPool *turbo.GPool //心跳时间 heartbeatPeriod time.Duration heartbeatTimeout time.Duration cliSelector Strategy } func newKite(parent context.Context, registryUri, groupId, secretKey string, warmingupSec int, listener IListener) *ki...
flowstat *stat.FlowStat ctx context.Context
random_line_split
kite.go
24, 10000, 10000, 10*time.Second, 50*10000) ctx, closed := context.WithCancel(parent) registryCenter := registry.NewRegistryCenter(ctx, registryUri) ga := turbo.NewGroupAuth(groupId, secretKey) ga.WarmingupSec = warmingupSec manager := &kite{ ga: ga, topicToAddress: &sync.Map{}, address...
s, err := k.registryCenter.GetQServerAndWatch(topic) if nil != err { log.Errorf("kite|GetQServerAndWatch|FAIL|%s|%s", err, topic) } else { log.Infof("kite|GetQServerAndWatch|SUCC|%s|%s", topic, hosts) } k.OnQServerChanged(topic, hosts) } length := 0 k.topicToAddress.Range(func(key, value interface{}) ...
(k.topics, b.Topic) } for _, topic := range k.topics { host
conditional_block
sms_fluxes.py
((diffangle - np.floor( diffangle )) * 360.0) - 180 return diffangle ################################################################################################# # Compute wind stress and direction def cart2pol(x, y): rho = np.sqrt(x**2 + y**2) phi = np.arctan2(y, x) return(rho, phi) def ca...
(f,vort
identifier_name
sms_fluxes.py
_, alpha, beta = gsw.rho_alpha_beta(SA,CT,y) return alpha,beta ################################################################################################# # Buoyancy and buoyancy gradient def calc_buoyancy(density,SA,CT,alpha,beta,mld,dx=1000,po=1027,g=9.8): """ Calculates buoyancy, buoyancy grad...
return by,by_S,by_T,bgrad,bxml ################################################################################################# # Glider Trajectory def calculate_initial_compass_bearing(pointA, pointB): """ Calculates the bearing between two points. The formulae used is the following: θ = ...
bxml[i]=(np.nanmean(bgrad[:np.int8(mld[i])-15,i],0))
conditional_block
sms_fluxes.py
# Alternative mld based on n2 def cal_mldn2(density,depth,n2,ref_depth=10,threshold=0.05): mld=np.ndarray(len(density[1,:])) for i in range(len(density[1,:])): try: drange = (depth[(np.abs((density[:,i]-density[ref_depth,i ]))>=threshold)].min()) mld[i]=depth[depth<=drange][n2...
for i in range(len(density[1,:])): try: mld[i]=(depth[(np.abs((density[:,i]-density[ref_depth,i ]))>=threshold)].min()) except ValueError: #raised if `y` is empty. mld[i]=(np.nan) return mld
random_line_split
sms_fluxes.py
buoyancy gradient def calc_buoyancy(density,SA,CT,alpha,beta,mld,dx=1000,po=1027,g=9.8): """ Calculates buoyancy, buoyancy gradient, mean buoyancy gradient in the mixed layer """ by = g * (1-density / po) # Buoyancy by_S = g * (1-beta*SA/po) by_T = g * (1-alpha*CT/po) #Raw buoyancy ...
Calculates Qmle based on Fox-Kemper 2008 Strong lateral gradients provide a resevoir of potential energy which can be released b ageostrophic overturning circulations as a result of ageostrophic baroclinic instabilities. The restratificatoin by ABI is slower than by Symmetric Instabilities but faster tha...
identifier_body
Fetch.ts
then throw error if (this._chainScope.setTo('catch')) { throw e; } else { // If no next catch exists, throw error to our safe scope this._chainScope.callError(e); } } }), this._chainScope); ...
{ return response; }
conditional_block
Fetch.ts
2, LOCKED = 423, FAILED_DEPENDENCY = 424, UNORDERED_COLLECTION = 425, UPGRADE_REQUIRED = 426, RETRY_WITH = 449, BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS = 450, UNAVAILABLE_FOR_LEGAL_REASON = 451, CLIENT_CLOSED_REQUEST = 499, INTERNAL_SERVER_ERROR = 500, NOT_IMPLEMENTED = 501, BAD...
HeadRequest
identifier_name
Fetch.ts
this._promise = promise; this._chainScope = chainScope; if (!this._chainScope) { this._chainScope = new PromiseChainScope(); } } public then<PromiseResult>(fnc: (value: T) => PromiseResult): PromiseWraper<PromiseResult> { // push to chain scope; this._chai...
return decodeURIComponent(atobFunction(str).split('').map(function(c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); } public static copyRequestDef(input: RequestDef, defaultHeaders?: {[key: string]: string}): RequestDef { let def: RequestDef =...
})); } public static b64DecodeUnicode(str) {
random_line_split
grasp_pos.py
rgb_stream.close() self.rgb_to_world_rmat = self.rgb_rmat.T self.rgb_to_world_tvec = -np.dot(self.rgb_rmat.T, self.rgb_tvec) self.ir_to_world_rmat = self.ir_rmat.T self.ir_to_world_tvec = -np.dot(self.ir_rmat.T, self.ir_tvec) def load_intrinsics(self): depth_stream = open("/home...
draw_rect
identifier_name
grasp_pos.py
1 cv2.namedWindow('RGB Image') cv2.setMouseCallback('RGB Image',self.draw_rect) def depth_callback(self,data): try: self.depth_image= self.br.imgmsg_to_cv2(data, desired_encoding="passthrough") except CvBridgeError as e: print(e) # print "depth" ...
depth_doc = yaml.load(depth_stream) self.depth_mtx = np.array(depth_doc['camera_matrix']['data']).reshape(3,3) self.depth_dist = np.array(depth_doc['distortion_coefficients']['data']) depth_stream.close() rgb_stream = open("/home/chentao/kinect_calibration/rgb_0000000000000000....
depth_stream = open("/home/chentao/kinect_calibration/depth_0000000000000000.yaml", "r")
identifier_body
grasp_pos.py
1 cv2.namedWindow('RGB Image') cv2.setMouseCallback('RGB Image',self.draw_rect) def depth_callback(self,data): try: self.depth_image= self.br.imgmsg_to_cv2(data, desired_encoding="passthrough") except CvBridgeError as e: print(e) # print "depth" ...
cv2.imshow("Segmentation",tempimg) cv2.waitKey(5) roi_points = [] for i,j in zip(interested_cluster_indices[0], interested_cluster_indices[1]): pix_point =np.zeros(2) pix_point[0] = j pix_point[1] = i point_...
# mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8') # interested_cluster_indices = np.where(mask2 == 1) # tempimg = self.rgb_image*mask2[:,:,np.newaxis]
random_line_split
grasp_pos.py
1 cv2.namedWindow('RGB Image') cv2.setMouseCallback('RGB Image',self.draw_rect) def depth_callback(self,data): try: self.depth_image= self.br.imgmsg_to_cv2(data, desired_encoding="passthrough") except CvBridgeError as e: print(e) # print "depth" ...
cv2.imshow('RGB Image', tempimg) cv2.waitKey(5) # print "rgb" def load_extrinsics(self): ir_stream = open("/home/chentao/kinect_calibration/ir_camera_pose.yaml", "r") ir_doc = yaml.load(ir_stream) self.ir_rmat = np.array(ir_doc['rmat']).reshape(3,3) se...
if (self.ix1 != -1 and self.iy1 != -1 and self.ix2 != -1 and self.iy2 != -1): cv2.rectangle(tempimg,(self.ix1,self.iy1),(self.ix2,self.iy2),(0,255,0),2) if self.rect_done: center_point = self.get_center_point() cv2.circle(tempimg, tuple(center_poin...
conditional_block
Draft.d.ts
(); * ``` * * **Querying drafts** * * ```javascript * // query a list of drafts in the inbox with the tag "blue" * let drafts = Draft.query("", "inbox", ["blue"]) * ``` */ declare class Draft { /** * Create new instance. */ constructor() /** * Unique identifier. */ readon...
readonly title: string /** * Generally, the first line of the draft, but cleaned up as it would be displayed in the draft list in the user interface, removing Markdown header characters, etc. */ readonly displayTitle: string /** * The lines of content separated into an array on `\n` line f...
*/
random_line_split
Draft.d.ts
* ``` * * **Querying drafts** * * ```javascript * // query a list of drafts in the inbox with the tag "blue" * let drafts = Draft.query("", "inbox", ["blue"]) * ``` */ declare class
{ /** * Create new instance. */ constructor() /** * Unique identifier. */ readonly uuid: string /** * The full text content. */ content: string /** * The first line. */ readonly title: string /** * Generally, the first line of the draft,...
Draft
identifier_name
client.go
Result, error) Close() } type Client struct { cfg *Config pool *Pool stopChan chan struct{} notifyPollingChan chan *PollItem polling *Polling closed int32 logDetail bool logInterval Duration working int32 waitChan chan struct{} } func...
else { return ret.hiveResult, nil } } } func (c *Client) SubmitAsync(statement string) (*ExecuteResult, error) { return c.ExecuteEx(statement, true) } func (c *Client) SubmitAsyncCtx(ctx context.Context, statement string) (*ExecuteResult, error) { return c.ExecuteAsyncCtx(ctx, statement) } func (c *Client) ...
{ return nil, ret.err }
conditional_block
client.go
Result, error) Close() } type Client struct { cfg *Config pool *Pool stopChan chan struct{} notifyPollingChan chan *PollItem polling *Polling closed int32 logDetail bool logInterval Duration working int32 waitChan chan struct{} } func...
ompareAndSwapInt32(&c.closed, 0, 1) { return } c.pool.Close() } //打印hive日志。注意本方法会一直执行直到hive结束(成功or失败),建议单起一个goroutine来执行本方法 func (c *Client) logResponseLog(handle *tcliservice.TOperationHandle) { start := time.Now()
mic.C
identifier_name
client.go
ExecuteResult, error) Close() } type Client struct { cfg *Config pool *Pool stopChan chan struct{} notifyPollingChan chan *PollItem polling *Polling closed int32 logDetail bool logInterval Duration working int32 waitChan chan struct{} ...
retChan := make(chan *result, 1) go func() { if ret, err := c.ExecuteEx(statement, false); err != nil { retChan <- &result{nil, err} } else { retChan <- &result{ret, nil} } }() select { case <-ctx.Done(): return nil, ctx.Err() case ret := <-retChan: if ret.err != nil { return nil, ret.err } ...
type result struct { hiveResult *ExecuteResult err error }
random_line_split
client.go
ExecuteResult, error) Close() } type Client struct { cfg *Config pool *Pool stopChan chan struct{} notifyPollingChan chan *PollItem polling *Polling closed int32 logDetail bool logInterval Duration working int32 waitChan chan struct{} ...
log.Debug("Execute HQL: ", statement) op, err := session.SubmitEx(statement, async) if err != nil { log.Errorf("ExecuteEx HQL error: %s, %s", statement, err.Error()) return nil, err } if c.logDetail { go c.logResponseLog(op.Handle) } //启动了hive日志打印开关 return newResult(c, op, statement), nil } func (c *...
{ // exceed the max of concurrent size c.checkConcurrentLimit() session, ok := c.pool.Require() if !ok { return nil, ErrClosing } defer c.pool.Release(session) //if err, _ := session.SubmitEx("SET hive.execution.engine=spark;", false); err != nil { //log.Error(err) //} //_, err := session.Submit("set spa...
identifier_body
grid-ref.ts
since some browsers will // // // blur the elements, for sub-pixel transforms. // // const offsetXPx = coerceCssPixelValue(Math.round(offset.x)); // // const offsetYPx = coerceCssPixelValue(Math.round(offset.y)); // // elementToOffset.style.transform = `translate3d(${offsetXPx}, ${offsetYPx}, ...
{ const grid = this._grid; const rowIndexes = toArray(this._grid.keys()); return reduce((acc, rowIndex) => { const rowItemPositions = grid.get(rowIndex) const { clientRect } = head(rowItemPositions); const { top, bottom } = clientRect; if (pointerY >= floor(top) && pointerY < floo...
identifier_body
grid-ref.ts
< top) rowOffset += grid.get(k).length; }) item = { ...item, rowOffset }; grid.set(top, [item]); } else { let row = grid.get(top); const rowOffset = last(row).rowOffset + 1; item = { ...item, rowOffset }; row = addItemToGrid(item, row); grid.s...
sibling.drag.getRootElement(); // Update the offset to reflect the new position. // console.log(offset, isDraggedItem); // sibling.gridOffset.x += offset.x; // sibling.gridOffset.y += offset.y; sibling.offset += offset; // Round the transforms since some browsers will ...
const offset = isDraggedItem ? itemOffset : siblingOffset; const elementToOffset = isDraggedItem ? item.getPlaceholderElement() :
random_line_split
grid-ref.ts
k < top) rowOffset += grid.get(k).length; }) item = { ...item, rowOffset }; grid.set(top, [item]); } else { let row = grid.get(top); const rowOffset = last(row).rowOffset + 1; item = { ...item, rowOffset }; row = addItemToGrid(item, row); grid....
(): void { const itemPositions = map(drag => { const elementToMeasure = drag.getVisibleElement(); return { drag, offset: 0, clientRect: getMutableClientRect(elementToMeasure) }; }, this._activeDraggables) this._itemPositions = flatten(groupWith(pathEq(['clientRect', 'top']), itemPositions)); ...
_cacheItemPositions
identifier_name
main.rs
// parse toml config files let mut specs: Vec<Spec> = vec![]; for filename in matches.opt_strs("f") { consume_specs_toml(&filename[..], &mut specs); } if specs.len() == 0 { let mut spec = Spec::new(); spec.start = Regex::new(r"\berror\b").ok(); specs.push(spec); }...
1 => { let path = path::Path::new(&matches.free[0]); match fs::File::open(&path) { Err(why) => { panic!("can't open {}: {}", matches.free[0], why.to_string()) }, Ok(ref mut f) => { read_lines(f) }, } } _ => { panic!("too many f...
{ read_lines(&mut io::stdin()) }
conditional_block
main.rs
// parse toml config files let mut specs: Vec<Spec> = vec![]; for filename in matches.opt_strs("f") { consume_specs_toml(&filename[..], &mut specs); } if specs.len() == 0 { let mut spec = Spec::new(); spec.start = Regex::new(r"\berror\b").ok(); specs.push(spec); }...
(spec: &Spec, line_index: usize, lines: &Vec<String>, sender: &mpsc::Sender<(isize, isize)>) { if let Some(ref rx) = spec.start { if rx.is_match(&lines[line_index][..]) { let sel_range = if spec.stop.is_some() || spec.whale.is_some() { try_select(&spec, lines, line_index as isize) } else { Some(...
process_spec
identifier_name
main.rs
// parse toml config files let mut specs: Vec<Spec> = vec![]; for filename in matches.opt_strs("f") { consume_specs_toml(&filename[..], &mut specs); } if specs.len() == 0 { let mut spec = Spec::new(); spec.start = Regex::new(r"\berror\b").ok(); specs.push(spec); }...
#[derive(Clone)] struct Spec { disable: bool, start: Option<Regex>, start_offset: isize, stop: Option<Regex>, stop_offset: isize, whale: Option<Regex>, backward: bool, limit: isize, } impl Spec { fn new() -> Self { Spec { disable: false, start: None, start_offset: 0, s...
{ let path = path::Path::new(filename); let mut file = match fs::File::open(&path) { Err(why) => { panic!("can't open {}: {}", filename, why.to_string()) } Ok(f) => f }; let mut content = String::new(); file.read_to_string(&mut content).unwrap(); let table = match content.parse...
identifier_body
main.rs
in a..b { selected_indexes.set(i as usize, true); } } } // output let mut prev_index = 0; for index in 0..work.lines.len() { if selected_indexes[index] { if prev_index > 0 { if index + 1 - prev_index > 1 { writ...
} else { failed_files.push(toml_path_s); println!("fail\n\t{} spec(s) recognized\n--- expected ---\n{}\n--- actual ---", specs.len(), &expected_content[..]); println!("{}", std::str::from_utf8(&output).unwrap()); println!("--- end ---");
random_line_split
plugin.py
else: tempResult = result[count] tempResult[key] = parseResult({key: ".".join(splitted[:i])}, tempEntry, False) count += 1 else: if(index.isdigit()): temp = temp[int(index)] else: temp = temp[index] return result def executeJso...
elif("poster" in listItemDescriptor): art['poster'] = listItemDescriptor['poster'] result.append(createListItem(listItemDescriptors['label'], listItemDescriptors['path'], listItemDescriptors['thumb'], listItemDescriptors['label'])) return result def doGet(url, headers): req = Request(url, headers=hea...
art['icon'] = listItemDescriptor['icon']
conditional_block
plugin.py
(True) xbmcplugin.setResolvedUrl(handle=handle, succeeded=True, listitem=xbmcgui.ListItem()) return def getDirectorFolder(director): command = '{"jsonrpc": "2.0","method": "Files.GetDirectory","params": {"directory": "videodb://movies/directors/"}, "id": 1}' jsonResult = executeJson(command)['files'] for e...
mediaInfo = getRunningmediaInfoInfo() listItems = getRelatedItems(mediaInfo) if(listItems): passToSkin(listItems)
identifier_body
plugin.py
else: tempResult = result[count] tempResult[key] = parseResult({key: ".".join(splitted[:i])}, tempEntry, False) count += 1 else: if(index.isdigit()): temp = temp[int(index)] else: temp = temp[index] return result def executeJso...
xbmc.log("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv") xbmc.log(url) xbmc.log(str(headers)) rResult = doGet(url, headers) xbmc.log(str(rResult)) result.append(parseResult(resultMapping, rResult, False)) return providerResult xbmc.log("loop end...
if 'headers' in provider: for headerName, headerValue in provider['headers'].items(): headers[headerName] = eval(headerValue)
random_line_split
plugin.py
: tempResult = result[count] tempResult[key] = parseResult({key: ".".join(splitted[:i])}, tempEntry, False) count += 1 else: if(index.isdigit()): temp = temp[int(index)] else: temp = temp[index] return result def executeJson(com...
(url, headers): req = Request(url, headers=headers) response = urlopen(req) result = response.read() xbmc.log(result) return json.loads(result) def findProviderForPlugin(mediaInfo): path = mediaInfo['pluginpath'] providerResult = {} providerResult['type'] = None providerResult['path'] = [] global pr...
doGet
identifier_name
storage.go
.Type.StorageType() targetStorageType := target.Type.StorageType() if sourceStorageType != targetStorageType { return errors.Newf( "source vdisk %s and target vdisk %s have different storageTypes (%s != %s)", source.VdiskID, target.VdiskID, sourceStorageType, targetStorageType) } var err error switch sour...
{ return nil, err }
conditional_block
storage.go
dereferenced. // See https://github.com/zero-os/0-Disk/issues/147 func DeleteVdiskInCluster(vdiskID string, t config.VdiskType, cluster ardb.StorageCluster) (bool, error) { var err error var deletedTlogMetadata bool if t.TlogSupport() { command := ardb.Command(command.Delete, tlogMetadataKey(vdiskID)) deletedTl...
{ p := len(s) - 1 if p <= 0 { return s } for i := p - 1; i >= 0; i-- { if s[p] != s[i] { p-- s[p] = s[i] } } return s[p:] }
identifier_body
storage.go
storage return NewBlockStorage(cfg, cluster, templateCluster) } // NewBlockStorage returns the correct block storage based on the given VdiskConfig. func NewBlockStorage(cfg BlockStorageConfig, cluster, templateCluster ardb.StorageCluster) (storage BlockStorage, err error) { err = cfg.Validate() if err != nil { ...
(vdiskID string, t config.VdiskType, cluster ardb.StorageCluster) (bool, error) { switch st := t.StorageType(); st { case config.StorageDeduped: return dedupedVdiskExists(vdiskID, cluster) case config.StorageNonDeduped: return nonDedupedVdiskExists(vdiskID, cluster) case config.StorageSemiDeduped: return se...
VdiskExistsInCluster
identifier_name
storage.go
storage return NewBlockStorage(cfg, cluster, templateCluster) } // NewBlockStorage returns the correct block storage based on the given VdiskConfig. func NewBlockStorage(cfg BlockStorageConfig, cluster, templateCluster ardb.StorageCluster) (storage BlockStorage, err error) { err = cfg.Validate() if err != nil { ...
func VdiskExistsInCluster(vdiskID string, t config.VdiskType, cluster ardb.StorageCluster) (bool, error) { switch st := t.StorageType(); st { case config.StorageDeduped: return dedupedVdiskExists(vdiskID, cluster) case config.StorageNonDeduped: return nonDedupedVdiskExists(vdiskID, cluster) case config.Storag...
random_line_split
FinalProject.py
.finalBill.items(): sum += details[1] * details[0] print(product + " ,quantity: " + str(details[1]) + " ,price: " + str(details[1] * details[0]) + "$") print("Total cost: " + str(sum)+"$") class Movie: def __init__(self, code, movieName, category, ScreeningDate, price): self.code = ...
newMenu.destroy() newMenu = Tk() newMenu.title("Nitzan & Eliran") bg = PhotoImage(file=r'''C:\Users\Nitzan Gabay\OneDrive - Ruppin Academic Center\Desktop\שנה ב'\סמסטר ב\פייטון\מבחן מסכם בפייטון\Cinema1.png''') bg_lable = Label(newMenu, image= bg) bg_lable.place(x=0, y=0, relwidth=1...
e Bye..")
identifier_name
FinalProject.py
self.finalBill[product] = (productPrice, productAmount) def ShowFinalBill(self): sum = 0 for product, details in self.finalBill.items(): sum += details[1] * details[0] print(product + " ,quantity: " + str(details[1]) + " ,price: " + str(details[1] * details[0]) + "$") p...
if product in i: self.finalBill[product] = (productPrice, self.finalBill[product][1] + productAmount) return
conditional_block
FinalProject.py
Bill.items(): sum += details[1] * details[0] print(product + " ,quantity: " + str(details[1]) + " ,price: " + str(details[1] * details[0]) + "$") print("Total cost: " + str(sum)+"$") class Movie: def __init__(self, code, movieName, category, ScreeningDate, price): self.code = code ...
j +=1 def menu(): def ExcNoneQuery(sql_command, values): server= 'LAPTOP-K8MAK0VU\SQLEXPRESS' database = 'Movies' cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server}; \ SERVER=' + server +'; \ DAT...
def __init__(self): self.avilableMovies = [Movie(536, "Fast & Furious", "Action", "24/06/2021", 30), Movie(245, "Lion King", "Disney", "24/06/2021",20), Movie(875, "Aladdin", "Disney", "25/07/2021", 20), Movie(444, "Taken", "Action", "30/06/2021", 30), Movie(333, "Neighb...
identifier_body
FinalProject.py
Bill.items(): sum += details[1] * details[0] print(product + " ,quantity: " + str(details[1]) + " ,price: " + str(details[1] * details[0]) + "$") print("Total cost: " + str(sum)+"$") class Movie: def __init__(self, code, movieName, category, ScreeningDate, price): self.code = code ...
def printMovies(self): print("Avilable movies in our Cinema:") j = 1 for i in self.avilableMovies : print(str(j) + ". Name: " + i.movieName + ", Category: " + i.category + ", Date: " + i.ScreeningDate + " , Price: " + str(i.price) + "$") j +=1 def menu(): ...
Movie(617, "The Little Mermaid", "Disney", "03/07/2021", 20), Movie(321, "The Hangover", "Comedy", "05/07/2021", 25), Movie(893, "American Pie", "Comedy", "10/07/2021", 25), Movie(445, "Mulan", "Disney", "07/07/2021", 20)]
random_line_split
micro_mlperftiny.py
to import a TFLite model from MLPerfTiny benchmark models, compile it with TVM and generate a Zephyr project which can be flashed to a Zephyr supported board to benchmark the model using EEMBC runner. """ ###################################################################### # # .. include:: ../../../../gallery/h...
project_options["cmsis_path"] = os.environ.get("CMSIS_PATH", "/content/cmsis")
conditional_block
micro_mlperftiny.py
download_testdata from tvm.micro import export_model_library_format import tvm.micro.testing from tvm.micro.testing.utils import ( create_header_file, mlf_extract_workspace_size_bytes, ) ###################################################################### # Import Visual Wake Word Model # ------------------...
# cmake .. # make -j2
random_line_split
client.go
for _, value := range strings.Split(strings.TrimSpace(received_data), common.MESSAGE_DELIMITER) { // // fmt.Println("parse received:", value) // // if len(value) > 0 && isValidString(value) { // // // Check if the end of the message is "end." Otherwise this is a partial message and you must wait for the r...
(num_t int, ch chan Latencies, exit chan FinalResult) { total := 0.0 num_successes := 0 earliest := 0 latest := 0 var nums[1000000] float64 var newval Latencies for i := 0; i < num_t; i++ { newval = <- ch // fmt.Println(i) if newval.time > 0 { total += newval.time num_successes++ val, _ := str...
summation
identifier_name
client.go
_, value := range strings.Split(strings.TrimSpace(received_data), common.MESSAGE_DELIMITER) { // // fmt.Println("parse received:", value) // // if len(value) > 0 && isValidString(value) { // // // Check if the end of the message is "end." Otherwise this is a partial message and you must wait for the rest ...
// Calculate standard deviation var sd float64 mean := total / float64(num_successes) for j := 0; j < num_t; j++ { if nums[j] > 0 { sd += math.Pow( nums[j] - mean, 2 ) } } sd = math.Sqrt(sd / float64(num_successes)) fmt.Println("Mean:", mean) fmt.Println("StdDev:", sd) exit <- FinalResult { total_lat...
{ newval = <- ch // fmt.Println(i) if newval.time > 0 { total += newval.time num_successes++ val, _ := strconv.Atoi(newval.start) if earliest == 0 || val < earliest { earliest = val } val, _ = strconv.Atoi(newval.end) if val > latest { latest = val } } nums[i] = newval.time...
conditional_block
client.go
for _, value := range strings.Split(strings.TrimSpace(received_data), common.MESSAGE_DELIMITER) { // // fmt.Println("parse received:", value) // // if len(value) > 0 && isValidString(value) { // // // Check if the end of the message is "end." Otherwise this is a partial message and you must wait for the r...
latest = val } } nums[i] = newval.time } // Calculate standard deviation var sd float64 mean := total / float64(num_successes) for j := 0; j < num_t; j++ { if nums[j] > 0 { sd += math.Pow( nums[j] - mean, 2 ) } } sd = math.Sqrt(sd / float64(num_successes)) fmt.Println("Mean:", mean) fmt.Print...
{ total := 0.0 num_successes := 0 earliest := 0 latest := 0 var nums[1000000] float64 var newval Latencies for i := 0; i < num_t; i++ { newval = <- ch // fmt.Println(i) if newval.time > 0 { total += newval.time num_successes++ val, _ := strconv.Atoi(newval.start) if earliest == 0 || val < e...
identifier_body
client.go
for _, value := range strings.Split(strings.TrimSpace(received_data), common.MESSAGE_DELIMITER) { // // fmt.Println("parse received:", value) // // if len(value) > 0 && isValidString(value) { // // // Check if the end of the message is "end." Otherwise this is a partial message and you must wait for the r...
client_request := common.MESSAGE_DELIMITER + "CLIENT_REQUEST|" + client_id + "!" + i_str + "!10" // start := time.Now() // fmt.Println("Starting :" + client_id + "!" + i_str + "!10") // start := time.Now()) if txn_type == "l" { client_request += "!l|" + common.MESSAGE_ENDER + common.MESSAGE_DELIMITER ...
random_line_split
shopee.js
) { if (accountType === 'subaccount') { // 子账号登录需要SPC_CDS,要不可能出错 jar.setCookieSync(cookie2str({ name: 'SPC_CDS', value: SPC_CDS, domain: host, path: '/' }, host), `https://${host}/`) } // 植入cookie, 保证本土店铺使用原有的 cookies.forEac...
reject(new Error(`sigget: ${res.code}, ${res.message}`)) } }, reject) } else { resolve() } }) } return new Promise((resolve, reject) => { getFingerprint().then(fingerprint => { let captcha_key = createCaptcheKey() // 密码先md5...
} else { reject(new Error('sig获取失败')) } } else {
conditional_block
shopee.js
= (username || '').trim() const accountType = getLoginType(username) const sellerCenterFeSessionHash = uuidv4() const SPC_CDS = uuidv4() const headers = { 'origin': `https://${host}`, 'referer': `https://${host}/account/signin`, 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10...
ername
identifier_name
shopee.js
const subaccountCookies = [] const http = axios.create({ timeout: 50e3, withCredentials: true, // WARNING: This value will be ignored. jar, headers }) // Set directly after wrapping instance. axiosCookieJarSupport(http) http.defaults.jar = jar if (agent) { ...
) const sellerCenterFeSessionHash = uuidv4() const SPC_CDS = uuidv4() const headers = { 'origin': `https://${host}`, 'referer': `https://${host}/account/signin`, 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safar...
identifier_body
shopee.js
shop.userId = user.subaccount_id || user.main_account_id } console.log('login.okkk', user) loginSig(shop.shopId).then(() => { http.post(`https://${host}/webchat/api/v1.2/login`).then(({ data: res }) => { console.log(res) shop.uid = res.us...
"user": { "username": "mangoali.my", "rating": 0, "uid": "0-16248284",
random_line_split
slice_test.rs
sth = [1,2,3,4,5]; let mut_slice = &mut sth[0..3]; mut_slice.swap(0, 2); print_slice(&mut_slice); } pub fn reverse() { println!("reverse"); let mut array = [1,2,3,4,5,6,7,8]; move_in_array(array); drop(array); let slice = &mut array[0..]; slice.reverse(); print_slice(&slice); }...
// without errors. Here, the Rust borrow checker allows i1 and i2 // to simultaneously exists. Hence, it is important for the API designer // to ensure that i1 and i2 do not refer to the same content in the original // slice println!("{}", i1); println!("{}", i2); // if i borrow from the g...
{ let mut array = [2,3,4,5,6,7]; let slice = &mut array[..]; let mut iter_mut = slice.iter_mut(); // i1 does not borrow from iter_mut, it is treated as a // a borrow of slice, and extends the lifetime of slice let i1 = iter_mut.next().unwrap(); // i2 is similar as i1 let i2 = ...
identifier_body
slice_test.rs
,7]; let slice = & array[..]; for i in slice { println!("{}", i); } println!("6"); let mut array = [2,3,4,5,6,7]; let slice = &mut array[..]; for i in slice { *i = *i + 1; println!("{}", i); } println!("7"); let array = [2,3,4,5,6,7]; let slice = &ar...
{ println!("please insert 109 at index {}", i); vec.insert(i, 109); }
conditional_block
slice_test.rs
(); while let Some(wtf) = iter.next(){ println!("{}", wtf); } println!("2"); let mut array = [2,3,4,5,6,7]; let mut iter = array.iter_mut(); while let Some(wtf) = iter.next() { *wtf = *wtf + 1; println!("{}", wtf); } println!("3"); let array = [2,3,4,5,6,7];...
sort_and_search
identifier_name
slice_test.rs
} pub fn slice_size_len() { println!("{}", mem::size_of::<&[i32]>()); // println!("{}", mem::size_of::<[i32]>()); let sth = [1,2,3]; let slice = &sth[0..3]; println!("slice.len"); println!("{}",slice.len()); assert!(slice.first() == Some(&1)); } pub fn slice_split_first() { let slice ...
*i = *i + 1; println!("{} ", i); }
random_line_split
tree_search.py
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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either...
# That's it. This program state is now updated. return self.objective(self.arr.cluster_state.resources) def simulate_action(self, action): tnode_id, kwargs = action entry = self.tnode_map[tnode_id] node: TreeNode = entry[0] new_resources: np.ndarray = node.simulate_...
tnode_id, kwargs = action entry = self.tnode_map[tnode_id] old_node: TreeNode = entry[0] new_node: TreeNode = old_node.execute_on(**kwargs) # The frontier needs to be updated, so remove the current node from frontier. del self.tnode_map[tnode_id] if old_node.parent is Non...
identifier_body
tree_search.py
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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ex...
(self): for grid_entry in self.arr.grid.get_entry_iterator(): self.add_frontier_tree(self.arr.graphs[grid_entry]) def add_frontier_tree(self, start_node: TreeNode): for tnode in start_node.get_frontier(): self.add_frontier_node(tnode) def get_bc_action(self, tnode: Tree...
init_frontier
identifier_name
tree_search.py
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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ex...
if actions is None: actions = tnode.get_actions(**self.get_action_kwargs) self.tnode_map[tnode.tree_node_id] = (tnode, actions) def copy(self): return ProgramState(self.arr.copy()) def commit_action(self, action): tnode_id, kwargs = action entry = self.tnod...
actions = self.get_bc_action(tnode)
conditional_block
tree_search.py
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing ...
# # 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
random_line_split
scan_run.pb.go
,proto3" json:"start_time,omitempty"` // The time at which the ScanRun reached termination state - that the ScanRun // is either finished or stopped by user. EndTime *timestamp.Timestamp `protobuf:"bytes,5,opt,name=end_time,json=endTime,proto3" json:"end_time,omitempty"` // The number of URLs crawled during thi...
return nil } func (m *ScanRun) GetUrlsCrawledCount() int64 { if m != nil { return m.UrlsCrawledCount } return 0 } func (m *ScanRun) GetUrlsTestedCount() int64 { if m != nil { return m.UrlsTestedCount } return 0 } func (m *ScanRun) GetHasVulnerabilities() bool { if m != nil { return...
{ return m.EndTime }
conditional_block
scan_run.pb.go
// A ScanRun is a output-only resource representing an actual run of the scan. type ScanRun struct { // The resource name of the ScanRun. The name follows the format of // 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'. // The ScanRun IDs are generated by the system. Name string `pr...
{ return fileDescriptor_d1e91fc2897e59cf, []int{0, 1} }
identifier_body
scan_run.pb.go
// The time at which the ScanRun started. StartTime *timestamp.Timestamp `protobuf:"bytes,4,opt,name=start_time,json=startTime,proto3" json:"start_time,omitempty"` // The time at which the ScanRun reached termination state - that the ScanRun // is either finished or stopped by user. EndTime *timestamp.Timestam...
random_line_split
scan_run.pb.go
,proto3" json:"start_time,omitempty"` // The time at which the ScanRun reached termination state - that the ScanRun // is either finished or stopped by user. EndTime *timestamp.Timestamp `protobuf:"bytes,5,opt,name=end_time,json=endTime,proto3" json:"end_time,omitempty"` // The number of URLs crawled during thi...
() ScanRun_ResultState { if m != nil { return m.ResultState } return ScanRun_RESULT_STATE_UNSPECIFIED } func (m *ScanRun) GetStartTime() *timestamp.Timestamp { if m != nil { return m.StartTime } return nil } func (m *ScanRun) GetEndTime() *timestamp.Timestamp { if m != nil { return m.EndT...
GetResultState
identifier_name
onnx_helpers.py
: enable constant-folding optimization # * input_names: setup input names as a list of string # * output_names: setup output names as a list of string # * opset_version: opset version of ONNX model. Latest one is recommended. # * operator_export_type: # * OperatorExportTypes.ON...
(prediction): """Merge two layers output into one. Args: prediction (np.array): probability map with 2 layers Returns: np.array: single layer probability map """ prob_map = prediction[0][0] prob_map_flipped = np.flip(prediction[1][0], (1)) # (H, ...
_np_merge_prediction
identifier_name
onnx_helpers.py
olding: enable constant-folding optimization # * input_names: setup input names as a list of string # * output_names: setup output names as a list of string # * opset_version: opset version of ONNX model. Latest one is recommended. # * operator_export_type: # * OperatorExportTy...
self.ort_session = ort.InferenceSession(onnx_path, sess_options=sess_options) def inference_ort(self, image, points): """Inference with ONNX Runtime session Args: image (np.array): processed image array points (np.arra...
# Setup options for optimization sess_options = ort.SessionOptions() sess_options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
random_line_split
onnx_helpers.py
) / _std return _image @staticmethod def _np_flip_n_cat(image): """Horizontal flipping and concatenation for model input Args: image (np.array): image array Returns: np.array: result array """ image_flip = np.flip(image, (2)) # flip the ...
"""ONNX interface contained main flow Args: img_np (np.array): image array in RBG-format click_list (List[List]): user click list onnx_handler (ONNXHandler): ONNX handler cfg (dict): config Returns: np.array: mask array with original image shape (H, W) """ # [pr...
identifier_body
onnx_helpers.py
: enable constant-folding optimization # * input_names: setup input names as a list of string # * output_names: setup output names as a list of string # * opset_version: opset version of ONNX model. Latest one is recommended. # * operator_export_type: # * OperatorExportTypes.ON...
image = self._np_transpose(input_image) image = self._np_normalize(image) image = self._np_flip_n_cat(image) return image @staticmethod def _np_sigmoid(prediction): """Sigmoid function for activation NOTE: * [WARN] Numerical stability is not handled...
input_image = self._np_resize_image(input_image, self.input_size, dtype='int')
conditional_block
table.go
services service.List) (PanelInfo, error) // InsertData 插入資料 InsertData(dataList form.Values) error // UpdateData 更新資料 UpdateData(dataList form.Values) error // DeleteData 刪除資料 DeleteData(pk string) error } // DefaultBaseTable 建立預設的BaseTable(同時也是Table(interface)) func DefaultBaseTable(cfgs ...ConfigTable) Ta...
res map[string]interface{} args = []interface{}{id} fields, joins, groupBy = "", "", "" tableName = base.GetFormPanel().Table pk = tableName + "." + base.PrimaryKey.Name queryStatement = "select %s from %s" + " %s where " + pk + "...
id = param.FindPK()
random_line_split
table.go
) countStatement string queryStatement string primaryKey = base.Informatoin.Table + "." + base.PrimaryKey.Name // 主鍵 wheres = "" args = make([]interface{}, 0) whereArgs = make([]interface{}, 0) existKeys = make([]string, 0) size int ) if len(ids) > 0 { quer...
identifier_body
table.go
services service.List) (PanelInfo, error) // InsertData 插入資料 InsertData(dataList form.Values) error // UpdateData 更新資料 UpdateData(dataList form.Values) error // DeleteData 刪除資料 DeleteData(pk string) error } // DefaultBaseTable 建立預設的BaseTable(同時也是Table(interface)) func DefaultBaseTable(cfgs ...ConfigTable) Ta...
strings.Split(id, ",") if base.Informatoin.DeleteFunc != nil { err := base.Informatoin.DeleteFunc(idArr) return err } return nil } // -----BaseTable的所有Table方法-----end // GetSQLByService 設置db.SQL(struct)的Connection、CRUD func (base *BaseTable) GetSQLByService(services service.List) *db.SQL { if base.connection...
Arr :=
identifier_name
table.go
) countStatement string queryStatement string primaryKey = base.Informatoin.Table + "." + base.PrimaryKey.Name // 主鍵 wheres = "" args = make([]interface{}, 0) whereArgs = make([]interface{}, 0) existKeys = make([]string, 0) size int ) if len(ids) > 0 { quer...
conditional_block
session.rs
let timestamp = time.timestamp() as i64; let nano = time.nanosecond() as i64; ((timestamp << 32) | (nano & 0x_7fff_fffc)) } #[derive(Debug, Clone)] pub struct AppId { pub api_id: i32, pub api_hash: String, } #[derive(Debug, Clone)] struct Salt { valid_since: DateTime<Utc>, valid_until: DateTi...
(&mut self) -> i32 { let ret = self.seq_no | 1; self.seq_no += 2; ret } fn next_seq_no(&mut self, content_message: bool) -> i32 { if content_message { self.next_content_seq_no() } else { self.seq_no } } fn latest_server_salt(&mut ...
next_content_seq_no
identifier_name
session.rs
4; ((timestamp << 32) | (nano & 0x_7fff_fffc)) } #[derive(Debug, Clone)] pub struct AppId { pub api_id: i32, pub api_hash: String, } #[derive(Debug, Clone)] struct Salt { valid_since: DateTime<Utc>, valid_until: DateTime<Utc>, salt: i64, } impl From<mtproto::FutureSalt> for Salt { fn from...
Either::Left(m) => self.serialize_plain_message(m),
random_line_split
typechecking.rs
_table_handle.borrow(); self.global_env.populate_from_symbols(symbol_table); let output = self.global_env.infer_block(&input.0)?; Ok(format!("{:?}", output)) } } impl TypeEnv { fn instantiate(&mut self, sigma: Scheme) -> Type { match sigma { Scheme { ty, .. } => ty, } } fn generate(&m...
use self::parsing::Declaration::*; use self::Type::*; match decl {
random_line_split
typechecking.rs
TypeName, Type>, symbol_table_handle: Rc<RefCell<SymbolTable>>, global_env: TypeEnv } impl<'a> TypeContext<'a> { pub fn new(symbol_table_handle: Rc<RefCell<SymbolTable>>) -> TypeContext<'static> { TypeContext { values: ScopeStack::new(None), global_env: TypeEnv::default(), symbol_table_handle } } pub f...
Value(name) => { let s = match self.0.get(name) { Some(sigma) => sigma.clone(), None => return Err(format!("Unknown variable: {}", name)) }; self.instantiate(s) }, _ => Type::Const(Unit) }) } } /* GIANT TODO - use the rust im crate, unless I make thi...
return Err(format!("NOTDONE")) },
conditional_block
typechecking.rs
ashMap<TypeName, Type>); impl Substitution { fn empty() -> Substitution { Substitution(HashMap::new()) } } #[derive(Debug, PartialEq, Clone)] struct TypeEnv(HashMap<TypeName, Scheme>); impl TypeEnv { fn default() -> TypeEnv { TypeEnv(HashMap::new()) } fn populate_from_symbols(&mut self, symbol_tabl...
bstitution(H
identifier_name
summary6.1.py
计所有属于主动买入的Signal类型 buy_signal_types = t[t[u"类型"] == u"买入"].groupby('Signal') # 统计所有属于主动卖空的Signal类型 short_signal_types = t[t['类型'] == '卖空'].groupby('Signal') buy_signals_name_list = buy_signal_types.size()._index short_signals_name_list = short_signal_types.size()._index signal_class_list = [] ...
返回结果:最大回撤率,开始日期,结束日期,总收益率,年化收益,年化回撤 ''' t['Capital'] = float(t['价格'][1])+t['Net Profit - Cum Net Profit'] yearly_drawdown = dict() t['Year']=pd.Series(t['Date/Time'][i].year for i in range(len(t))) t_group=t.groupby('Year') year_groups=[t_group.get_gro...
def drawdown_by_time(t: pd.DataFrame): ''' 计算内容:最大回撤比例,累计收益率 计算方式:单利
random_line_split
summary6.1.py
所有属于主动买入的Signal类型 buy_signal_types = t[t[u"类型"] == u"买入"].groupby('Signal') # 统计所有属于主动卖空的Signal类型 short_signal_types = t[t['类型'] == '卖空'].groupby('Signal') buy_signals_name_list = buy_signal_types.size()._index short_signals_name_list = short_signal_types.size()._index signal_class_list = [] ...
ow['Date/Time'], start_price=this_row['价格'], end_price=next_row['价格'], start_signal=this_row['Signal'], end_signal=next_row['Signal'], volume=this_row['Shares/Ctrts/Units - Profit/Loss'])) print('添加交易记录对象...') return frequency ...
'], end= next_r
identifier_name
summary6.1.py
所有属于主动买入的Signal类型 buy_signal_types = t[t[u"类型"] == u"买入"].groupby('Signal') # 统计所有属于主动卖空的Signal类型 short_signal_types = t[t['类型'] == '卖空'].groupby('Signal') buy_signals_name_list = buy_signal_types.size()._index short_signals_name_list = short_signal_types.size()._index signal_class_list = [] ...
for i in range(2, len(t),2): # 偶数行的数据 if temp_max_value < t['Capital'][i-2]: current_start_date = t['Date/Time'][i] temp_max_value = max(temp_max_value, t['Capital'][i-2]) if max_draw_down>t['Capital'][i]/temp_max_value-1: if not continous: ...
oup['Date/Time'][i] temp_max_value = max(temp_max_value, year_group['Capital'][i]) continous = False else: if max_draw_down>year_group['Capital'][i]/temp_max_value-1: if not continous: contin...
identifier_body
summary6.1.py
:用最后的净值/最先的净值作为比例。(eg. 1.06/1.02) duration = (ts.index[-1]-ts.index[0]).days/365 # 从第一次交易到最后一次交易的时间 if (duration == 0): yearly_rate = ts[0] #如果只有一次交易,时间跨度是0不能计算,则用该交易的收益率作为yearly_rate else: yearly_rate = ratio**(1/duration)-1 # 算出年化收益率 ret...
数 ''' table[start_row-1][start_col].value = '每日交易次数' fd = frequency.describe() for i in range(len(fd)): table[start_row+i][start_col].value = fd.keys()[i] table[start_row+i][start_col+1].value = fd[i] table[start_row+i][start_col+1].number_format=forma...
conditional_block
client.ts
* @returns preset query on the client. */ get query () { return this._query } /** * @returns preset request options on the client. */ get requestOptions () { return this._requestOptions } /** * Creates (by Object.create) a **new client** instance with given service methods. * @para...
{ return new Promise((resolve) => $setTimeout(resolve, ms)) }
identifier_body
client.ts
null ? Math.floor(options.retryDelay) : 2000 const maxAttempts = options.maxAttempts != null ? Math.floor(options.maxAttempts) : 3 const retryErrorCodes = Array.isArray(options.retryErrorCodes) ? options.retryErrorCodes : RETRIABLE_ERRORS // default to `false` options.followRedirect = options.followRe...
(periodical: number = 3600, options?: jwt.SignOptions) { const iat = Math.floor(Date.now() / (1000 * periodical)) * periodical const payload = { iat, exp: iat + Math.floor(1.1 * periodical), _appId: this._options.appId, } // token change in every hour, optimizing for server cache. ...
signAppToken
identifier_name