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 |
|---|---|---|---|---|
DissertationScript.py | from subprocess import call
import os
import pandas as pd
from pandas import DataFrame
import string
import re
from urllib.request import urlopen
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.se... |
###LASTLY, once you have the shell file created from rtmp_file, run it from Linux command line.
###First, you need to run rtmpsrv and such...
if __name__ == "__main__":
#match_name_CongressRecord()
#add_dates()
#cspan_selenium_getsite()
get_vid()
| name = line.split("\t")[0].replace(" ","")
date = line.split("\t")[3].split("-")[:-1]
date = "-".join(date)
starttime = line.split("\t")[7]
if len(line.split("\t"))>10:
rtmp = line.split("\t")[10].split(" -o ")[0] + " -o " +name + date + "_" + starttime + ... | conditional_block |
DissertationScript.py | from subprocess import call
import os
import pandas as pd
from pandas import DataFrame
import string
import re
from urllib.request import urlopen
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.se... |
#Because there weren't corresponding videos for the specific dates in the Congressional Record transcripts,
#this just makes it so you can search a person on C-SPAN for that whole month, not just a specific day.
def add_date_month():
with open("C-SPAN PersonID and File Dates.txt") as f:
f = f.read().split... | date = datetime.datetime.strptime(date,"%Y-%m-%d")
date = datetime.datetime.strftime(date, "%Y-%m-%d")
return(date) | identifier_body |
makesnapshots.py | #!/usr/bin/env python3
"""
# (c) 2012/2014 E.M. van Nuil / Oblivion b.v.
#
# makesnapshots.py version 3.3
#
# Changelog
# version 1: Initial version
# version 1.1: Added description and region
# version 1.2: Added extra error handeling and logging
# version 1.3: Added SNS email functionality for succes and error repo... | (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 | #!/usr/bin/env python3
"""
# (c) 2012/2014 E.M. van Nuil / Oblivion b.v.
#
# makesnapshots.py version 3.3
#
# Changelog
# version 1: Initial version
# version 1.1: Added description and region
# version 1.2: Added extra error handeling and logging
# version 1.3: Added SNS email functionality for succes and error repo... |
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 | #!/usr/bin/env python3
"""
# (c) 2012/2014 E.M. van Nuil / Oblivion b.v.
#
# makesnapshots.py version 3.3
#
# Changelog
# version 1: Initial version
# version 1.1: Added description and region
# version 1.2: Added extra error handeling and logging
# version 1.3: Added SNS email functionality for succes and error repo... | 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 | #!/usr/bin/env python3
"""
# (c) 2012/2014 E.M. van Nuil / Oblivion b.v.
#
# makesnapshots.py version 3.3
#
# Changelog
# version 1: Initial version
# version 1.1: Added description and region
# version 1.2: Added extra error handeling and logging
# version 1.3: Added SNS email functionality for succes and error repo... |
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 | #[cfg(feature = "encoding")]
use encoding_rs::UTF_8;
use crate::encoding::Decoder;
use crate::errors::{Error, Result};
use crate::events::{BytesCData, BytesDecl, BytesEnd, BytesStart, BytesText, Event};
#[cfg(feature = "encoding")]
use crate::reader::EncodingRef;
use crate::reader::{is_whitespace, BangType, ParseState... | <'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 | #[cfg(feature = "encoding")]
use encoding_rs::UTF_8;
use crate::encoding::Decoder;
use crate::errors::{Error, Result};
use crate::events::{BytesCData, BytesDecl, BytesEnd, BytesStart, BytesText, Event};
#[cfg(feature = "encoding")]
use crate::reader::EncodingRef;
use crate::reader::{is_whitespace, BangType, ParseState... | /// 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 | #[cfg(feature = "encoding")]
use encoding_rs::UTF_8;
use crate::encoding::Decoder;
use crate::errors::{Error, Result};
use crate::events::{BytesCData, BytesDecl, BytesEnd, BytesStart, BytesText, Event};
#[cfg(feature = "encoding")]
use crate::reader::EncodingRef;
use crate::reader::{is_whitespace, BangType, ParseState... |
}
impl Default for Parser {
fn default() -> Self {
Self {
offset: 0,
state: ParseState::Init,
expand_empty_elements: false,
trim_text_start: false,
trim_text_end: false,
trim_markup_names_in_closing_tags: true,
check_end_n... | {
Decoder {
#[cfg(feature = "encoding")]
encoding: self.encoding.encoding(),
}
} | identifier_body |
parser.rs | #[cfg(feature = "encoding")]
use encoding_rs::UTF_8;
use crate::encoding::Decoder;
use crate::errors::{Error, Result};
use crate::events::{BytesCData, BytesDecl, BytesEnd, BytesStart, BytesText, Event};
#[cfg(feature = "encoding")]
use crate::reader::EncodingRef;
use crate::reader::{is_whitespace, BangType, ParseState... |
}
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 | /**
* Tencent is pleased to support the open source community by making CL5 available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a... | 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 | /**
* Tencent is pleased to support the open source community by making CL5 available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a... | 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.OperationDiscoverInstance, false)
... | 辑
func (t *ConsumerMeshTestin | identifier_name |
api_consumer_mesh_suite.go | /**
* Tencent is pleased to support the open source community by making CL5 available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a... | rt TestGetMeshConfig")
t.testGetMeshConfig(c, false, true, true)
}
//测试获取不存在的网格规则
func (t *ConsumerMeshTestingSuite) TestGetMeshConfigNotExist(c *check.C) {
log.Printf("Start TestGetMeshConfigNotExist")
t.testGetMeshConfig(c, false, false, true)
}
//测试获取类型不匹配的网格规则
func (t *ConsumerMeshTestingSuite) TestGetMeshCon... | ).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 | /**
* Tencent is pleased to support the open source community by making CL5 available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a... | 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 | use super::{
branch_expander, data_expander, heap2stack, ir::*, normalizer, rewriter, simplifier, traverser,
};
use crate::ast;
use crate::module::ModuleSet;
use derive_new::new;
use if_chain::if_chain;
use std::collections::{hash_map, BTreeSet, HashMap};
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct Cont... | fn data_expansions(&mut self) -> &mut HashMap<CtId, data_expander::DataExpansion> {
self.data_expansions
}
}
#[derive(Debug, new)]
struct MatchExpander<'a> {
rt_id_gen: &'a mut RtIdGen,
data_expansions: &'a HashMap<CtId, data_expander::DataExpansion>,
}
impl<'a> branch_expander::Env for MatchE... | random_line_split | |
context.rs | use super::{
branch_expander, data_expander, heap2stack, ir::*, normalizer, rewriter, simplifier, traverser,
};
use crate::ast;
use crate::module::ModuleSet;
use derive_new::new;
use if_chain::if_chain;
use std::collections::{hash_map, BTreeSet, HashMap};
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct Cont... | (&mut self, def: CtDef) -> CtId {
let id = self.ct_id_gen.next();
self.defs.insert(id, def);
id
}
fn data_expansions(&mut self) -> &mut HashMap<CtId, data_expander::DataExpansion> {
self.data_expansions
}
}
#[derive(Debug, new)]
struct MatchExpander<'a> {
rt_id_gen: &'a... | 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... |
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 manager.key in self.config['jobmanagers']:
currency = manager.confi... | 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 | package client
import (
"context"
"encoding/json"
"errors"
"fmt"
"runtime"
"sort"
"net"
"os"
"sync"
"time"
"github.com/blackbeans/kiteq-common/protocol"
"github.com/blackbeans/kiteq-common/registry"
"github.com/blackbeans/kiteq-common/stat"
"github.com/blackbeans/turbo"
)
var addressPool = &sync.Pool... | //remoteAddr := tc.RemoteAddr()
return false
})
}
func (k *kite) heartbeat() {
for {
select {
case <-time.After(k.heartbeatPeriod):
//心跳检测
k.addressToTClient.Range(func(key, value interface{}) bool {
i := 0
future := value.(*turbo.FutureTask)
if v, err := future.Get(); nil == err && nil !=... | {
//只接收
| identifier_name |
kite.go | package client
import (
"context"
"encoding/json"
"errors"
"fmt"
"runtime"
"sort"
"net"
"os"
"sync"
"time"
"github.com/blackbeans/kiteq-common/protocol"
"github.com/blackbeans/kiteq-common/registry"
"github.com/blackbeans/kiteq-common/stat"
"github.com/blackbeans/turbo"
)
var addressPool = &sync.Pool... | 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 | package client
import (
"context"
"encoding/json"
"errors"
"fmt"
"runtime"
"sort"
"net"
"os"
"sync"
"time"
"github.com/blackbeans/kiteq-common/protocol"
"github.com/blackbeans/kiteq-common/registry"
"github.com/blackbeans/kiteq-common/stat"
"github.com/blackbeans/turbo"
)
var addressPool = &sync.Pool... | 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 | package client
import (
"context"
"encoding/json"
"errors"
"fmt"
"runtime"
"sort"
"net"
"os"
"sync"
"time"
"github.com/blackbeans/kiteq-common/protocol"
"github.com/blackbeans/kiteq-common/registry"
"github.com/blackbeans/kiteq-common/stat"
"github.com/blackbeans/turbo"
)
var addressPool = &sync.Pool... | 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 | ##### Repository for the calculations, mostly related to submesoscale heat fluxes
##### Isabelle Giddy 2020
###########################################################
# All data should be gridded to equal horizontal distances to standardise gradients in density
# Python Modules
import numpy as np
import matplotlib... | icity):
"""
The modified Rossby Number gives a measure of horizontal shear
"""
Ro = vorticity/f
modRo = np.arctan(-1-Ro)
return Ro, modRo
| (f,vort | identifier_name |
sms_fluxes.py | ##### Repository for the calculations, mostly related to submesoscale heat fluxes
##### Isabelle Giddy 2020
###########################################################
# All data should be gridded to equal horizontal distances to standardise gradients in density
# Python Modules
import numpy as np
import matplotlib... |
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 | ##### Repository for the calculations, mostly related to submesoscale heat fluxes
##### Isabelle Giddy 2020
###########################################################
# All data should be gridded to equal horizontal distances to standardise gradients in density
# Python Modules
import numpy as np
import matplotlib... |
# 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 | ##### Repository for the calculations, mostly related to submesoscale heat fluxes
##### Isabelle Giddy 2020
###########################################################
# All data should be gridded to equal horizontal distances to standardise gradients in density
# Python Modules
import numpy as np
import matplotlib... | ############################################################################################
# EKMAN BUOYANCY FLUX
def calc_ebf(buoyancy_gradient_mld,wind_dir,glider_dir,tau_x,tau_y,f,alpha,cp=4000,g=9.8):
"""
Calculates the wind force on the ocean over fronts
Downfront windstress, or wind stress in the... | 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 | import { Machine } from 'script-engine';
declare const require;
let fetchFunction;
if (typeof fetch === 'undefined' && typeof require === 'function') {
const nodeFetchPackageName = 'node-fetch';
fetchFunction = eval('require(nodeFetchPackageName)');
} else {
fetchFunction = window.fetch;
}
let btoaFunct... | else {
throw new ProxyCommunicationError('unknown', 'Internal request failed (status: ' + status + ')');
}
}).then((response: ResponseDef) => {
// request from proxy to external server failed
if (response.error_type && response.error_message) {
... | {
return response;
} | conditional_block |
Fetch.ts | import { Machine } from 'script-engine';
declare const require;
let fetchFunction;
if (typeof fetch === 'undefined' && typeof require === 'function') {
const nodeFetchPackageName = 'node-fetch';
fetchFunction = eval('require(nodeFetchPackageName)');
} else {
fetchFunction = window.fetch;
}
let btoaFunct... | extends FetchRequest {
public constructor(url: string) {
super('HEAD', url);
}
}
export class OptionsRequest extends FetchRequest {
public constructor(url: string) {
super('OPTIONS', url);
}
}
| HeadRequest | identifier_name |
Fetch.ts | import { Machine } from 'script-engine';
declare const require;
let fetchFunction;
if (typeof fetch === 'undefined' && typeof require === 'function') {
const nodeFetchPackageName = 'node-fetch';
fetchFunction = eval('require(nodeFetchPackageName)');
} else {
fetchFunction = window.fetch;
}
let btoaFunct... | 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 | #!/usr/bin/env python
import rospy
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from sklearn.cluster import KMeans
from sklearn import preprocessing
from sklearn import linear_model
import numpy as np
from scipy import optimize
import yaml
import sys
from matplotlib impor... | (self,event,x,y,flags,param):
if event == cv2.EVENT_LBUTTONDOWN:
self.drawing = True
self.rect_done = False
self.ix1 = x
self.iy1 = y
elif event == cv2.EVENT_MOUSEMOVE:
if self.drawing == True:
self.ix2 = x
self... | draw_rect | identifier_name |
grasp_pos.py | #!/usr/bin/env python
import rospy
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from sklearn.cluster import KMeans
from sklearn import preprocessing
from sklearn import linear_model
import numpy as np
from scipy import optimize
import yaml
import sys
from matplotlib impor... |
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 | #!/usr/bin/env python
import rospy
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from sklearn.cluster import KMeans
from sklearn import preprocessing
from sklearn import linear_model
import numpy as np
from scipy import optimize
import yaml
import sys
from matplotlib impor... | 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 | #!/usr/bin/env python
import rospy
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from sklearn.cluster import KMeans
from sklearn import preprocessing
from sklearn import linear_model
import numpy as np
from scipy import optimize
import yaml
import sys
from matplotlib impor... |
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 | type draftFolderTab = 'inbox' | 'flagged' | 'archive' | 'trash' | 'all'
/**
* The Draft object represents a single draft. When an action is run, the current draft is available as the global variable `draft`. Scripts can also create new drafts, access and set values, and update the draft to persist changes.
*
* @exa... | 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 | type draftFolderTab = 'inbox' | 'flagged' | 'archive' | 'trash' | 'all'
/**
* The Draft object represents a single draft. When an action is run, the current draft is available as the global variable `draft`. Scripts can also create new drafts, access and set values, and update the draft to persist changes.
*
* @exa... | {
/**
* 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 | package hive
import (
"context"
"fmt"
"sync/atomic"
"time"
"crypto/md5"
"dmp_web/go/commons/db/hive/tcliservice"
"dmp_web/go/commons/log"
)
var (
ErrClosing = fmt.Errorf("I'm closing, please try it later")
)
type Cli interface {
AddPollingWithCallback(op *Operation, f func(*PollingResult))
AddPolling(op *... | 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 | package hive
import (
"context"
"fmt"
"sync/atomic"
"time"
"crypto/md5"
"dmp_web/go/commons/db/hive/tcliservice"
"dmp_web/go/commons/log"
)
var (
ErrClosing = fmt.Errorf("I'm closing, please try it later")
)
type Cli interface {
AddPollingWithCallback(op *Operation, f func(*PollingResult))
AddPolling(op *... | ompareAndSwapInt32(&c.closed, 0, 1) {
return
}
c.pool.Close()
}
//打印hive日志。注意本方法会一直执行直到hive结束(成功or失败),建议单起一个goroutine来执行本方法
func (c *Client) logResponseLog(handle *tcliservice.TOperationHandle) {
start := time.Now()
//每次拉取日志行数
maxRows := 20
req := tcliservice.NewTFetchResultsReq()
req.OperationHandle = hand... | mic.C | identifier_name |
client.go | package hive
import (
"context"
"fmt"
"sync/atomic"
"time"
"crypto/md5"
"dmp_web/go/commons/db/hive/tcliservice"
"dmp_web/go/commons/log"
)
var (
ErrClosing = fmt.Errorf("I'm closing, please try it later")
)
type Cli interface {
AddPollingWithCallback(op *Operation, f func(*PollingResult))
AddPolling(op *... | 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 | package hive
import (
"context"
"fmt"
"sync/atomic"
"time"
"crypto/md5"
"dmp_web/go/commons/db/hive/tcliservice"
"dmp_web/go/commons/log"
)
var (
ErrClosing = fmt.Errorf("I'm closing, please try it later")
)
type Cli interface {
AddPollingWithCallback(op *Operation, f func(*PollingResult))
AddPolling(op *... | Close() {
if !atomic.CompareAndSwapInt32(&c.closed, 0, 1) {
return
}
c.pool.Close()
}
//打印hive日志。注意本方法会一直执行直到hive结束(成功or失败),建议单起一个goroutine来执行本方法
func (c *Client) logResponseLog(handle *tcliservice.TOperationHandle) {
start := time.Now()
//每次拉取日志行数
maxRows := 20
req := tcliservice.NewTFetchResultsReq()
re... | {
// 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 |
import { coerceCssPixelValue } from '@angular/cdk/coercion';
import { Point } from '@angular/cdk/drag-drop';
import { map, append, sortBy, path, compose, curryN, findIndex as rFindIndex, reduce, head, forEach, addIndex, flatten, groupWith, pathEq, last } from 'ramda';
import { floor, toArray } from 'ramda-adjunct';
im... |
}
/**
* Finds the index of an item that matches a predicate function. Used as an equivalent
* of `Array.prototype.findIndex` which isn't part of the standard Google typings.
* @param array Array in which to look for matches.
* @param predicate Function used to determine whether an item is a match.
*/
function fi... | {
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 | import { coerceCssPixelValue } from '@angular/cdk/coercion';
import { Point } from '@angular/cdk/drag-drop';
import { map, append, sortBy, path, compose, curryN, findIndex as rFindIndex, reduce, head, forEach, addIndex, flatten, groupWith, pathEq, last } from 'ramda';
import { floor, toArray } from 'ramda-adjunct';
imp... | 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 |
import { coerceCssPixelValue } from '@angular/cdk/coercion';
import { Point } from '@angular/cdk/drag-drop';
import { map, append, sortBy, path, compose, curryN, findIndex as rFindIndex, reduce, head, forEach, addIndex, flatten, groupWith, pathEq, last } from 'ramda';
import { floor, toArray } from 'ramda-adjunct';
im... | (): 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 | extern crate fixedbitset;
extern crate getopts;
extern crate libc;
extern crate regex;
extern crate toml;
extern crate num_cpus;
use regex::Regex;
use std::fs;
use std::io;
use std::io::{Read, Write, BufRead};
use std::path;
use std::sync;
use std::sync::mpsc;
use std::thread;
#[cfg(not(test))]
fn main()
{
let arg... |
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 | extern crate fixedbitset;
extern crate getopts;
extern crate libc;
extern crate regex;
extern crate toml;
extern crate num_cpus;
use regex::Regex;
use std::fs;
use std::io;
use std::io::{Read, Write, BufRead};
use std::path;
use std::sync;
use std::sync::mpsc;
use std::thread;
#[cfg(not(test))]
fn main()
{
let arg... | (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 | extern crate fixedbitset;
extern crate getopts;
extern crate libc;
extern crate regex;
extern crate toml;
extern crate num_cpus;
use regex::Regex;
use std::fs;
use std::io;
use std::io::{Read, Write, BufRead};
use std::path;
use std::sync;
use std::sync::mpsc;
use std::thread;
#[cfg(not(test))]
fn main()
{
let arg... |
#[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 | extern crate fixedbitset;
extern crate getopts;
extern crate libc;
extern crate regex;
extern crate toml;
extern crate num_cpus;
use regex::Regex;
use std::fs;
use std::io;
use std::io::{Read, Write, BufRead};
use std::path;
use std::sync;
use std::sync::mpsc;
use std::thread;
#[cfg(not(test))]
fn main()
{
let arg... | }
}
}
if failed_files.len() > 0 {
println!("Summary of failed files:");
for ffn in failed_files { println!(" {}", ffn); }
panic!();
}
} | } 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 | # -*- coding: utf-8 -*-
# Copyright (C) 2018 - Benjamin Hebgen <mail>
# This program is Free Software see LICENSE file for details
import os
import sys
import xbmc
import xbmcvfs
import xbmcgui
import xbmcplugin
import xbmcaddon
import simplejson as json
import urllib
import re
try:
from urllib.request import Reque... |
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 | # -*- coding: utf-8 -*-
# Copyright (C) 2018 - Benjamin Hebgen <mail>
# This program is Free Software see LICENSE file for details
import os
import sys
import xbmc
import xbmcvfs
import xbmcgui
import xbmcplugin
import xbmcaddon
import simplejson as json
import urllib
import re
try:
from urllib.request import Reque... |
def addToPlaylist(path, art, label):
playList = xbmc.PlayList(1)
pos = playList.getposition();
pos += 1
item = createListItem(label, path, art, label)
playList.add(path, item, pos)
def playNext():
xbmc.Player().playnext()
window = xbmcgui.Window(12005)
window.show()
window.doModal()
def getLastDir():... | mediaInfo = getRunningmediaInfoInfo()
listItems = getRelatedItems(mediaInfo)
if(listItems):
passToSkin(listItems) | identifier_body |
plugin.py | # -*- coding: utf-8 -*-
# Copyright (C) 2018 - Benjamin Hebgen <mail>
# This program is Free Software see LICENSE file for details
import os
import sys
import xbmc
import xbmcvfs
import xbmcgui
import xbmcplugin
import xbmcaddon
import simplejson as json
import urllib
import re
try:
from urllib.request import Reque... | 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 | # -*- coding: utf-8 -*-
# Copyright (C) 2018 - Benjamin Hebgen <mail>
# This program is Free Software see LICENSE file for details
import os
import sys
import xbmc
import xbmcvfs
import xbmcgui
import xbmcplugin
import xbmcaddon
import simplejson as json
import urllib
import re
try:
from urllib.request import Reque... | (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 | package storage
import (
"context"
"reflect"
"regexp"
"sort"
"strings"
"github.com/zero-os/0-Disk/config"
"github.com/zero-os/0-Disk/errors"
"github.com/zero-os/0-Disk/log"
"github.com/zero-os/0-Disk/nbd/ardb"
"github.com/zero-os/0-Disk/nbd/ardb/command"
)
// BlockStorage defines an interface for all a blo... |
nbdConfig, err := config.ReadNBDStorageConfig(source, vdiskID)
if err != nil {
return nil, errors.Wrap(err, "failed to ReadNBDStorageConfig")
}
// create (primary) storage cluster
// TODO: support optional slave cluster here
// see: https://github.com/zero-os/0-Disk/issues/445
cluster, err := ardb.NewCluste... | {
return nil, err
} | conditional_block |
storage.go | package storage
import (
"context"
"reflect"
"regexp"
"sort"
"strings"
"github.com/zero-os/0-Disk/config"
"github.com/zero-os/0-Disk/errors"
"github.com/zero-os/0-Disk/log"
"github.com/zero-os/0-Disk/nbd/ardb"
"github.com/zero-os/0-Disk/nbd/ardb/command"
)
// BlockStorage defines an interface for all a blo... |
// dedupStrings deduplicates a given string slice which is already sorted.
func dedupStrings(s []string) []string {
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:]
}
// a slightly expensive helper function which allows
// us ... | {
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 | package storage
import (
"context"
"reflect"
"regexp"
"sort"
"strings"
"github.com/zero-os/0-Disk/config"
"github.com/zero-os/0-Disk/errors"
"github.com/zero-os/0-Disk/log"
"github.com/zero-os/0-Disk/nbd/ardb"
"github.com/zero-os/0-Disk/nbd/ardb/command"
)
// BlockStorage defines an interface for all a blo... | (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 | package storage
import (
"context"
"reflect"
"regexp"
"sort"
"strings"
"github.com/zero-os/0-Disk/config"
"github.com/zero-os/0-Disk/errors"
"github.com/zero-os/0-Disk/log"
"github.com/zero-os/0-Disk/nbd/ardb"
"github.com/zero-os/0-Disk/nbd/ardb/command"
)
// BlockStorage defines an interface for all a blo... | 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 | from os import name
import tkinter
import pyodbc
import openpyxl
from tkinter import messagebox
from tkinter import *
class Customer:
def __init__(self, name, budget):
self.name = name
self.budget = budget
self.finalBill = {}
def BuyTicket(self, cinema):
movieInde... |
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 | from os import name
import tkinter
import pyodbc
import openpyxl
from tkinter import messagebox
from tkinter import *
class Customer:
def __init__(self, name, budget):
self.name = name
self.budget = budget
self.finalBill = {}
def BuyTicket(self, cinema):
movieInde... |
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 | from os import name
import tkinter
import pyodbc
import openpyxl
from tkinter import messagebox
from tkinter import *
class Customer:
def __init__(self, name, budget):
self.name = name
self.budget = budget
self.finalBill = {}
def BuyTicket(self, cinema):
movieInde... |
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 +'; \
DATABASE='+ database ... | 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 | from os import name
import tkinter
import pyodbc
import openpyxl
from tkinter import messagebox
from tkinter import *
class Customer:
def __init__(self, name, budget):
self.name = name
self.budget = budget
self.finalBill = {}
def BuyTicket(self, cinema):
movieInde... |
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 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
generated_project_dir = temp_dir / "project"
project = tvm.micro.project.generate_project_from_mlf(
template_project_path, generated_project_dir, model_tar_path, project_options
)
project.build()
# Cleanup the build directory and extra artifacts
shutil.rmtree(generated_project_dir / "build")
(generated_project_... | project_options["cmsis_path"] = os.environ.get("CMSIS_PATH", "/content/cmsis") | conditional_block |
micro_mlperftiny.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | # west flash
#
# Now you can connect your board to EEMBC runner using this
# `instructions <https://github.com/eembc/energyrunner>`_
# and benchmark this model on your board.
# | # cmake ..
# make -j2 | random_line_split |
client.go | package main
import (
"EdgeBFT/common"
"fmt"
"net"
"bufio"
"time"
"os"
"strings"
"sync"
"strconv"
"encoding/json"
"io/ioutil"
"regexp"
"math"
"github.com/libp2p/go-reuseport"
)
// var all_start bool
var lock_mutex = &sync.Mutex{}
type Latencies struct {
start string
end string
time float64
}... | (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 | package main
import (
"EdgeBFT/common"
"fmt"
"net"
"bufio"
"time"
"os"
"strings"
"sync"
"strconv"
"encoding/json"
"io/ioutil"
"regexp"
"math"
"github.com/libp2p/go-reuseport"
)
// var all_start bool
var lock_mutex = &sync.Mutex{}
type Latencies struct {
start string
end string
time float64
}... |
// 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 | package main
import (
"EdgeBFT/common"
"fmt"
"net"
"bufio"
"time"
"os"
"strings"
"sync"
"strconv"
"encoding/json"
"io/ioutil"
"regexp"
"math"
"github.com/libp2p/go-reuseport"
)
// var all_start bool
var lock_mutex = &sync.Mutex{}
type Latencies struct {
start string
end string
time float64
}... |
func main() {
num_c := 10
num_t := 10
zone := "0"
client_id_seed := 0
// percent := 0.5
ip_addr := "127.0.0.1"
port := 8000
argsWithoutProg := os.Args[1:]
for i, s := range argsWithoutProg {
switch s {
case "-a":
ip_addr = argsWithoutProg[i + 1]
case "-p":
new_p, err := strconv.Atoi(argsW... | {
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 | package main
import (
"EdgeBFT/common"
"fmt"
"net"
"bufio"
"time"
"os"
"strings"
"sync"
"strconv"
"encoding/json"
"io/ioutil"
"regexp"
"math"
"github.com/libp2p/go-reuseport"
)
// var all_start bool
var lock_mutex = &sync.Mutex{}
type Latencies struct {
start string
end string
time float64
}... | 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 | const axios = require('axios')
const tough = require('tough-cookie')
const axiosCookieJarSupport = require('axios-cookiejar-support').default
const createCaptcheKey = require('./captche').createCaptcheKey
const cryptojs = require('./cryptojs')
const parsePhone = require('phone')
const { v4: uuidv4 } = require('uuid')
... | 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 | const axios = require('axios')
const tough = require('tough-cookie')
const axiosCookieJarSupport = require('axios-cookiejar-support').default
const createCaptcheKey = require('./captche').createCaptcheKey
const cryptojs = require('./cryptojs')
const parsePhone = require('phone')
const { v4: uuidv4 } = require('uuid')
... | = (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 axios = require('axios')
const tough = require('tough-cookie')
const axiosCookieJarSupport = require('axios-cookiejar-support').default
const createCaptcheKey = require('./captche').createCaptcheKey
const cryptojs = require('./cryptojs')
const parsePhone = require('phone')
const { v4: uuidv4 } = require('uuid')
... | t headers = {
'origin': `https://${host}`,
'referer': `https://${host}/webchat/login`,
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
'x-forwarded-proto': 'https',
'x-forwarded-port': '443',
'... | )
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 | const axios = require('axios')
const tough = require('tough-cookie')
const axiosCookieJarSupport = require('axios-cookiejar-support').default
const createCaptcheKey = require('./captche').createCaptcheKey
const cryptojs = require('./cryptojs')
const parsePhone = require('phone')
const { v4: uuidv4 } = require('uuid')
... | "distribution_status": null,
"shop_id": 16246947,
"is_blocked": false,
"id": 16248284,
"country": "MY",
"locale": "en",
"status": "normal",
"avatar": null,
"cb_option": 1,
"type": "seller"
}
}
jar.getCookies('https://seller.my.shopee.cn/', (err, cookies) => {
// cookies数组
c... | "user": {
"username": "mangoali.my",
"rating": 0,
"uid": "0-16248284", | random_line_split |
slice_test.rs | use std::mem;
fn print_slice(slice : &[i32]) {
for i in slice{
println!("{}", i);
}
}
fn move_in_array(mut arr : [i32; 8]) {
for i in &mut arr {
*i = *i + 1;
println!("{} ", i);
}
}
pub fn slice_size_len() {
println!("{}", mem::size_of::<&[i32]>());
// println!("{}", m... |
pub fn window() {
// Why we can't implement windows_mut?
// if we implement windows_mut, we can get two
// mutable slices that share a portion of the elements
// in the original slice.
let slice = &[1,2,3,4,5][..];
let wins = slice.windows(3);
for win in wins {
println!("start of... | {
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 | use std::mem;
fn print_slice(slice : &[i32]) {
for i in slice{
println!("{}", i);
}
}
fn move_in_array(mut arr : [i32; 8]) {
for i in &mut arr {
*i = *i + 1;
println!("{} ", i);
}
}
pub fn slice_size_len() {
println!("{}", mem::size_of::<&[i32]>());
// println!("{}", m... |
}
let slice = &mut vec[..];
println!("printing the vec after insertion");
for i in slice {
println!("{}", i);
}
}
pub fn rotate_left() {
let slice = &mut [1,2,3,4,5][..];
slice.rotate_left(1);
println!("{:?}", slice);
}
fn manual_clone_from_slice<T : Clone>(dst : &mut [T], sr... | {
println!("please insert 109 at index {}", i);
vec.insert(i, 109);
} | conditional_block |
slice_test.rs | use std::mem;
fn print_slice(slice : &[i32]) {
for i in slice{
println!("{}", i);
}
}
fn move_in_array(mut arr : [i32; 8]) {
for i in &mut arr {
*i = *i + 1;
println!("{} ", i);
}
}
pub fn slice_size_len() {
println!("{}", mem::size_of::<&[i32]>());
// println!("{}", m... | () {
let mut vec = vec!(2,1,2,4,3,2,3,2,1,3,2,3,4,5);
println!("{:?}", &vec);
let slice = &mut vec[..];
slice.sort_unstable();
let res = slice.binary_search(&3);
match res {
Ok(i) => {
println!("found {} from index {}", slice[i], i);
},
Err(i) => {
... | sort_and_search | identifier_name |
slice_test.rs | use std::mem;
fn print_slice(slice : &[i32]) {
for i in slice{
println!("{}", i);
}
}
fn move_in_array(mut arr : [i32; 8]) {
for i in &mut arr { | }
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 | # coding=utf-8
# Copyright (C) 2020 NumS Development Team.
#
# 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... |
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_on(**kwargs)
return self.objective(new_resources)
def objective(self, resources):
# Our simple obje... | 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 | # coding=utf-8
# Copyright (C) 2020 NumS Development Team.
#
# 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... | (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 | # coding=utf-8
# Copyright (C) 2020 NumS Development Team.
#
# 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 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 | # coding=utf-8
# Copyright (C) 2020 NumS Development Team. | #
# 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 | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/cloud/websecurityscanner/v1alpha/scan_run.proto
package websecurityscanner
import (
fmt "fmt"
math "math"
proto "github.com/golang/protobuf/proto"
timestamp "github.com/golang/protobuf/ptypes/timestamp"
_ "google.golang.org/genproto/g... |
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 | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/cloud/websecurityscanner/v1alpha/scan_run.proto
package websecurityscanner
import (
fmt "fmt"
math "math"
proto "github.com/golang/protobuf/proto"
timestamp "github.com/golang/protobuf/ptypes/timestamp"
_ "google.golang.org/genproto/g... |
// 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 | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/cloud/websecurityscanner/v1alpha/scan_run.proto
package websecurityscanner
import (
fmt "fmt"
math "math"
proto "github.com/golang/protobuf/proto"
timestamp "github.com/golang/protobuf/ptypes/timestamp"
_ "google.golang.org/genproto/g... | // 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 | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/cloud/websecurityscanner/v1alpha/scan_run.proto
package websecurityscanner
import (
fmt "fmt"
math "math"
proto "github.com/golang/protobuf/proto"
timestamp "github.com/golang/protobuf/ptypes/timestamp"
_ "google.golang.org/genproto/g... | () 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 | import logging
import os
from operator import mul, truediv
import cv2
import numpy as np
import onnx
import onnxruntime as ort
import torch
from core.isegm.inference import clicker
from skimage.transform import resize as skresize
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
class 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 | import logging
import os
from operator import mul, truediv
import cv2
import numpy as np
import onnx
import onnxruntime as ort
import torch
from core.isegm.inference import clicker
from skimage.transform import resize as skresize
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
class ON... | 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 | import logging
import os
from operator import mul, truediv
import cv2
import numpy as np
import onnx
import onnxruntime as ort
import torch
from core.isegm.inference import clicker
from skimage.transform import resize as skresize
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
class ON... | """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 | import logging
import os
from operator import mul, truediv
import cv2
import numpy as np
import onnx
import onnxruntime as ort
import torch
from core.isegm.inference import clicker
from skimage.transform import resize as skresize
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
class 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 | package table
import (
"errors"
"fmt"
"hilive/context"
"hilive/modules/db"
"hilive/modules/form"
"hilive/modules/paginator"
"hilive/modules/parameter"
"hilive/modules/service"
"hilive/modules/utils"
"hilive/template/types"
"html/template"
"strconv"
"strings"
"sync"
"sync/atomic"
)
var (
services servi... | 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 | package table
import (
"errors"
"fmt"
"hilive/context"
"hilive/modules/db"
"hilive/modules/form"
"hilive/modules/paginator"
"hilive/modules/parameter"
"hilive/modules/service"
"hilive/modules/utils"
"hilive/template/types"
"html/template"
"strconv"
"strings"
"sync"
"sync/atomic"
)
var (
services servi... | identifier_body | ||
table.go | package table
import (
"errors"
"fmt"
"hilive/context"
"hilive/modules/db"
"hilive/modules/form"
"hilive/modules/paginator"
"hilive/modules/parameter"
"hilive/modules/service"
"hilive/modules/utils"
"hilive/template/types"
"html/template"
"strconv"
"strings"
"sync"
"sync/atomic"
)
var (
services servi... | 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 | package table
import (
"errors"
"fmt"
"hilive/context"
"hilive/modules/db"
"hilive/modules/form"
"hilive/modules/paginator"
"hilive/modules/parameter"
"hilive/modules/service"
"hilive/modules/utils"
"hilive/template/types"
"html/template"
"strconv"
"strings"
"sync"
"sync/atomic"
)
var (
services servi... | conditional_block | ||
session.rs | use chrono::{DateTime, Duration, Utc, Timelike, TimeZone};
use clacks_crypto::CSRNG;
use clacks_crypto::symm::AuthKey;
use clacks_mtproto::{AnyBoxedSerialize, BareSerialize, BoxedSerialize, ConstructorNumber, IntoBoxed, mtproto};
use clacks_mtproto::mtproto::wire::outbound_encrypted::OutboundEncrypted;
use clacks_mtpro... | (&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 | use chrono::{DateTime, Duration, Utc, Timelike, TimeZone};
use clacks_crypto::CSRNG;
use clacks_crypto::symm::AuthKey;
use clacks_mtproto::{AnyBoxedSerialize, BareSerialize, BoxedSerialize, ConstructorNumber, IntoBoxed, mtproto};
use clacks_mtproto::mtproto::wire::outbound_encrypted::OutboundEncrypted;
use clacks_mtpro... | Either::Right(m) => self.serialize_encrypted_message(m),
}
}
pub fn bind_auth_key(&mut self, perm_key: AuthKey, expires_in: Duration) -> Result<MessageBuilder<EncryptedPayload>> {
let temp_key = self.fresh_auth_key()?;
let message_id = next_message_id();
let (session... | Either::Left(m) => self.serialize_plain_message(m), | random_line_split |
typechecking.rs | use std::cell::RefCell;
use std::rc::Rc;
use std::collections::HashMap;
use std::fmt;
use std::fmt::Write;
/*
use std::collections::hash_set::Union;
use std::iter::Iterator;
use itertools::Itertools;
*/
use ast;
use util::ScopeStack;
use symbol_table::{SymbolSpec, SymbolTable};
pub type TypeName = Rc<String>;
type Ty... | Binding { name, expr, .. } => {
let ty = self.infer(expr)?;
self.bindings.insert(name.clone(), ty);
},
_ => return Err(format!("other formats not done"))
}
Ok(Void)
}
fn infer(&mut self, expr: &parsing::Expression) -> TypeResult<Type> {
use self::parsing::Expression;
... | use self::parsing::Declaration::*;
use self::Type::*;
match decl { | random_line_split |
typechecking.rs | use std::cell::RefCell;
use std::rc::Rc;
use std::collections::HashMap;
use std::fmt;
use std::fmt::Write;
/*
use std::collections::hash_set::Union;
use std::iter::Iterator;
use itertools::Itertools;
*/
use ast;
use util::ScopeStack;
use symbol_table::{SymbolSpec, SymbolTable};
pub type TypeName = Rc<String>;
type Ty... | 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 | use std::cell::RefCell;
use std::rc::Rc;
use std::collections::HashMap;
use std::fmt;
use std::fmt::Write;
/*
use std::collections::hash_set::Union;
use std::iter::Iterator;
use itertools::Itertools;
*/
use ast;
use util::ScopeStack;
use symbol_table::{SymbolSpec, SymbolTable};
pub type TypeName = Rc<String>;
type Ty... | 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 | # -*- coding: utf-8 -*-
import time
import os
import openpyxl
import pandas as pd
import numpy as np
class Signal():
'''
一个包含了signal的统计信息的类
--------------------------
包含的属性如下
name, volume, profit
需要逐个查看signal对象时,可以使用
>>> s.signal_class_list
'''
def __init__(self, input_name):
... | 返回结果:最大回撤率,开始日期,结束日期,总收益率,年化收益,年化回撤
'''
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 | # -*- coding: utf-8 -*-
import time
import os
import openpyxl
import pandas as pd
import numpy as np
class Signal():
'''
一个包含了signal的统计信息的类
--------------------------
包含的属性如下
name, volume, profit
需要逐个查看signal对象时,可以使用
>>> s.signal_class_list
'''
def __init__(self, input_name):
... | 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 | # -*- coding: utf-8 -*-
import time
import os
import openpyxl
import pandas as pd
import numpy as np
class Signal():
'''
一个包含了signal的统计信息的类
--------------------------
包含的属性如下
name, volume, profit
需要逐个查看signal对象时,可以使用
>>> s.signal_class_list
'''
def __init__(self, input_name):
... | **(1/duration)-1 # 算出年化收益率
return (yearly_rate-risk_free)/ts.std()
def write_sheet1_summation():
current_row = 0
for i in range(len(signal_class_list)):
# 连结profit表和volume表
v = signal_class_list[i].volume
p = signal_class_list[i].profit
w, w... | 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 | # -*- coding: utf-8 -*-
import time
import os
import openpyxl
import pandas as pd
import numpy as np
class Signal():
'''
一个包含了signal的统计信息的类
--------------------------
包含的属性如下
name, volume, profit
需要逐个查看signal对象时,可以使用
>>> s.signal_class_list
'''
def __init__(self, input_name):
... | number
for row in range(1,table.max_row+1):
for j in range(0,table.max_column):
try:
table[row][j].font = font
except:pass
def write_sheet2_daily_profit():
'''插入日收益详情'''
global ans
ans = 每日浮动收益统计(symbol=global_symb... | 数
'''
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 | 'use strict'
import { IncomingMessage } from 'http'
import request from 'request'
import jwt from 'jsonwebtoken'
import createError from 'http-errors'
import { UA } from './ua'
const $setTimeout = setTimeout
const MONGO_REG = /^[0-9a-f]{24}$/i
// Network Errors, exclude 'ETIMEDOUT' and 'ESOCKETTIMEDOUT'
// https://gi... |
/**.
* @returns a Response body or throw a error.
*/
export function assertRes<T> (res: Response): T {
if (isSuccess(res) && typeof res.body !== 'string') {
return res.body as T
}
// 追加额外的信息,方便调试
// 注意,不要把调试信息直接返给客户端
const err = createError(res.statusCode, res.statusMessage, {
originalUrl: res.or... | {
return new Promise((resolve) => $setTimeout(resolve, ms))
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.