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 |
|---|---|---|---|---|
kmp.py | .sum(L,axis=0)))/data.shape[1]) # Average Log likelihood
if iter>=self.em_num_min_steps:
if LL[iter]-LL[iter-1]<self.em_max_diffLL or iter==self.em_num_max_steps-1:
print('EM converged after ',str(iter),' iterations.')
return
print('Max no. of ... |
#######################################################################################################################
class KMP: #Assumptions: Input is only time; All dofs of output are continuous TODO: Generalize
def __init__(self, input_dofs, robot_dofs, demo_dt, ndemos, data_address):
self.input_dof... | L = np.zeros((self.num_states,data.shape[1]))
for i in range(self.num_states):
L[i,:] = self.priors[i]*gaussPDF(data,self.mu[:,i],self.sigma[i,:,:])
L_axis0_sum = np.sum(L,axis=0)
gamma = np.divide(L, np.repeat(L_axis0_sum.reshape(1,L_axis0_sum.shape[0]), self.num_states, axis=0))
... | identifier_body |
kmp.py | _dist = float('Inf')
for i in range(math.ceil(via_pt_ind*phase_size), math.floor((via_pt_ind+1)*phase_size)):
dist = distBWPts(self.ref_traj[i].mu[0:2],via_pt)
# print("dist: ", dist)
if dist<min_dist:
min_dist = dist
# ... | plt.title('KMP generalization over new via points') | random_line_split | |
kmp.py | .sum(L,axis=0)))/data.shape[1]) # Average Log likelihood
if iter>=self.em_num_min_steps:
if LL[iter]-LL[iter-1]<self.em_max_diffLL or iter==self.em_num_max_steps-1:
print('EM converged after ',str(iter),' iterations.')
return
print('Max no. of ... | : #Assumptions: Input is only time; All dofs of output are continuous TODO: Generalize
def __init__(self, input_dofs, robot_dofs, demo_dt, ndemos, data_address):
self.input_dofs = input_dofs
self.robot_dofs = robot_dofs
self.ndemos = ndemos
self.demo_dt = demo_dt
self.norm_d... | KMP | identifier_name |
main_model.py | .append(transforms.ToTensor())
# if args.frozen:
# transforms_list.append(lambda x: x.repeat(3, 1, 1))
# transforms_list.append(transforms.Normalize(mean=[0.485, 0.456, 0.406],
# std=[0.229, 0.224, 0.225]))
# transform = transforms.Compose(transforms_list)
transform = transforms.ToTe... |
prob = self.product/self.sum_
prob[prob < 0] = 0
idx = choice(self.num_levels, p = prob)
self.product[idx] = self.product[idx] - self.weight_vector[idx]
self.sum_ = self.sum_ - self.weight_vector[idx]
idx2 = choice(len(self.samples[idx]))
ret2 = self.samples[idx]... | raise StopIteration | conditional_block |
main_model.py | .append(transforms.ToTensor())
# if args.frozen:
# transforms_list.append(lambda x: x.repeat(3, 1, 1))
# transforms_list.append(transforms.Normalize(mean=[0.485, 0.456, 0.406],
# std=[0.229, 0.224, 0.225]))
# transform = transforms.Compose(transforms_list)
transform = transforms.ToTe... |
def __len__(self):
return len(os.listdir(self.array_dir))*self.num_sketch_levels
def __getitem__(self, sampler):
idx = next(sampler)
sketch_fp = os.path.join(self.sketch_dir, idx[0], idx[1])
fname = os.path.splitext(idx[1])[0]
array_fp = os.path.join(self.array_dir, fn... | self.sketch_dir = sketch_dir
self.array_dir = array_dir
self.num_sketch_levels = len(os.listdir(sketch_dir)) | identifier_body |
main_model.py | .append(transforms.ToTensor())
# if args.frozen:
# transforms_list.append(lambda x: x.repeat(3, 1, 1))
# transforms_list.append(transforms.Normalize(mean=[0.485, 0.456, 0.406],
# std=[0.229, 0.224, 0.225]))
# transform = transforms.Compose(transforms_list)
transform = transforms.ToTe... | (model, dataloader, j = 0):
"""
test model, output different loss for each category
"""
model.float()
model.to(device)
model.eval()
criterion = nn.MSELoss()
val_loss = 0
num_batches = 0
variances = np.array(0)
for i, data in enumerate(dataloader):
num_batches += 1
... | test | identifier_name |
main_model.py | .append(transforms.ToTensor())
# if args.frozen:
# transforms_list.append(lambda x: x.repeat(3, 1, 1))
# transforms_list.append(transforms.Normalize(mean=[0.485, 0.456, 0.406],
# std=[0.229, 0.224, 0.225]))
# transform = transforms.Compose(transforms_list)
transform = transforms.ToTe... | self.fc1 = nn.Linear(128 * 6 * 6, 1028)
# self.fc2 = nn.Linear
def forward(self, x):
x = self.relu(self.conv1(x))
x = self.relu(self.conv2(x))
x = self.relu(self.conv3(x))
x = self.pool1(x)
x = x.view(16 , -1)
x = self.relu(self.fc1(x))
... | random_line_split | |
row.component.ts | // patternStr:'[\u4e00-\u9fa5]+[0-9]*',
patternStr: '[a-zA-Z0-9]+',
patternErr: '表格名称格式不正确,只能为中文名称或中文名称加数字'
}
},
{ | pattern: false,
}
},
{
name: '列表/视图', eName: 'tableName', type: 'text', validateCon: '请输入列表/视图', require: true,
validators: {
require: true,
pattern: false,
}
},
{
name: '列表字段', eName: 'colEname', type: 'text', validateCon: '请输入列表字段', require: true,
... | name: '列名称', eName: 'colCname', type: 'text', validateCon: '请输入列名称', require: true,
validators: {
require: true, | random_line_split |
row.component.ts | patternStr:'[\u4e00-\u9fa5]+[0-9]*',
patternStr: '[a-zA-Z0-9]+',
patternErr: '表格名称格式不正确,只能为中文名称或中文名称加数字'
}
},
{
name: '列名称', eName: 'colCname', type: 'text', validateCon: '请输入列名称', require: true,
validators: {
require: true,
pattern: false,
}
},
{... | xport`;
this.http.post(url, this.searchData, {responseType: 'blob'}).subscribe(
res => {
let blob = new Blob([res], {type: 'application/vnd.ms-excel'});
let objectUrl = URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = objectUrl;
a.target = '_blan... | a.length = data.length || this.pageSize; //最好有
this.searchData = data;
this.listLoading = true;
this.getListSearch(data);
}
btnClick(data: any): void {
switch (data.type.buttonId) {
case 'Export': { //导出
this.btnExport();
}
break;
}
}
/**
* 导出按钮
*/
btnEx... | identifier_body |
row.component.ts | validators: {
require: true,
pattern: false,
}
},
{
name: '列表字段', eName: 'colEname', type: 'text', validateCon: '请输入列表字段', require: true,
validators: {
require: true,
pattern: false,
}
},
{
name: '列是否显示', eName: 'visible', type: 'radio', val... | .data[0]. | identifier_name | |
row.component.ts | // patternStr:'[\u4e00-\u9fa5]+[0-9]*',
patternStr: '[a-zA-Z0-9]+',
patternErr: '表格名称格式不正确,只能为中文名称或中文名称加数字'
}
},
{
name: '列名称', eName: 'colCname', type: 'text', validateCon: '请输入列名称', require: true,
validators: {
require: true,
pattern: false,
}
},
... | ironment.baseUrl}column/selectColumnList`;
params.data = data;
this.httpUtilService.request(params).then(
(res: any) => {
this.listLoading = false;
if (res.success) {
this.dataSet = res.data.data.data;
this.totalPage = res.data.data.total;
}
}
);
}
... | this.listLoading = true;
const params = {url: '', data: {}, method: 'POST'};
params.url = `${env | conditional_block |
ingredients.go | ParseTextIngredients parses a list of ingredients and
// returns an ingredient list back
func ParseTextIngredients(text string) (ingredientList IngredientList, err error) {
r := &Recipe{FileName: "lines"}
r.FileContent = text
lines := strings.Split(text, "\n")
i := 0
goodLines := make([]string, len(lines))
for _... | {
return
} | conditional_block | |
ingredients.go | () {
inflection.AddSingular("(clove)(s)?$", "${1}")
inflection.AddSingular("(potato)(es)?$", "${1}")
inflection.AddSingular("(tomato)(es)?$", "${1}")
inflection.AddUncountable("molasses")
inflection.AddUncountable("bacon")
}
// Recipe contains the info for the file and the lines
type Recipe struct {
FileName ... | init | identifier_name | |
ingredients.go | Recipe{FileName: "lines"}
r.FileContent = text
lines := strings.Split(text, "\n")
i := 0
goodLines := make([]string, len(lines))
for _, line := range lines {
line = strings.TrimSpace(line)
if len(line) == 0 {
continue
}
goodLines[i] = line
i++
}
_, r.Lines = scoreLines(goodLines)
err = r.parseRecip... | if len(arrayMap) == 0 {
err = fmt.Errorf("nothing to parse")
return
}
parseMap(arrayMap[0], &lineInfo) | random_line_split | |
ingredients.go | {
b, err := ioutil.ReadFile(fname)
if err != nil {
return
}
r = new(Recipe)
err = json.Unmarshal(b, r)
return
}
// ParseTextIngredients parses a list of ingredients and
// returns an ingredient list back
func ParseTextIngredients(text string) (ingredientList IngredientList, err error) {
r := &Recipe{FileName... |
// NewFromHTML generates a new parser from a HTML text
func NewFromHTML(name, htmlstring string) (r *Recipe, err error) {
r = &Recipe{FileName: name}
r.FileContent = htmlstring
err = r.parseHTML()
return
}
func IngredientsFromURL(url string) (ingredients []Ingredient, err error) {
r, err := NewFromURL(url)
if ... | {
client := http.Client{
Timeout: 10 * time.Second,
}
resp, err := client.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
html, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
return NewFromHTML(url, string(html))
} | identifier_body |
tidy_toys.py | _width
global image_height
global toys
global frame
# declare golbal variables
global driveLeft, driveRight
global toys_collected
# define variables
Known_Distance = 100 #100cm
Known_Width = 5 #5cm
image_width = 640
image_height = 480
toys = ["blue", "green", "red"]
target_toy = None # allocates a none value
toys_co... | # movement
print("Movement Control")
def grabber(): # grabber control
print("Grabber Control")
# HSV COLOURSPACE START
def find_toy(frame, target_toy):
# convert captured image to HSV colour space to detect colours
toy = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
#cv2.imshow("toy", toy)
#key ... | ving(): | identifier_name |
tidy_toys.py | # Ensure the communications failsafe has been enabled!
failsafe = False
for i in range(5):
TB.SetCommsFailsafe(True)
failsafe = TB.GetCommsFailsafe()
if failsafe:
break
if not failsafe:
print('Board %02X failed to report in failsafe mode!' % (TB.i2cAddress))
def startup():
print("Waiting fo... | nt("steering left")
drive = "steering left"
#Enter motor controls here
#TB.SetMotor1(0.25)
#TB.SetMotor2(0.5)
driveLeft = 0.25
driveRight = 0.50
cv2.putText(frame, drive, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2)
... | conditional_block | |
tidy_toys.py | image_width
global image_height
global toys
global frame
# declare golbal variables
global driveLeft, driveRight
global toys_collected
# define variables
Known_Distance = 100 #100cm
Known_Width = 5 #5cm
image_width = 640
image_height = 480
toys = ["blue", "green", "red"]
target_toy = None # allocates a none value
t... | # DISTANCE (z) BEGIN
# initialise the known distance from the camera to the object which is 300mm 11.81102 inches
KNOWN_DISTANCE = 100
Z = KNOWN_DISTANCE
# initialise the know object width, which is 50mm or 1.968504 inches
KNOWN_WIDTH = 0.5
D = KNOWN_WIDTH
# d = width in pixels at 100cm... | def distance(w, frame):
#global Z
print("distance, z") #Debugging | random_line_split |
tidy_toys.py | AIN_APPROX_SIMPLE)
contour_sizes = [(cv2.contourArea(contours), contours) for contours in contours]
if len(contour_sizes) > 0:
biggest_contour = max(contour_sizes, key=lambda x: x[0])[1]
# draw a green bounding box around the detected object
x, y, w, h = cv2.boundingRect(biggest_conto... | SetMotor1(driveLeft)
TB.SetMotor2(driveRight)
d | identifier_body | |
TkUtil.py | Tkinter with Tkinter.Tk().
Warning: windowingsystem is a fairly recent tk command;
if it is not available then this code does its best to guess
but will not guess aqua.
"""
global g_winSys
if not g_winSys:
tkWdg = _getTkWdg()
try:
g_winSys = tkWdg.tk.call("... | extent_ii = usableScreenExtent_ii | conditional_block | |
TkUtil.py | #def register(self, func):
#"""Register a function as a tcl function.
#Returns the name of the tcl function.
#Be sure to deregister the function when done
#or delete the TkAdapter
#"""
#funcObj = TclFunc(func)
#funcName = funcObj.tclFuncName
#self.func... | screenExtent | identifier_name | |
TkUtil.py | truncRGB = [max(min(int(val), 0xFFFF), 0) for val in netRGB]
retColor = "#%04x%04x%04x" % tuple(truncRGB)
#print "mixColors(%r); netRGB=%s; truncRGB=%s; retColor=%r" % (colorMultPairs, netRGB, truncRGB, retColor)
return retColor
def colorOK(colorStr):
"""Return True if colorStr is a valid tk color, Fa... |
class Geometry(object):
"""A class representing a tk geometry
Fields include the following two-element tuples:
- offset: x,y offset of window relative to screen; see also offsetFlipped
- offsetFlipped: is the meaning of x,y offset flipped?
if False (unflipped) then offset is the distance ... | return self.tclFuncName | identifier_body |
TkUtil.py |
# windowing system constants
WSysAqua = "aqua"
WSysX11 = "x11"
WSysWin = "win32"
# internal globals
g_tkWdg = None
g_winSys = None
g_tkVersion = None
def addColors(*colorMultPairs):
"""Add colors or scale a color.
Inputs:
- A list of one or more (color, mult) pairs.
Returns sum of (R, G, B)... | import tkinter
import RO.OS | random_line_split | |
cleaner.go | detail_new_|" +
"detail_related_|" +
"figcaption|" +
"footnote|" +
"foot|" +
"header|" +
"img_popup_single|" +
"js_replies|" +
"[Kk]ona[Ff]ilter|" +
"leading|" +
"legende|" +
"links|" +
"mediaarticlerelated|" +
"menucontainer|" +
"meta$|" +
"navbar|" +
"pagetools|" +
"popup|" +
"post-attributes|" +
"... |
func (this *cleaner) cleanEMTags(doc *goquery.Document) *goquery.Document {
ems := doc.Find("em")
ems.Each(func(i int, s *goquery.Selection) {
images := s.Find("img")
if images.Length() == 0 {
this.config.parser.dropTag(s)
}
})
if this.config.debug {
log.Printf("Cleaning %d EM tags\n", ems.Size())
}
... | {
tags := [3]string{"id", "name", "class"}
articles := doc.Find("article")
articles.Each(func(i int, s *goquery.Selection) {
for _, tag := range tags {
this.config.parser.delAttr(s, tag)
}
})
return doc
} | identifier_body |
cleaner.go | detail_new_|" +
"detail_related_|" +
"figcaption|" +
"footnote|" +
"foot|" +
"header|" +
"img_popup_single|" +
"js_replies|" +
"[Kk]ona[Ff]ilter|" +
"leading|" +
"legende|" +
"links|" +
"mediaarticlerelated|" +
"menucontainer|" +
"meta$|" +
"navbar|" +
"pagetools|" +
"popup|" +
"post-attributes|" +
"... | (doc *goquery.Document) *goquery.Document {
spans := doc.Find("span")
spans.Each(func(i int, s *goquery.Selection) {
parent := s.Parent()
if parent != nil && parent.Length() > 0 && parent.Get(0).DataAtom == atom.P {
node := s.Get(0)
node.Data = s.Text()
node.Type = html.TextNode
}
})
return doc
}
fu... | cleanParaSpans | identifier_name |
cleaner.go | k]ona[Ff]ilter|" +
"leading|" +
"legende|" +
"links|" +
"mediaarticlerelated|" +
"menucontainer|" +
"meta$|" +
"navbar|" +
"pagetools|" +
"popup|" +
"post-attributes|" +
"post-title|" +
"relacionado|" +
"retweet|" +
"runaroundLeft|" +
"shoutbox|" +
"site_nav|" +
"socialNetworking|" +
"social_|" +
"so... |
for _, o := range output {
o.NextSibling = nil
} | random_line_split | |
cleaner.go | detail_new_|" +
"detail_related_|" +
"figcaption|" +
"footnote|" +
"foot|" +
"header|" +
"img_popup_single|" +
"js_replies|" +
"[Kk]ona[Ff]ilter|" +
"leading|" +
"legende|" +
"links|" +
"mediaarticlerelated|" +
"menucontainer|" +
"meta$|" +
"navbar|" +
"pagetools|" +
"popup|" +
"post-attributes|" +
"... |
})
}
return doc
}
func (this *cleaner) cleanParaSpans(doc *goquery.Document) *goquery.Document {
spans := doc.Find("span")
spans.Each(func(i int, s *goquery.Selection) {
parent := s.Parent()
if parent != nil && parent.Length() > 0 && parent.Get(0).DataAtom == atom.P {
node := s.Get(0)
node.Data = s.Te... | {
log.Printf("%d naughty %s elements found", cont, selector)
} | conditional_block |
新的分钟数据整合.py | _range_path)['date'].values.tolist()
rar.extractall(path=file_name.split('.')[0])
# 首先需要输入end_date 确保截取的时间长度和main主力合约的时间对齐
# 按照月份确定位置
pro = ts.pro_api('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6')
ts.set_token('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6')
date_df=pro... | #分割到的长度放入容器中
target_num=len(target_df)
#理论长度
theory_num=len(time_0931_15)
#实际上两种情况:1.是交易日但完全没有数据2.是交易日,只有部分数据 3.是交易日,数据也是完整的
if target_num>0:
#开始区分2,3情况
have_time=target_df['time'].values.tolist()
lac... | # 设置了存放按月填充的路径
for date_index in range(len(target_date)):
#按日期进行分割
target_df=final_df.loc[final_df['date2']==target_date[date_index]] | random_line_split |
新的分钟数据整合.py | _path)['date'].values.tolist()
rar.extractall(path=file_name.split('.')[0])
# 首先需要输入end_date 确保截取的时间长度和main主力合约的时间对齐
# 按照月份确定位置
pro = ts.pro_api('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6')
ts.set_token('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6')
date_df=pro.trade... | for row_index in range(len(result)):
target_row=result.iloc[row_index].tolist()
clean_row=target_row[:-2]
orignal_data.append(clean_row)
print(f'{contract_kind} {date} finished!')
else:
print(f'没找到合约品种{contract_kind}在{date}')
print(f'{c... | if result.shape[0]>0:
| conditional_block |
新的分钟数据整合.py | path:str,rar_data_file_path:str,clean_data_path:str,time_range_path:str,end_date:str,commodity_bool=True):
'''
用于更新月度的商品期货数据
year_month:'201911'字符串年份和月份,对应的是FutAC_Min1_Std_后面的数字,如FutAC_Min1_Std_201911
contract_kind:放对应品种的list 类似['A','B']
main_code_path:对应存放主力合约的地方
rar_data_file_path: 对应的是存放rar数据... | ct_kind:str,main_code_ | identifier_name | |
新的分钟数据整合.py | data=np.load(specifi_path)
time_0931_15=pd.read_csv(time_range_path)['date'].values.tolist()
rar.extractall(path=file_name.split('.')[0])
# 首先需要输入end_date 确保截取的时间长度和main主力合约的时间对齐
# 按照月份确定位置
pro = ts.pro_api('3d832df2966f27c20e6ff243ab1d53a35a4adc1c64b353cc370ac7d6')
ts.set_token('3d832df296... | '字符串年份和月份,对应的是FutAC_Min1_Std_后面的数字,如FutAC_Min1_Std_201911
contract_kind:放对应品种的list 类似['A','B']
main_code_path:对应存放主力合约的地方
rar_data_file_path: 对应的是存放rar数据如FutAC_Min1_Std_201911.rar的位置,不包括对应的文件名
clean_data_path:对应存放分钟数据的位置,处理好的新数据会追加到对应位置下的对应品种处
time_range_path:放置交易时间文件的路径,包括文件名 如 D:/统一所有品种时间范围.csv
... | identifier_body | |
conf.go | "time"
)
type urlHolder struct {
scheme string
host string
port int
}
type config struct {
securityProviders []securityProvider
urlHolder *urlHolder
pathStyle bool
cname bool
sslVerify bool
endpoint string
signature SignatureType
region s... | "strconv"
"strings" | random_line_split | |
conf.go | d]",
conf.endpoint, conf.signature, conf.pathStyle, conf.region,
conf.connectTimeout, conf.socketTimeout, conf.headerTimeout, conf.idleConnTimeout,
conf.maxRetryCount, conf.maxConnsPerHost, conf.sslVerify, conf.maxRedirectCount,
)
}
type configurer func(conf *config)
func WithSecurityProviders(sps ...securityP... | (headerTimeout int) configurer {
return func(conf *config) {
conf.headerTimeout = headerTimeout
}
}
// WithProxyUrl is a configurer for ObsClient to set HTTP proxy.
func WithProxyUrl(proxyURL string) configurer {
return func(conf *config) {
conf.proxyURL = proxyURL
}
}
// WithMaxConnections is a configurer fo... | WithHeaderTimeout | identifier_name |
conf.go | ]",
conf.endpoint, conf.signature, conf.pathStyle, conf.region,
conf.connectTimeout, conf.socketTimeout, conf.headerTimeout, conf.idleConnTimeout,
conf.maxRetryCount, conf.maxConnsPerHost, conf.sslVerify, conf.maxRedirectCount,
)
}
type configurer func(conf *config)
func WithSecurityProviders(sps ...securityPr... |
func (conf *config) prepareConfig() {
if conf.connectTimeout <= 0 {
conf.connectTimeout = DEFAULT_CONNECT_TIMEOUT
}
if conf.socketTimeout <= 0 {
conf.socketTimeout = DEFAULT_SOCKET_TIMEOUT
}
conf.finalTimeout = conf.socketTimeout * 10
if conf.headerTimeout <= 0 {
conf.headerTimeout = DEFAULT_HEADER_TIM... | {
return func(conf *config) {
conf.enableCompression = enableCompression
}
} | identifier_body |
conf.go | ]",
conf.endpoint, conf.signature, conf.pathStyle, conf.region,
conf.connectTimeout, conf.socketTimeout, conf.headerTimeout, conf.idleConnTimeout,
conf.maxRetryCount, conf.maxConnsPerHost, conf.sslVerify, conf.maxRedirectCount,
)
}
type configurer func(conf *config)
func WithSecurityProviders(sps ...securityPr... |
conf.transport.Proxy = http.ProxyURL(proxyURL)
}
tlsConfig := &tls.Config{InsecureSkipVerify: !conf.sslVerify}
if conf.sslVerify && conf.pemCerts != nil {
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(conf.pemCerts)
tlsConfig.RootCAs = pool
}
conf.transport.TLSClientConfig = tlsConfig
co... | {
return err
} | conditional_block |
PROGRAM.py | (mode,text):
keyboard=text
if keyboard=='': return
if mode==1:
try:
window_id = xbmcgui.getCurrentWindowDialogId()
window = xbmcgui.Window(window_id)
keyboard = mixARABIC(keyboard)
window.getControl(311).setLabel(keyboard)
except: pass
elif mode==0:
ttype='X'
check=isinstance(keyboard, unicode)
... | FIX_KEYBOARD | identifier_name | |
PROGRAM.py | اذن أقرأ قسم المشاكل والحلول واذا لم تجد الحل هناك فاذن اكتب رسالة عن المكان والوقت والحال الذي تحدث فيه المشكلة واكتب جميع التفاصيل لان المبرمج لا يعلم الغيب')
xbmcgui.Dialog().ok('عنوان الايميل','اذا كنت تريد ان تسأل وتحتاج جواب من المبرمج فاذن يجب عليك اضافة عنوان البريد الالكتروني email الخاص بك الى رسالتك لانها ا... | "}'
# #auth=("api", "my personal api key"),
# #response = requests.request('POST',url, data=payload, headers='', auth='')
# response = requests.post(url, data=payload, headers='', auth='')
# if response.status_code == 200:
# xbmcgui.Dialog().ok('تم الارسال بنجاح','')
# else:
# xbmcgui.Dialog().ok('خطأ في الارس... | sage+' | conditional_block |
PROGRAM.py | اذن أقرأ قسم المشاكل والحلول واذا لم تجد الحل هناك فاذن اكتب رسالة عن المكان والوقت والحال الذي تحدث فيه المشكلة واكتب جميع التفاصيل لان المبرمج لا يعلم الغيب')
xbmcgui.Dialog().ok('عنوان الايميل','اذا كنت تريد ان تسأل وتحتاج جواب من المبرمج فاذن يجب عليك اضافة عنوان البريد الالكتروني email الخاص بك الى رسالتك لانها ا... | ب','',99,'','',search)
addDir('[COLOR FFC89008]=========================[/COLOR]','',9999)
addDir('13. [COLOR FFC89008]SHA [/COLOR]'+search+' - موقع شاهد فوريو','',119,'','',search)
addDir('14. [COLOR FFC89008]HLA [/COLOR]'+search+' - موقع هلا سيما','',89,'','',search)
xbmcplugin.endOfDirectory(addon_handle)
r... | identifier_body | |
PROGRAM.py | فر) يعمل على جهازك ... وجهازك قادر على استخدام المواقع المشفرة')
else:
xbmcgui.Dialog().ok('الاتصال المشفر','مشكلة ... الاتصال المشفر (الربط المشفر) لا يعمل على جهازك ... وجهازك غير قادر على استخدام المواقع المشفرة')
from PROBLEMS import MAIN as PROBLEMS_MAIN
PROBLEMS_MAIN(152)
return
def SERVERS_TYPE():
text... | random_line_split | ||
api_op_ListSMSSandboxPhoneNumbers.go | .com/sns/latest/dg/sns-sms-sandbox.html)
// in the Amazon SNS Developer Guide.
func (c *Client) ListSMSSandboxPhoneNumbers(ctx context.Context, params *ListSMSSandboxPhoneNumbersInput, optFns ...func(*Options)) (*ListSMSSandboxPhoneNumbersOutput, error) {
if params == nil {
params = &ListSMSSandboxPhoneNumbersInput{... |
func (m *opListSMSSandboxPhoneNumbersResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
return next.HandleS... | {
return "ResolveEndpointV2"
} | identifier_body |
api_op_ListSMSSandboxPhoneNumbers.go | .com/sns/latest/dg/sns-sms-sandbox.html)
// in the Amazon SNS Developer Guide.
func (c *Client) ListSMSSandboxPhoneNumbers(ctx context.Context, params *ListSMSSandboxPhoneNumbersInput, optFns ...func(*Options)) (*ListSMSSandboxPhoneNumbersOutput, error) {
if params == nil {
params = &ListSMSSandboxPhoneNumbersInput{... |
return nil
}
// ListSMSSandboxPhoneNumbersAPIClient is a client that implements the
// ListSMSSandboxPhoneNumbers operation.
type ListSMSSandboxPhoneNumbersAPIClient interface {
ListSMSSandboxPhoneNumbers(context.Context, *ListSMSSandboxPhoneNumbersInput, ...func(*Options)) (*ListSMSSandboxPhoneNumbersOutput, error... | {
return err
} | conditional_block |
api_op_ListSMSSandboxPhoneNumbers.go | .amazon.com/sns/latest/dg/sns-sms-sandbox.html)
// in the Amazon SNS Developer Guide.
func (c *Client) ListSMSSandboxPhoneNumbers(ctx context.Context, params *ListSMSSandboxPhoneNumbersInput, optFns ...func(*Options)) (*ListSMSSandboxPhoneNumbersOutput, error) {
if params == nil {
params = &ListSMSSandboxPhoneNumber... |
// A list of the calling account's pending and verified phone numbers.
//
// This member is required.
PhoneNumbers []types.SMSSandboxPhoneNumber
// A NextToken string is returned when you call the ListSMSSandboxPhoneNumbersInput
// operation if additional pages of records are available.
NextToken *string
// ... |
noSmithyDocumentSerde
}
type ListSMSSandboxPhoneNumbersOutput struct { | random_line_split |
api_op_ListSMSSandboxPhoneNumbers.go | .amazon.com/sns/latest/dg/sns-sms-sandbox.html)
// in the Amazon SNS Developer Guide.
func (c *Client) ListSMSSandboxPhoneNumbers(ctx context.Context, params *ListSMSSandboxPhoneNumbersInput, optFns ...func(*Options)) (*ListSMSSandboxPhoneNumbersOutput, error) {
if params == nil {
params = &ListSMSSandboxPhoneNumber... | () bool {
return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0)
}
// NextPage retrieves the next ListSMSSandboxPhoneNumbers page.
func (p *ListSMSSandboxPhoneNumbersPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListSMSSandboxPhoneNumbersOutput, error) {
if !p.HasMorePages() {
... | HasMorePages | identifier_name |
app.js | é uma linha do arquivo
var fileArr = e.target.result.split('\n');
// Monta a div que irá exibir os dados
var cnpj = fileArr[2].slice(3, 17);
var div = '<p><strong>CNPJ:</strong> ' + formataCnpj(cnpj) + '</p>';
div += '<p><strong>Transportadora:</strong> ' + fileArr[2].slice(17, 57) + '</p>';
... | '</tr>';
};
div += '</table>';
// Seta a div montada com os dados
areaUpload.classList.add('hidden');
btnNewReader.classList.remove('hidden');
// Exibe os dados
exibeArquivo.innerHTML = div;
};
btnNewReader.addEventListener('click', function() {
areaUpload.classList.remove('hid... | Verifica se o registro é de uma ocorrência
if (fileLine[j].slice(0, 3) == '342') {
var ocorrencia = dadosOcorrencia(fileLine[j].slice(28, 30));
div += '<td>' + ocorrencia.cod + '</td>';
div += '<td>' + ocorrencia.descricao + '</td>';
}
};... | conditional_block |
app.js | // Passa os dados do arquivo para um aray onde cada índice é uma linha do arquivo
var fileArr = e.target.result.split('\n');
// Monta a div que irá exibir os dados
var cnpj = fileArr[2].slice(3, 17);
var div = '<p><strong>CNPJ:</strong> ' + formataCnpj(cnpj) + '</p>';
div += '<p><strong>Transport... | o(e) {
| identifier_name | |
app.js | índice é uma linha do arquivo
var fileArr = e.target.result.split('\n');
// Monta a div que irá exibir os dados
var cnpj = fileArr[2].slice(3, 17);
var div = '<p><strong>CNPJ:</strong> ' + formataCnpj(cnpj) + '</p>';
div += '<p><strong>Transportadora:</strong> ' + fileArr[2].slice(17, 57) + '</p>... | };
btnNewReader.addEventListener('click', function() {
areaUpload.classList.remove('hidden');
btnNewReader.classList.add('hidden');
exibeArquivo.innerHTML = '';
});
var formataCnpj = function(cnpj) {
return cnpj.slice(0, 2) + '.' +
cnpj.slice(2, 5) + '.' +
cnpj.slice(5, 8) + '/' +
... | random_line_split | |
app.js | é uma linha do arquivo
var fileArr = e.target.result.split('\n');
// Monta a div que irá exibir os dados
var cnpj = fileArr[2].slice(3, 17);
var div = '<p><strong>CNPJ:</strong> ' + formataCnpj(cnpj) + '</p>';
div += '<p><strong>Transportadora:</strong> ' + fileArr[2].slice(17, 57) + '</p>';
... | {cod: '19', descricao: "Reentrega Solicitada pelo Cliente"},
{cod: '20', descricao: "Entrega Prejudicada por Horário/Falta de Tempo Hábil"},
{cod: '21', descricao: "Estabelecimento Fechado"},
{cod: '22', descricao: "Reentrega sem Cobrança do Cliente"},
{cod: '23', descricao: "Ext... | rrencias = [
{cod: '00', descricao: "Processo de Transporte já Iniciado"},
{cod: '01', descricao: "Entrega Realizada Normalmente"},
{cod: '02', descricao: "Entrega Fora da Data Programada"},
{cod: '03', descricao: "Recusa por Falta de Pedido de Compra"},
{cod: '04', descricao: "... | identifier_body |
mc.py | ):
self.pool.add(canonical((i, j)))
for piece in self.my_pieces:
self.pool.remove(canonical(piece))
def feed(self):
# Save
if self.history_pointer == 0:
self.my_init()
# Game simulation
# team = self.position % 2
while self.h... | for i in range(4):
# Player `i` don't have any remaining piece
if (mask >> (7 * i)) & ((1 << 7) - 1) == 0:
winner_team = i & 1
break
hand = 0
for j in range(7):
if (mask >> (i * 7 + j)) & 1:
hand += sum(distribution[i][j])
... | light_player = set()
| random_line_split |
mc.py | ):
self.pool.add(canonical((i, j)))
for piece in self.my_pieces:
self.pool.remove(canonical(piece))
def feed(self):
# Save
if self.history_pointer == 0:
self.my_init()
# Game simulation
# team = self.position % 2
while self.h... |
assert len(order) == 0
return pieces
def choice(self):
self.feed()
NUM_SAMPLING = 10
NUM_EXPANDED = 2000
scores = {} # Score of each move (piece, head)
winpredictions = {}
for _ in range(NUM_SAMPLING):
distribution = self.sample()
... | if pos == self.position:
pieces[pos] = deepcopy(self.pieces)
else:
r = self.remaining[pos]
pieces[pos] = order[:r]
order = order[r:]
assert len(pieces[pos]) == r | conditional_block |
mc.py | ):
self.pool.add(canonical((i, j)))
for piece in self.my_pieces:
self.pool.remove(canonical(piece))
def feed(self):
# Save
if self.history_pointer == 0:
self.my_init()
# Game simulation
# team = self.position % 2
while self.h... | (self):
self.feed()
NUM_SAMPLING = 10
NUM_EXPANDED = 2000
scores = {} # Score of each move (piece, head)
winpredictions = {}
for _ in range(NUM_SAMPLING):
distribution = self.sample()
cscores, cwinpredictions = montecarlo(distribution, tuple(se... | choice | identifier_name |
mc.py | ):
self.pool.add(canonical((i, j)))
for piece in self.my_pieces:
self.pool.remove(canonical(piece))
def feed(self):
# Save
if self.history_pointer == 0:
self.my_init()
# Game simulation
# team = self.position % 2
while self.h... | heads = tuple(heads)
pos = position
start = (mask, heads, pos)
# Initialize states for MonteCarlo Tree Search
state_map = {start: Node(start)}
# Run MonteCarlo
iterations = 0
logger.debug(f"Start montecarlo from: {bin(mask)} | {heads} | {pos}")
while True:
iterations += ... | """
state: (bitmask, heads, pos)
bitmask: 7 bits each player 2**28 states that denotes which pieces are still holding relative to `distribution`
parent visit count: PC
visit count: VC
win count: WC
exploration control: K
WC / VC +... | identifier_body |
csn.py | _id_node_counter = 1
_or_nodes = 0
_leaf_nodes = 0
_or_edges = 0
_clt_edges = 0
_cltrees = 0
_depth = 0
_mean_depth = 0
@classmethod
def init_stats(cls):
Csn._id_node_counter = 1
Csn._or_nodes = 0
Csn._leaf_nodes = 0
Csn._or_edges = 0
Csn._cl... | if clt is None:
COC = [[] for i in range(data.shape[0])]
for r in range(data.shape[0]):
for f in range(data.shape[1]):
if data[r,f]>0:
COC[r].append(f)
self.node.cltree = Cltree()
self.node... | self.min_instances = min_instances
self.min_features = min_features
self.alpha = alpha
self.depth = depth
self.data = data
self.node = TreeNode()
self.multilabel = multilabel
self.n_labels = n_labels
self.ml_tree_structure = ml_tree_structure
self.... | identifier_body |
csn.py | ll = 0.0, min_instances = 5, min_features = 3,
alpha = 1.0, n_original_samples = None,
leaf_vars = [], depth = 1,
multilabel = False, n_labels=0, ml_tree_structure=0, xcnet=False):
self.min_instances = min_instances
self.min_features = min_f... | random_line_split | ||
csn.py | _id_node_counter = 1
_or_nodes = 0
_leaf_nodes = 0
_or_edges = 0
_clt_edges = 0
_cltrees = 0
_depth = 0
_mean_depth = 0
@classmethod
def init_stats(cls):
Csn._id_node_counter = 1
Csn._or_nodes = 0
Csn._leaf_nodes = 0
Csn._or_edges = 0
Csn._cl... | (self, X):
Prob = X[:,0]*0.0
for i in range(X.shape[0]):
Prob[i] = np.exp(self.score_sample_log_proba(X[i]))
return Prob
def or_cut(self):
print(" > trying to cut ... ")
sys.stdout.flush()
found = False
bestlik = self.orig_ll
be... | score_samples_proba | identifier_name |
csn.py | _id_node_counter = 1
_or_nodes = 0
_leaf_nodes = 0
_or_edges = 0
_clt_edges = 0
_cltrees = 0
_depth = 0
_mean_depth = 0
@classmethod
def init_stats(cls):
Csn._id_node_counter = 1
Csn._or_nodes = 0
Csn._leaf_nodes = 0
Csn._or_edges = 0
Csn._cl... |
self.node.cltree = Cltree()
self.node.cltree.fit(data, alpha=self.alpha,
multilabel = self.multilabel, n_labels=self.n_labels, ml_tree_structure=self.ml_tree_structure)
self.orig_ll = self.node.cltree.score_samples_log_proba(self.dat... | for f in range(data.shape[1]):
if data[r,f]>0:
COC[r].append(f) | conditional_block |
network.rs | Mojang, MojangHasJoinedResponse};
use crate::packets::*;
use crate::player::Player;
use openssl::pkey::Private;
use openssl::rsa::{Padding, Rsa};
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::sync::mpsc;
use std::threa... | loop {
/*let now = SystemTime::now();
let time_since = now.duration_since(last_tick_time).unwrap().as_millis();
if time_since > 50 {
last_tick_time = now;
}
*/
self | random_line_split | |
network.rs | Mojang, MojangHasJoinedResponse};
use crate::packets::*;
use crate::player::Player;
use openssl::pkey::Private;
use openssl::rsa::{Padding, Rsa};
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::sync::mpsc;
use std::threa... |
fn start(mut self) {
println!("Listening for connections...");
//let mut last_tick_time = SystemTime::now();
loop {
/*let now = SystemTime::now();
let time_since = now.duration_since(last_tick_time).unwrap().as_millis();
if time_since > 50 {
... | { // TODO: Clean up maybe
let mut finished_indicies = Vec::new();
for (i, pending) in self.mojang.has_joined_pending.iter().enumerate() {
if pending.result.is_some() {
finished_indicies.push(i);
}
}
for index in finished_indicies {
let ... | identifier_body |
network.rs | Mojang, MojangHasJoinedResponse};
use crate::packets::*;
use crate::player::Player;
use openssl::pkey::Private;
use openssl::rsa::{Padding, Rsa};
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::sync::mpsc;
use std::threa... | (&mut self) {
let num_clients = self.clients.len();
for client in 0..num_clients {
let mut packets = self.clients[client]
.connection
.receive_packets();
for packet_batch in packets.drain(..) {
for packet in PacketDecoder::new_batch... | receive_packets | identifier_name |
network.rs | Mojang, MojangHasJoinedResponse};
use crate::packets::*;
use crate::player::Player;
use openssl::pkey::Private;
use openssl::rsa::{Padding, Rsa};
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::sync::mpsc;
use std::threa... |
}
fn poll_mojang(&mut self) { // TODO: Clean up maybe
let mut finished_indicies = Vec::new();
for (i, pending) in self.mojang.has_joined_pending.iter().enumerate() {
if pending.result.is_some() {
finished_indicies.push(i);
}
}
for index i... | {
self.clients.push(client);
} | conditional_block |
tautils.py | , ta_file):
""" Write data to a file. """
file_handle = file(ta_file, "w")
file_handle.write(data_to_string(data))
file_handle.close()
def data_to_string(data):
""" JSON dump a string. """
return json_dump(data).replace(']], ', ']],\n')
def do_dialog(dialog, suffix, load_save_folder):
""... | (top):
""" When we undock, retract the 'arm' that extends from 'sandwichtop'. """
if top is not None and top.name in ['sandwichtop', 'sandwichtop_no_label']:
if top.ey > 0:
top.reset_y()
def grow_stack_arm(top):
""" When we dock, grow an 'arm' from 'sandwichtop'. """
if top is not ... | reset_stack_arm | identifier_name |
tautils.py |
def data_from_string(text):
""" JSON load data from a string. """
return json_load(text.replace(']],\n', ']], '))
def data_to_file(data, ta_file):
""" Write data to a file. """
file_handle = file(ta_file, "w")
file_handle.write(data_to_string(data))
file_handle.close()
def data_to_string(... | """ Open the .ta file, ignoring any .png file that might be present. """
file_handle = open(ta_file, "r")
#
# We try to maintain read-compatibility with all versions of Turtle Art.
# Try pickle first; then different versions of json.
#
try:
_data = pickle.load(file_handle)
except:
... | identifier_body | |
tautils.py | (data, ta_file):
""" Write data to a file. """
file_handle = file(ta_file, "w")
file_handle.write(data_to_string(data))
file_handle.close()
def data_to_string(data):
""" JSON dump a string. """
return json_dump(data).replace(']], ', ']],\n')
def do_dialog(dialog, suffix, load_save_folder):
... | while _blk is not None:
if _blk.name in COLLAPSIBLE:
return None
if _blk.name in ['repeat', 'if', 'ifelse', 'forever', 'while']:
if blk != _blk.connections[len(_blk.connections) - 1]:
return None
if _blk.name in ['sandwichtop', 'sandwichtop_no_label',
... | def find_sandwich_top(blk):
""" Find the sandwich top above this block. """
# Always follow the main branch of a flow: the first connection.
_blk = blk.connections[0] | random_line_split |
tautils.py | .spr.get_xy()
_yd = _you.docks[len(_you.docks) - 1]
(_bx, _by) = _blk.spr.get_xy()
_dx = _yx + _yd[2] - _blk.docks[0][2] - _bx
_dy = _yy + _yd[3] - _blk.docks[0][3] - _by
_blk.spr.move_relative((_dx, _dy))
# Since the shapes have changed, the dock ... | if not numeric_arg(blk2.connections[2].values[0]):
return False | conditional_block | |
color.rs | /// Return the green value.
pub fn green(&self) -> f32 {
let Rgba(_, g, _, _) = self.to_rgb();
g
}
/// Return the blue value.
pub fn blue(&self) -> f32 {
let Rgba(_, _, b, _) = self.to_rgb();
b
}
/// Set the red value.
pub fn set_red(&mut self, r: f32) {
... | /// Chocolate - Light - #E9B96E | random_line_split | |
color.rs | _rgb(hue: f32, saturation: f32, lightness: f32) -> (f32, f32, f32) {
let chroma = (1.0 - (2.0 * lightness - 1.0).abs()) * saturation;
let hue = hue / degrees(60.0);
let x = chroma * (1.0 - (fmod(hue, 2) - 1.0).abs());
let (r, g, b) = match hue {
hue if hue < 0.0 => (0.0, 0.0, 0.0),
hue i... | hsla | identifier_name | |
color.rs | , 1.0-p, 1.0)
}
/// Construct a random color.
pub fn random() -> Color {
rgb(::rand::random(), ::rand::random(), ::rand::random())
}
/// Clamp a f32 between 0f32 and 1f32.
fn clampf32(f: f32) -> f32 {
if f < 0.0 { 0.0 } else if f > 1.0 { 1.0 } else { f }
}
impl Color {
/// Produce a complementary col... |
else {
(clampf32((1.0 - r) * 0.75 + r),
clampf32((1.0 - g) * 0.25 + g),
clampf32((1.0 - b) * 0.25 + b))
}
};
let a = clampf32((1.0 - a) * 0.75 + a);
rgba(r, g, b, a)
}
/// Return the Color's invert.
pub fn in... | { (r + 0.4, g + 0.2, b + 0.2) } | conditional_block |
color.rs | , 1.0-p, 1.0)
}
/// Construct a random color.
pub fn random() -> Color {
rgb(::rand::random(), ::rand::random(), ::rand::random())
}
/// Clamp a f32 between 0f32 and 1f32.
fn clampf32(f: f32) -> f32 {
if f < 0.0 { 0.0 } else if f > 1.0 { 1.0 } else { f }
}
impl Color {
/// Produce a complementary col... |
/// Return either black or white, depending which contrasts the Color the most. This will be
/// useful for determining a readable color for text on any given background Color.
pub fn plain_contrast(self) -> Color {
if self.luminance() > 0.5 { black() } else { white() }
}
/// Extract the ... | {
match *self {
Color::Rgba(r, g, b, _) => (r + g + b) / 3.0,
Color::Hsla(_, _, l, _) => l,
}
} | identifier_body |
lib.rs | //! either specific types or type constraints.
//! - Functions are first-class types. Functions can have type and/or const params.
//! Const params always specify tuple length.
//! - Type params can be constrained. Constraints are expressed via [`Constraint`]s.
//! As an example, [`Num`] has a few known constrain... | ConstraintSet::default()
}
}
// | identifier_body | |
lib.rs | that all type / length variables not resolved at the function definition site become
//! parameters of the function. Likewise, each function call instantiates a separate instance
//! of a generic function; type / length params for each call are assigned independently.
//! See the example below for more details.
//!
//... | type(input | identifier_name | |
lib.rs | arith::Num
//! [`Linearity`]: crate::arith::Linearity
//!
//! # Inference rules
//!
//! Inference mostly corresponds to [Hindley–Milner typing rules]. It does not require
//! type annotations, but utilizes them if present. Type unification (encapsulated in
//! [`Substitutions`]) is performed at each variable use or ass... | /// let code = "x: [Num] = (1, 2, 3);";
/// let ast = Annotated::<F32Grammar>::parse_statements(code)?; | random_line_split | |
NJ.py |
else:
my_species = self.mrca
self.graph.add_node(newNode, species=my_species)
# replace first merged leave by newNode then shift everything after the 2nd merged leave
self.graph.add_edge(unadded_nodes[minp[0]], newNode, homology_dist=mp0_mp_dist, synteny_dist=syn0_mp_dist)
self.graph.add_edge(unadde... | my_species = self.graph.node[unadded_nodes[minp[0]]]['species'] | conditional_block | |
NJ.py | ] * (minp[1] - 1) / 2) + k]
hom_matrix[pos] = 0.5 * (dfk_hom + dgk_hom - dfg_hom)
syn_matrix[pos] = 0.5 * (dfk_syn + dgk_syn - dfg_syn)
elif k == minp[0]:
dfk_hom = hom_matrix[pos]
dgk_hom = hom_matrix[pos + minp[1] - minp[0]]
dfk_syn = syn_matrix[pos]
dgk_syn = syn_matrix[pos + minp[1... | (self):
if self.rootedTree:
processed = ['root']
current_leaves = list(self.rootedTree['root'])
# nwk = "(" + ",".join(current_leaves) + ");"
# nwk = ",".join(current_leaves)
nwk = "(" + current_leaves[0] + ":" + str(self.rootedTree['root'][current_leaves[0]]['homology_dist']) + ',' + current_leaves[1]... | getNewick | identifier_name |
NJ.py | - 1):
# raw_len += self.graph[raw_path[i]][raw_path[i + 1]]['homology_dist']
# # subract half of root edge length from raw_dist to get the distance from the root (edge mid-point) to this node, n
# edge_length = self.graph[e[0]][e[1]][attr]
# mid_edge = edge_length / 2.0
# dist = raw_len + mid_edge
# retur... | new_trees = []
new_root_edges = []
futur_roots = [root[1][0], root[1][1]]
self.graph.remove_edge(root[1][0], root[1][1])
new_graphs = nx.connected_component_subgraphs(self.graph)
for n in new_graphs:
for futur_root in futur_roots: # loop here, but next if selects only 1 iteration
if futur_root in n.no... | identifier_body | |
NJ.py | _gain_poisson = 0.0
my_gain_poisson = poisson.pmf((gain), self.gain)
if my_gain_poisson > 0:
my_poisson += math.log10(my_gain_poisson)
# my_loss_poisson = 0.0
my_loss_poisson = poisson.pmf((loss), self.loss)
if my_loss_poisson > 0:
my_poisson += math.log10(my_loss_poisson)
gl_factor = self.gamma * my_... | random_line_split | ||
main.rs | ::activation::softmax_with_loss::SoftmaxWithLoss;
use selecting_flow::compute_graph::fully_connected_layer::{ApplyFullyConnectedLayer, FullyConnectedLayer};
use selecting_flow::compute_graph::input_box::InputBox;
use selecting_flow::compute_graph::{ExactDimensionComputeGraphNode, GraphNode};
use selecting_flow::data_ty... |
}
fn read_train_data(labels: impl AsRef<Path>, features: impl AsRef<Path>) -> TrainData {
let (output_size, labels) = read_file_as_tensors(labels);
let (input_size, features) = read_file_as_tensors(features);
let data_pair = labels
.into_par_iter()
.zip_eq(features)
.filter(|(outpu... | {
TrainDataPair { input, output }
} | identifier_body |
main.rs | _graph::activation::softmax_with_loss::SoftmaxWithLoss;
use selecting_flow::compute_graph::fully_connected_layer::{ApplyFullyConnectedLayer, FullyConnectedLayer};
use selecting_flow::compute_graph::input_box::InputBox;
use selecting_flow::compute_graph::{ExactDimensionComputeGraphNode, GraphNode};
use selecting_flow::d... | (labels: impl AsRef<Path>, features: impl AsRef<Path>) -> TrainData {
let (output_size, labels) = read_file_as_tensors(labels);
let (input_size, features) = read_file_as_tensors(features);
let data_pair = labels
.into_par_iter()
.zip_eq(features)
.filter(|(output, _)| output.value_co... | read_train_data | identifier_name |
main.rs | _graph::activation::softmax_with_loss::SoftmaxWithLoss;
use selecting_flow::compute_graph::fully_connected_layer::{ApplyFullyConnectedLayer, FullyConnectedLayer};
use selecting_flow::compute_graph::input_box::InputBox;
use selecting_flow::compute_graph::{ExactDimensionComputeGraphNode, GraphNode};
use selecting_flow::d... | input: input_value,
output: output_value,
} = &data;
assert_eq!(output_value.value_count(), 1);
input.set_value(input_value.clone().into());
output.set_expect_output(output_value.clone());
... | let mut accuracy = 0f64;
for data in &data_pair[range] {
let TrainDataPair { | random_line_split |
main.rs | _graph::activation::softmax_with_loss::SoftmaxWithLoss;
use selecting_flow::compute_graph::fully_connected_layer::{ApplyFullyConnectedLayer, FullyConnectedLayer};
use selecting_flow::compute_graph::input_box::InputBox;
use selecting_flow::compute_graph::{ExactDimensionComputeGraphNode, GraphNode};
use selecting_flow::d... | else {
0.
}
}
};
sum_of_loss += *output_loss.get([]).unwrap() as f64;
if back_propagate {
output.clear_gradient_all();
output.b... | {
1.
} | conditional_block |
structs.go | // This is the point of sale of segments in PNRs: - 9 char Amadeus Office ID. - OR 2 char GDS code for OA PNRs PNRs containing a segment sold in any Amadeus Office ID matching pattern NCE6X*** or ***BA0*** or sold in Sabre (1S) or Gallileo (1G).
Pos *PointOfSaleInformationType `xml:"pos,omitempty"`
// The repetitio... | // identifies the category or categories.
SubQueueInfoDetails *SubQueueInformationDetailsTypeI `xml:"subQueueInfoDetails,omitempty"`
}
| random_line_split | |
tkteach.py | =tk.LEFT)
self.frameLEFT = tk.Frame(master,bd=2,relief=tk.SUNKEN)
self.frameLEFT.pack(side=tk.LEFT)
self.datasetTitleLabel = tk.Label(self.frameLEFT, text="Data Set Selection:")
self.datasetTitleLabel.pack()
self.dataSetsListbox = tk.Listbox(self.frameLEFT,relief=tk.FLAT)
for item in self.... |
# MIDDLE FRAME VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
self.frameMIDDLE = tk.Frame(master, bd=2)
self.frameMIDDLE.pack(side=tk.LEFT)
self.imgStage = tk.Label(self.frameMIDDLE, text="", height=self.default_size[1], width=self.default_size[0])
self.imgStage.pack()
self.imgFileName = tk.Label(se... | self.frameSeperator01 = tk.Frame(master,width=20,height=1)
self.frameSeperator01.pack(side=tk.LEFT)
| random_line_split |
tkteach.py | .frameMIDDLEIMGZOOM = tk.Frame(self.frameMIDDLE, bd=2)
self.frameMIDDLEIMGZOOM.pack()
self.imageZoomLabel = tk.Label(self.frameMIDDLEIMGZOOM, text="Zoom:")
self.imageZoomLabel.pack(side=tk.LEFT)
self.zoomOutButton = tk.Button(self.frameMIDDLEIMGZOOM, text="-", command=self.zoomOut, state=tk.DISABLED... | skipToImage | identifier_name | |
tkteach.py | =tk.LEFT)
self.frameLEFT = tk.Frame(master,bd=2,relief=tk.SUNKEN)
self.frameLEFT.pack(side=tk.LEFT)
self.datasetTitleLabel = tk.Label(self.frameLEFT, text="Data Set Selection:")
self.datasetTitleLabel.pack()
self.dataSetsListbox = tk.Listbox(self.frameLEFT,relief=tk.FLAT)
for item in self.... |
else:
#Check if this is an ad-hoc keybind for a category selection...
try:
if self.categoriesListbox.selection_includes(self.keyBindings.index(key.char.lower())):
self.categoriesListbox.selection_clear(self.keyBindings.index(key.char.lower()))
else:
self.categoriesListbox.selection_set... | self.zoomOutButton.config(relief=tk.SUNKEN)
self.zoomOutButton.update_idletasks()
self.zoomOut()
time.sleep(0.05)
self.zoomOutButton.config(relief=tk.RAISED) | conditional_block |
tkteach.py |
# LEFT FRAME VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
self.frameSeperator00 = tk.Frame(master,width=6,height=1)
self.frameSeperator00.pack(side=tk.LEFT)
self.frameLEFT = tk.Frame(master,bd=2,relief=tk.SUNKEN)
self.frameLEFT.pack(side=tk.LEFT)
self.datasetTitleLabel = tk.Label(self.frameLEFT, t... | print("-->__init__")
self.master = master
self.default_size = (800, 400)
master.title("tkteach version 002")
master.bind("<Key>", self.keyPressed)
# Create GUI elements:
self.titleLabel = tk.Label(master, text="tkteach version 002")
self.titleLabel.pack()
# BOTTOM "STATUS B... | identifier_body | |
v3_alarm_test.go | during apply
func TestV3StorageQuotaApply(t *testing.T) {
integration.BeforeTest(t)
quotasize := int64(16 * os.Getpagesize())
clus := integration.NewCluster(t, &integration.ClusterConfig{Size: 2})
defer clus.Terminate(t)
kvc1 := integration.ToGRPC(clus.Client(1)).KV
// Set a quota on one node
clus.Members[0].... | (t *testing.T) {
integration.BeforeTest(t)
clus := integration.NewCluster(t, &integration.ClusterConfig{Size: 3})
defer clus.Terminate(t)
kvc := integration.ToGRPC(clus.RandClient()).KV
mt := integration.ToGRPC(clus.RandClient()).Maintenance
alarmReq := &pb.AlarmRequest{
MemberID: 123,
Action: pb.AlarmReq... | TestV3AlarmDeactivate | identifier_name |
v3_alarm_test.go | during apply
func TestV3StorageQuotaApply(t *testing.T) {
integration.BeforeTest(t)
quotasize := int64(16 * os.Getpagesize())
clus := integration.NewCluster(t, &integration.ClusterConfig{Size: 2})
defer clus.Terminate(t)
kvc1 := integration.ToGRPC(clus.Client(1)).KV
// Set a quota on one node
clus.Members[0].... | select {
case <-stopc:
t.Fatalf("timed out waiting for alarm")
case <-time.After(10 * time.Millisecond):
}
}
// txn with non-mutating Ops should go through when NOSPACE alarm is raised
_, err = kvc0.Txn(context.TODO(), &pb.TxnRequest{
Compare: []*pb.Compare{
{
Key: key,
Result: ... | random_line_split | |
v3_alarm_test.go | during apply
func TestV3StorageQuotaApply(t *testing.T) {
integration.BeforeTest(t)
quotasize := int64(16 * os.Getpagesize())
clus := integration.NewCluster(t, &integration.ClusterConfig{Size: 2})
defer clus.Terminate(t)
kvc1 := integration.ToGRPC(clus.Client(1)).KV
// Set a quota on one node
clus.Members[0].... |
ctx, cancel := context.WithTimeout(context.TODO(), integration.RequestWaitTimeout)
defer cancel()
// small quota machine should reject put
if _, err := kvc0.Put(ctx, &pb.PutRequest{Key: key, Value: smallbuf}); err == nil {
t.Fatalf("past-quota instance should reject put")
}
// large quota machine should rej... | {
t.Fatal(err)
} | conditional_block |
v3_alarm_test.go | during apply
func TestV3StorageQuotaApply(t *testing.T) {
integration.BeforeTest(t)
quotasize := int64(16 * os.Getpagesize())
clus := integration.NewCluster(t, &integration.ClusterConfig{Size: 2})
defer clus.Terminate(t)
kvc1 := integration.ToGRPC(clus.Client(1)).KV
// Set a quota on one node
clus.Members[0].... | fp := filepath.Join(clus.Members[0].DataDir, "member", "snap", "db")
be := backend.NewDefaultBackend(lg, fp)
s := mvcc.NewStore(lg, be, nil, mvcc.StoreConfig{})
// NOTE: cluster_proxy mode with namespacing won't set 'k', but namespace/'k'.
s.Put([]byte("abc"), []byte("def"), 0)
s.Put([]byte("xyz"), []byte("123"),... | {
integration.BeforeTest(t)
lg := zaptest.NewLogger(t)
clus := integration.NewCluster(t, &integration.ClusterConfig{Size: 3, UseBridge: true})
defer clus.Terminate(t)
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
go func() {
defer wg.Done()
if _, err := clus.Client(0).Put(context.TODO(), "k... | identifier_body |
agent.go | network logical label
// Asynchronous operations
resumeReconciliation <-chan string // nil if no async ops
cancelAsyncOps context.CancelFunc // nil if no async ops
waitForAsyncOps func() // NOOP if no async ops
}
func (a *agent) init() error {
a.ctx = context.Background()
linkChan :... |
}
func (a *agent) linkSubscribe(doneChan <-chan struct{}) chan netlink.LinkUpdate {
linkChan := make(chan netlink.LinkUpdate, 64)
linkErrFunc := func(err error) {
log.Errorf("LinkSubscribe failed %s\n", err)
}
linkOpts := netlink.LinkSubscribeOptions{
ErrorCallback: linkErrFunc,
}
if err := netlink.LinkSubs... | {
log.Infof("Fixed config items: %s",
strings.Join(fixed, ", "))
} | conditional_block |
agent.go | : network logical label
// Asynchronous operations
resumeReconciliation <-chan string // nil if no async ops
cancelAsyncOps context.CancelFunc // nil if no async ops
waitForAsyncOps func() // NOOP if no async ops
}
func (a *agent) init() error | return nil
}
func (a *agent) run(linkChan chan netlink.LinkUpdate) {
for {
select {
case netModel := <-a.newNetModel:
// Network model is already validated, applying...
a.Lock()
a.netModel = netModel
a.updateCurrentState()
a.updateIntendedState()
a.reconcile()
a.Unlock()
case <-a.resumeR... | {
a.ctx = context.Background()
linkChan := a.linkSubscribe(a.ctx.Done())
a.macLookup = &maclookup.MacLookup{}
a.macLookup.RefreshCache()
registry := &reconciler.DefaultRegistry{}
if err := configitems.RegisterItems(registry, a.macLookup); err != nil {
return err
}
a.registry = registry
a.newNetModel = make(c... | identifier_body |
agent.go | : network logical label
// Asynchronous operations
resumeReconciliation <-chan string // nil if no async ops
cancelAsyncOps context.CancelFunc // nil if no async ops
waitForAsyncOps func() // NOOP if no async ops
}
func (a *agent) init() error {
a.ctx = context.Background()
linkChan ... | (doneChan <-chan struct{}) chan netlink.LinkUpdate {
linkChan := make(chan netlink.LinkUpdate, 64)
linkErrFunc := func(err error) {
log.Errorf("LinkSubscribe failed %s\n", err)
}
linkOpts := netlink.LinkSubscribeOptions{
ErrorCallback: linkErrFunc,
}
if err := netlink.LinkSubscribeWithOptions(
linkChan, don... | linkSubscribe | identifier_name |
agent.go | := linkUpdate.Header.Type == syscall.RTM_DELLINK
if added || deleted {
log.Debugf("Important link change: %+v", linkUpdate)
a.Lock()
a.macLookup.RefreshCache()
changed := a.updateCurrentState()
mac := linkUpdate.Attrs().HardwareAddr
if bytes.HasPrefix(mac, hostPortMACPrefix) {
// Intend... | func (a *agent) getHostGwIP(ipv6 bool) net.IP {
hostPort, found := a.macLookup.GetInterfaceByMAC(hostPortMACPrefix, true) | random_line_split | |
client.go | getLogger = func(ctx context.Context) log.Logger {
return log.NewNopLogger()
}
}
if setLogger == nil {
setLogger = func(ctx context.Context, _ log.Logger) context.Context {
return ctx
}
}
tokenAcquirer, err := buildTokenAcquirer(&config.Auth)
if err != nil {
return nil, err
}
clientStore := &Clien... | {
if c.observer == nil || c.observer.ticker == nil {
return nil
}
if !atomic.CompareAndSwapInt32(&c.observer.state, running, transitioning) {
level.Error(c.logger).Log(xlog.MessageKey(), "Stop called when a listener was not in running state", "err", ErrListenerNotStopped)
return ErrListenerNotRunning
}
c.o... | identifier_body | |
client.go | client.
Listen ListenerConfig
}
type response struct {
Body []byte
ArgusErrorHeader string
Code int
}
type Auth struct {
JWT acquire.RemoteBearerTokenAcquirerOptions
Basic string
}
type Items []model.Item
type Client struct {
client *http.Client
auth acquire.Acquirer... | }
if !atomic.CompareAndSwapInt32(&c.observer.state, stopped, transitioning) {
level.Error(c.logger).Log(xlog.MessageKey(), "Start called when a listener was not in stopped state", "err", ErrListenerNotStopped) | random_line_split | |
client.go | .New("argus address is required")
ErrBucketEmpty = errors.New("bucket name is required")
ErrItemIDEmpty = errors.New("item ID is required")
ErrItemDataEmpty = errors.New("data field in item is required")
ErrUndefinedIntervalTicker = errors.New("interval ticker is nil. Can't listen ... | (options acquire.RemoteBearerTokenAcquirerOptions) bool {
return len(options.AuthURL) < 1 || options.Buffer == 0 || options.Timeout == 0
}
func buildTokenAcquirer(auth *Auth) (acquire.Acquirer, error) {
if !isEmpty(auth.JWT) {
return acquire.NewRemoteBearerTokenAcquirer(auth.JWT)
} else if len(auth.Basic) > 0 {
... | isEmpty | identifier_name |
client.go | .New("argus address is required")
ErrBucketEmpty = errors.New("bucket name is required")
ErrItemIDEmpty = errors.New("item ID is required")
ErrItemDataEmpty = errors.New("data field in item is required")
ErrUndefinedIntervalTicker = errors.New("interval ticker is nil. Can't listen ... |
err := validateConfig(&config)
if err != nil {
return nil, err
}
if getLogger == nil {
getLogger = func(ctx context.Context) log.Logger {
return log.NewNopLogger()
}
}
if setLogger == nil {
setLogger = func(ctx context.Context, _ log.Logger) context.Context {
return ctx
}
}
tokenAcquirer, err ... | {
return nil, ErrNilMeasures
} | conditional_block |
shader.rs | use_program(&self) {
unsafe {
gl::UseProgram(self.gl_handle);
}
}
pub fn is_bound(&self) -> bool {
self.gl_handle == Shader::get_currently_bound_raw()
}
pub fn get_uniform_loc(&self, uniform: &str) -> i32 {
use std::ffi::CString;
unsafe {
let cstr = CString::new(uniform).unwrap();
gl::GetUnif... | .collect::<Vec<_>>();
| random_line_split | |
shader.rs | this please
gl::BindAttribLocation(program, 0, b"position\0".as_ptr() as _);
gl::LinkProgram(program);
let mut status = 0i32;
gl::GetProgramiv(program, gl::LINK_STATUS, &mut status);
if status == 0 {
let mut buf = [0u8; 1024];
let mut len = 0;
gl::GetProgramInfoLog(program, buf.len() as _,... |
pub fn attribute(mut self, name: &str, ty: &str) -> Self {
if name == "position" {
println!("Tried to overwrite 'position' attribute while building shader - ignoring");
return self
}
self.attributes.push(format!("{} {}", ty, name)); self
}
pub fn varying(mut self, name: &str, ty: &str) -> Self {
se... | {
self.uniforms.push(format!("{} u_{}", ty, name)); self
} | identifier_body |
shader.rs | of this please
gl::BindAttribLocation(program, 0, b"position\0".as_ptr() as _);
gl::LinkProgram(program);
let mut status = 0i32;
gl::GetProgramiv(program, gl::LINK_STATUS, &mut status);
if status == 0 {
let mut buf = [0u8; 1024];
let mut len = 0;
gl::GetProgramInfoLog(program, buf.len() as... | <V>(&self, uniform: &str, v: V) where V: Into<Vec3> {
assert!(self.is_bound(), "Tried to set uniform '{}' on unbound shader", uniform);
unsafe {
let v = v.into();
gl::Uniform3f(self.get_uniform_loc(&uniform), v.x, v.y, v.z);
}
}
pub fn set_uniform_vec4<V>(&self, uniform: &str, v: V) where V: Into<Vec4> ... | set_uniform_vec3 | identifier_name |
shader.rs | of this please
gl::BindAttribLocation(program, 0, b"position\0".as_ptr() as _);
gl::LinkProgram(program);
let mut status = 0i32;
gl::GetProgramiv(program, gl::LINK_STATUS, &mut status);
if status == 0 {
let mut buf = [0u8; 1024];
let mut len = 0;
gl::GetProgramInfoLog(program, buf.len() as... | else {
gl_position.push_str("vec4(position, 0.0, 1.0);\n");
}
self.vertex_body = format!("{}{}", gl_position, self.vertex_body);
let mut bodies = [&mut self.vertex_body, &mut self.fragment_body];
for (sh, body) in [&mut vert_src, &mut frag_src].iter_mut().zip(bodies.iter_mut()) {
write!(sh, "\n{}\n", v... | {
gl_position.push_str("vec4(position, 1.0);\n");
} | conditional_block |
console.js | of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* Aloha Editor is distributed in the hope that it will be useful, | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1... | * but WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.