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
main.go
package main import ( "code.google.com/p/go.net/websocket" "code.google.com/p/goauth2/oauth" "code.google.com/p/google-api-go-client/mirror/v1" "code.google.com/p/google-api-go-client/oauth2/v2" "encoding/json" "fmt" picarus "github.com/bwhite/picarus/go" "github.com/gorilla/pat" "github.com/ugorji/go-msgpack...
resp, err := trans.RoundTrip(req) if err != nil { LogPrintf("getattachment: content") return nil, err } defer resp.Body.Close() imageData, err := ioutil.ReadAll(resp.Body) if err != nil { LogPrintf("getattachment: body") return nil, err } return imageData, nil } func notifyOpenGlass(conn *picarus.Conn...
{ LogPrintf("getattachment: http") return nil, err }
conditional_block
main.go
package main import ( "code.google.com/p/go.net/websocket" "code.google.com/p/goauth2/oauth" "code.google.com/p/google-api-go-client/mirror/v1" "code.google.com/p/google-api-go-client/oauth2/v2" "encoding/json" "fmt" picarus "github.com/bwhite/picarus/go" "github.com/gorilla/pat" "github.com/ugorji/go-msgpack...
w.WriteHeader(500) LogPrintf("oauth: json marshal") return } storeCredential(userId, tok, string(userSer)) http.Redirect(w, r, fullUrl, http.StatusFound) } func SetupHandler(w http.ResponseWriter, r *http.Request) { userId, err := userID(r) if err != nil || userId == "" { w.WriteHeader(400) LogPrintf("s...
} userSer, err := json.Marshal(u) if err != nil {
random_line_split
main.go
package main import ( "code.google.com/p/go.net/websocket" "code.google.com/p/goauth2/oauth" "code.google.com/p/google-api-go-client/mirror/v1" "code.google.com/p/google-api-go-client/oauth2/v2" "encoding/json" "fmt" picarus "github.com/bwhite/picarus/go" "github.com/gorilla/pat" "github.com/ugorji/go-msgpack...
(conn *picarus.Conn, svc *mirror.Service, trans *oauth.Transport, t *mirror.TimelineItem) ([]byte, error) { a, err := svc.Timeline.Attachments.Get(t.Id, t.Attachments[0].Id).Do() if err != nil { LogPrintf("getattachment: metadata") return nil, err } req, err := http.NewRequest("GET", a.ContentUrl, nil) if err ...
getImageAttachment
identifier_name
snapshots.go
/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to...
Flags: []cli.Flag{ cli.StringFlag{ Name: "target, t", Usage: "Mount target path, will print mount, if provided", }, cli.BoolFlag{ Name: "mounts", Usage: "Print out snapshot mounts as JSON", }, }, Action: func(context *cli.Context) error { if narg := context.NArg(); narg < 1 || narg > 2 { r...
ArgsUsage: "[flags] <key> [<parent>]",
random_line_split
snapshots.go
/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to...
{ // FIXME: This is specific to Unix for _, m := range mounts { fmt.Printf("mount -t %s %s %s -o %s\n", m.Type, m.Source, filepath.Join(target, m.Target), strings.Join(m.Options, ",")) } }
identifier_body
snapshots.go
/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to...
(target string, mounts []mount.Mount) { // FIXME: This is specific to Unix for _, m := range mounts { fmt.Printf("mount -t %s %s %s -o %s\n", m.Type, m.Source, filepath.Join(target, m.Target), strings.Join(m.Options, ",")) } }
printMounts
identifier_name
snapshots.go
/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to...
defer cancel() snapshotter := client.SnapshotService(context.GlobalString("snapshotter")) info, err := snapshotter.Stat(ctx, key) if err != nil { return err } commands.PrintAsJSON(info) return nil }, } var setLabelCommand = cli.Command{ Name: "label", Usage: "Add labels to content",...
{ return err }
conditional_block
server.py
# -*- coding: utf-8 -*- # 简易http 与 websocket 服务端 import logging import socket import base64 import hashlib import struct import os import binascii import json from select import select logging.basicConfig(level=logging.DEBUG) def md5_for_file(f, block_size=2 ** 20): md5 = hashlib.md5() w...
v): key = base64.b64encode(hashlib.sha1(v + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest()) response = 'HTTP/1.1 101 Switching Protocols\r\n' \ 'Upgrade: websocket\r\n' \ 'Connection: Upgrade\r\n' \ 'Sec-WebSocket-Accept:' + key + '\r\n\...
self, conn,
identifier_name
server.py
# -*- coding: utf-8 -*- # 简易http 与 websocket 服务端 import logging import socket import base64 import hashlib import struct import os import binascii import json from select import select logging.basicConfig(level=logging.DEBUG) def md5_for_file(f, block_size=2 ** 20): md5 = hashlib.md5() w...
length = len_flag ret = '' for cnt, d in enumerate(raw): ret += chr(ord(d) ^ ord(mask[cnt % 4])) if not ret: pass # logging.debug("frame info FIN %d Opcode %d mask %d length %d " % (FIN, Opcode, is_mask, length)) # hexstr = binas...
raw = data[14:] length = reduce(lambda y, z: y * 256 + z, map(lambda x: ord(x), data[2:9])) else: mask = data[2:6] raw = data[6:]
random_line_split
server.py
# -*- coding: utf-8 -*- # 简易http 与 websocket 服务端 import logging import socket import base64 import hashlib import struct import os import binascii import json from select import select logging.basicConfig(level=logging.DEBUG) def md5_for_file(f, block_size=2 ** 20): md5 = hashlib.md5() w...
ey]['no'])) elif msg['a'] == 'f': logging.info('a %s s %d e %d n %d' % (msg['a'], msg['s'], msg['e'], msg['n'])) start, end = msg['s'], msg['e'] length = end - start if msg['n'] != session['no']: if msg['n'] < session[...
self.session[sesskey]['filebuffer'] = [] self.session[sesskey]['no'] = 0 self.session[sesskey]['file'] = open( os.path.join(os.path.dirname(__file__), 'upload', msg['name']), 'ab') elif msg['a'] == 'ping': self.ws_send(conn, "ok:%d"...
conditional_block
server.py
# -*- coding: utf-8 -*- # 简易http 与 websocket 服务端 import logging import socket import base64 import hashlib import struct import os import binascii import json from select import select logging.basicConfig(level=logging.DEBUG) def md5_for_file(f, block_size=2 ** 20): md5 = hashli
Server: socket = None socket_list = set() port = 7000 buffersize = 1024*1024 timeout = 20 content = dict() session = dict() def __init__(self): filelist = ['test.html', 'upload.js', 'spark-md5.min.js'] for i in filelist: with open(i, 'r') as f: ...
b.md5() while True: data = f.read(block_size) if not data: break md5.update(data) return md5.hexdigest() class
identifier_body
rol_common.js
// 防止事件冒泡 function stopBubble(e) { // If an event object is provided, then this is a non-IE browser if ( e && e.stopPropagation ) // and therefore it supports the W3C stopPropagation() method e.stopPropagation(); else // Otherwise, we need to use the Internet Explorer // way of cancelling event bubbling window...
function show_msg_tips_newdiv(type,msg,id){ if(!type || !msg) return; var time=3000; if('success'==type || 'yes'==type) $.scmtips.show("success",msg,null,time); if('warn'==type || 'warning'==type) $.scmtips.show("warn",msg,null,time); if('error'==type || 'wrong'==type) $.scmtips.show("error",msg,null,time)...
//在弹出框中显示提示信息
random_line_split
rol_common.js
// 防止事件冒泡 function stopBubble(e) { // If an event object is provided, then this is a non-IE browser if ( e && e.stopPropagation ) // and therefore it supports the W3C stopPropagation() method e.stopPropagation(); else // Otherwise, we need to use the Internet Explorer // way of cancelling event bubbling window...
nav_open"); } } //左边菜单展开,关闭替换图标 function replaceImg(obj){ var img = $(obj).find("img"); var src = img.attr("src"); if(src.indexOf('open')>0){ img.attr("src",src.replace("open","close")); }else{ img.attr("src",src.replace("close","open")); } } //打开左侧菜单,根据设置的.info样式 function open_left_nav(){ $("#left_nav"...
$(obj).css("zIndex",1000); $(obj).css("height",$(obj).find(".float_div_content").height()+70) },100); }else{ $(obj).hide(); } } //左菜单展开,关闭 function switch_left_nav(obj){ var div = $(obj).parent(); if($(obj).hasClass("left_nav_open")) { div.find(">div:not(div:first-child)").hide(); $(obj).removeClass("le...
conditional_block
rol_common.js
// 防止事件冒泡 function stopBubble(e) { // If an event object is provided, then this is a non-IE browser if ( e && e.stopPropagation ) // and therefore it supports the W3C stopPropagation() method e.stopPropagation(); else // Otherwise, we need to use the Internet Explorer // way of cancelling event bubbling window...
rror",msg,null,time); } function show_msg_tips(type,msg,width){ if(!type || !msg) return; var time=1000; if('success'==type || 'yes'==type) $.scmtips.show("success",msg, width,time); if('warn'==type || 'warning'==type) $.scmtips.show("warn",msg, width,time); if('error'==type || 'wrong'==type) $.scmtips.sh...
cmtips.show("warn",msg,null,time); if('error'==type || 'wrong'==type) $.scmtips.show("e
identifier_body
rol_common.js
// 防止事件冒泡 function stopBubble(e) { // If an event object is provided, then this is a non-IE browser if ( e && e.stopPropagation ) // and therefore it supports the W3C stopPropagation() method e.stopPropagation(); else // Otherwise, we need to use the Internet Explorer // way of cancelling event bubbling window...
} } if(flag) return true; } var patrn = /^[^<]*(<(.|\s)+>)[^>]*$|^#$/; if (!patrn.exec(s)) return false ; return true ; } //字符串真实的长度 function getStrRealLength(str){ return str.replace(/[^\x00-\xff]/gi, "--").replace(/[wW]/gi, "--").length; } //字符串缩略 function subStrBreviary(str,maxLength){...
break;
identifier_name
ranker_ltr.py
""" Uses Learning to Rank to rank entities @author: Faegheh Hasibi """ from datetime import datetime import pickle from nordlys.erd.features.query_sim_feat import QuerySimFeat from nordlys.ml.cross_validation import CrossValidation from nordlys.erd.features.entity_feat import EntityFeat from nordlys.erd.features.men...
return self.ml.apply_model(inss, model) def rank_queries(self, queries, time_log_file=None): # commonness_th, filter=True, """ Ranks entities for the given queries using the trained model. :param queries: a dictionary, {q_id: q_content, ...} :param time_log_file: file nam...
model = self.model
conditional_block
ranker_ltr.py
""" Uses Learning to Rank to rank entities @author: Faegheh Hasibi """ from datetime import datetime import pickle from nordlys.erd.features.query_sim_feat import QuerySimFeat from nordlys.ml.cross_validation import CrossValidation from nordlys.erd.features.entity_feat import EntityFeat from nordlys.erd.features.men...
(self, queries, time_log_file=None): # commonness_th, filter=True, """ Ranks entities for the given queries using the trained model. :param queries: a dictionary, {q_id: q_content, ...} :param time_log_file: file name to save time log :return erd.ml.CERInstances, Ranked instanc...
rank_queries
identifier_name
ranker_ltr.py
""" Uses Learning to Rank to rank entities @author: Faegheh Hasibi """ from datetime import datetime import pickle from nordlys.erd.features.query_sim_feat import QuerySimFeat from nordlys.ml.cross_validation import CrossValidation from nordlys.erd.features.entity_feat import EntityFeat from nordlys.erd.features.men...
def rank_query(self, query): """ Generates ranking score for entities related to the given query. :param query: query.Query :return erd.ml.CERInstances """ q_inss = CERInstances.gen_instances(query, self.commonness_th, sf_source=self.sf_source, filter=self.filter) ...
""" Ranks entities for the given queries using the trained model. :param queries: a dictionary, {q_id: q_content, ...} :param time_log_file: file name to save time log :return erd.ml.CERInstances, Ranked instances """ print "Ranking queries ..." total_time = 0.0 ...
identifier_body
ranker_ltr.py
""" Uses Learning to Rank to rank entities @author: Faegheh Hasibi """ from datetime import datetime import pickle from nordlys.erd.features.query_sim_feat import QuerySimFeat from nordlys.ml.cross_validation import CrossValidation from nordlys.erd.features.entity_feat import EntityFeat from nordlys.erd.features.men...
model: the trained model """ def __init__(self, commonness_th=None, sf_source=None, filter=True, model=None, config={}): self.commonness_th = commonness_th self.sf_source = sf_source self.filter = filter self.config = config self.model = model self.ml = ML...
random_line_split
opentuna-stack.ts
import * as cdk from '@aws-cdk/core'; import * as cloudfront from '@aws-cdk/aws-cloudfront'; import * as route53 from '@aws-cdk/aws-route53'; import * as route53targets from '@aws-cdk/aws-route53-targets'; import * as acm from '@aws-cdk/aws-certificatemanager'; import * as cloudwatch from '@aws-cdk/aws-cloudwatch'; imp...
extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props: OpenTunaStackProps) { super(scope, id, props); const stack = cdk.Stack.of(this); const domainName = this.node.tryGetContext('domainName'); const domainZoneName = this.node.tryGetContext('domainZone'); const iamCertId = thi...
OpentunaStack
identifier_name
opentuna-stack.ts
import * as cdk from '@aws-cdk/core'; import * as cloudfront from '@aws-cdk/aws-cloudfront'; import * as route53 from '@aws-cdk/aws-route53'; import * as route53targets from '@aws-cdk/aws-route53-targets'; import * as acm from '@aws-cdk/aws-certificatemanager'; import * as cloudwatch from '@aws-cdk/aws-cloudwatch'; imp...
else if (typeof cloudfrontCert === "string") { // IAM cert cloudfrontProps = { viewerCertificate: cloudfront.ViewerCertificate.fromIamCertificate( cloudfrontCert, { aliases: [domainName], securityPolicy: cloudfront.SecurityPolicyProtocol.TLS...
{ // ACM cert cloudfrontProps = { aliasConfiguration: { acmCertRef: cloudfrontCert.certificateArn, names: [domainName], }, ...cloudfrontProps } }
conditional_block
opentuna-stack.ts
import * as cdk from '@aws-cdk/core'; import * as cloudfront from '@aws-cdk/aws-cloudfront'; import * as route53 from '@aws-cdk/aws-route53'; import * as route53targets from '@aws-cdk/aws-route53-targets'; import * as acm from '@aws-cdk/aws-certificatemanager'; import * as cloudwatch from '@aws-cdk/aws-cloudwatch'; imp...
}
{ super(scope, id, props); const stack = cdk.Stack.of(this); const domainName = this.node.tryGetContext('domainName'); const domainZoneName = this.node.tryGetContext('domainZone'); const iamCertId = this.node.tryGetContext('iamCertId'); let useHTTPS = false; let domainZone: r53.IHostedZone...
identifier_body
opentuna-stack.ts
import * as cdk from '@aws-cdk/core'; import * as cloudfront from '@aws-cdk/aws-cloudfront'; import * as route53 from '@aws-cdk/aws-route53'; import * as route53targets from '@aws-cdk/aws-route53-targets'; import * as acm from '@aws-cdk/aws-certificatemanager'; import * as cloudwatch from '@aws-cdk/aws-cloudwatch'; imp...
allowAllOutbound: true, }); const tunaManagerALBSG = new ec2.SecurityGroup(this, "TunaManagerALBSG", { vpc, description: "SG of ALB of Tuna Manager", allowAllOutbound: false, }); const tunaWorkerSG = new ec2.SecurityGroup(this, "TunaWorkerSG", { vpc, description: "SG ...
const tunaManagerSG = new ec2.SecurityGroup(this, "TunaManagerSG", { vpc, description: "SG of Tuna Manager",
random_line_split
L.IM_RoutingControl.js
/** * L.Control.RoutingControl control de routing basado en el leaflet-routing-machine */ L.Control.RoutingControl = L.Control.extend({ includes: L.Mixin.Events, options: { position: 'topleft', lang: 'ca', id: 'dv_bt_Routing', className: 'leaflet-bar btn btn-default btn-sm grisfort', title: 'Routing', ...
else { return L.marker(wp.latLng, { draggable: true, icon: puntIntermig }); } }; this._plan = new this._reversablePlan([], { geocoder: L.Control.Geocoder.icgc(), routeWhileDragging: true, language: lang, createMarker: createM...
return L.marker(wp.latLng, { draggable: true, icon: puntDesti }); }
conditional_block
L.IM_RoutingControl.js
/** * L.Control.RoutingControl control de routing basado en el leaflet-routing-machine */ L.Control.RoutingControl = L.Control.extend({ includes: L.Mixin.Events, options: { position: 'topleft', lang: 'ca', id: 'dv_bt_Routing', className: 'leaflet-bar btn btn-default btn-sm grisfort', title: 'Routing', ...
'<i class="t-square-rounded" style="-webkit-transform:scale(1.25) scale(0.65) rotate(45deg);-moz-transform:scale(1.25) scale(0.65) rotate(45deg);transform:scale(1.25) scale(0.65) rotate(45deg)"></i>'+ '<i class="t-turn-90-l t-c-white" style="-webkit-transform:scale(-1.3, 1.3);-moz-transform:scale(-1.3, 1.3);transfo...
random_line_split
views.py
from django.shortcuts import render, redirect, get_object_or_404 from django.core.urlresolvers import reverse_lazy from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.base import TemplateResponseMixin, View from django.views.generic.edit import Cre...
lass CourseUpdateView(PermissionRequiredMixin, OwnerCourseEditMixin, UpdateView): """ Используется для изменения Course """ # PermissionRequiredMixin проверяет если у пользователя указанный permission_required permission_required = "courses.change_course" class CourseDeleteView(PermissionRequiredMixin, OwnerCou...
age_course_list') template_name = "courses/manage/course/form.html" class ManageCourseListView(OwnerCourseMixin, ListView): """ Используя наследование от OwnerCourseMixin, ListView этот класс также будет содержать все поля и методы из OwnerCourseMixin, ListView, OwnerMixin """ template_name = "courses/manage/c...
identifier_body
views.py
from django.shortcuts import render, redirect, get_object_or_404 from django.core.urlresolvers import reverse_lazy from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.base import TemplateResponseMixin, View from django.views.generic.edit import Cre...
ved': 'OK'}) class CourseListView(TemplateResponseMixin, View): """ Список всех курсов """ model = Course template_name = "courses/course/list.html" def get(self, request, subject=None): # возвращаем все subjects с количеством курсов для subject subjects = Subject.objects.annotate(total_courses=Count('cour...
ериализирует response """ def post(self, request): for id, order in self.request_json.items(): print('id', id, ' -- ', order) for id, order in self.request_json.items(): Content.objects.filter(id=id, module__course__owner=request.user).update(order=order) return self.render_json_response({'sa
conditional_block
views.py
from django.shortcuts import render, redirect, get_object_or_404 from django.core.urlresolvers import reverse_lazy from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.base import TemplateResponseMixin, View from django.views.generic.edit import Cre...
content.content_object.delete() content.delete() # возвращаемся к списку контента модуля return redirect('module_content_list', module.id) class ModuleContentListView(TemplateResponseMixin, View): template_name = "courses/manage/module/content_list.html" def get(self, request, module_id): module = get_ob...
id=id, module__course__owner=request.user) module = content.module
random_line_split
views.py
from django.shortcuts import render, redirect, get_object_or_404 from django.core.urlresolvers import reverse_lazy from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.base import TemplateResponseMixin, View from django.views.generic.edit import Cre...
ы) задается владелец этого объекта. """ form.instance.owner = self.request.user return super(OwnerEditMixin, self).form_valid(form) class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin): """ Указание модели для queryset во всех дочерних классах """ model = Course class OwnerCourseEditMixin(OwnerCourseM...
верждение форм
identifier_name
CKEditor_media_tab.js
/** * Add a media tab to the image properties dialog. * * This process as to be executed in a precise time frame; * After CKEditor is loaded, but before it's executed. * * It tooks me some time to find out a stable way to define this. * There is how I understand the loading process: * * Drupal Page: * ...
else { inputEl.setAttribute('readonly', true); inputEl.addClass('disabled'); } }; var imageStyles = [ ['Original', 'media_original'], ['Link', 'media_link'], ['Preview', 'media_preview'], ['Large', 'media_large'] ]; // NOTE: Drupal.settings.eatlas_media_frame_filter.drupal_custom_image...
{ inputEl.removeAttribute('readonly'); inputEl.removeClass('disabled'); }
conditional_block
CKEditor_media_tab.js
/** * Add a media tab to the image properties dialog. * * This process as to be executed in a precise time frame; * After CKEditor is loaded, but before it's executed. * * It tooks me some time to find out a stable way to define this. * There is how I understand the loading process: * * Drupal Page: * ...
// Remove previous 'image style' class and find the image ID var newClasses = []; for (var i=0, len=classes.length; i<len; i++) { if (classes[i].substring(0, IMAGESTYLE_CLASS_PREFIX.length) !== IMAGESTYLE_CLASS_PREFIX) { newClasses.push(classes[i]); } } // Add new 'image style' class ne...
// API: dialog.getValueOf(pageId, elementId); var classes = dialog.getValueOf('advanced', 'txtGenClass'); classes = classes ? classes.split(/\s+/) : [];
random_line_split
CKEditor_media_tab.js
/** * Add a media tab to the image properties dialog. * * This process as to be executed in a precise time frame; * After CKEditor is loaded, but before it's executed. * * It tooks me some time to find out a stable way to define this. * There is how I understand the loading process: * * Drupal Page: * ...
/** * element: CKEDITOR.dom.element * The file ID is store in the class of the element: * class="... img__fid__12 ..."; */ function _eatlas_media_frame_ckeditor_get_fid(element) { var classesStr = element.getAttribute('class'); var fidClassPrefix = 'img__fid__'; if (classesStr) { var ...
{ return $('<div/>').html(str).text(); }
identifier_body
CKEditor_media_tab.js
/** * Add a media tab to the image properties dialog. * * This process as to be executed in a precise time frame; * After CKEditor is loaded, but before it's executed. * * It tooks me some time to find out a stable way to define this. * There is how I understand the loading process: * * Drupal Page: * ...
(str) { return $('<div/>').html(str).text(); } /** * element: CKEDITOR.dom.element * The file ID is store in the class of the element: * class="... img__fid__12 ..."; */ function _eatlas_media_frame_ckeditor_get_fid(element) { var classesStr = element.getAttribute('class'); var fidClassP...
_decode
identifier_name
lib.rs
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.a...
} #[pallet::hooks] impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> { fn integrity_test() { // If you hit this error, you need to try to `Box` big dispatchable parameters. assert!( sp_std::mem::size_of::<<T as Config>::RuntimeCall>() as u32 <= CALL_ALIGN, "Call enum size should be smaller tha...
{ let allocator_limit = sp_core::MAX_POSSIBLE_ALLOCATION; let call_size = ((sp_std::mem::size_of::<<T as Config>::RuntimeCall>() as u32 + CALL_ALIGN - 1) / CALL_ALIGN) * CALL_ALIGN; // The margin to take into account vec doubling capacity. let margin_factor = 3; allocator_limit / margin_factor /...
identifier_body
lib.rs
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.a...
() { // If you hit this error, you need to try to `Box` big dispatchable parameters. assert!( sp_std::mem::size_of::<<T as Config>::RuntimeCall>() as u32 <= CALL_ALIGN, "Call enum size should be smaller than {} bytes.", CALL_ALIGN, ); } } #[pallet::error] pub enum Error<T> { /// Too many ca...
integrity_test
identifier_name
lib.rs
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.a...
let is_root = ensure_root(origin.clone()).is_ok(); let calls_len = calls.len(); ensure!(calls_len <= Self::batched_calls_limit() as usize, Error::<T>::TooManyCalls); // Track the actual weight of each of the batch calls. let mut weight = Weight::zero(); for (index, call) in calls.into_iter().enumer...
{ return Err(BadOrigin.into()) }
conditional_block
lib.rs
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.a...
/// event is deposited. If a call failed and the batch was interrupted, then the /// `BatchInterrupted` event is deposited, along with the number of successful calls made /// and the error of the failed call. If all were successful, then the `BatchCompleted` /// event is deposited. #[pallet::call_index(0)] ...
/// - O(C) where C is the number of calls to be batched. /// /// This will return `Ok` in all circumstances. To determine the success of the batch, an
random_line_split
main.py
import argparse import os import random import shutil import time import warnings import numpy as np from torchvision import datasets from functions import * from imagepreprocess import * from model_init import * from src.representation import * import torch import torch.nn as nn import torch.nn.parallel import torc...
(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count class Learning_rate_generater(ob...
__init__
identifier_name
main.py
import argparse import os import random import shutil import time import warnings import numpy as np from torchvision import datasets from functions import * from imagepreprocess import * from model_init import * from src.representation import * import torch import torch.nn as nn import torch.nn.parallel import torc...
else: raise KeyError("=> undefined learning rate method '{}'" .format(method)) self.lr_factor = lr_factor self.lr = lr def step(self, params, total_epoch): decrease_until = decode_params(params) decrease_num = len(decrease_until) base_factor = 0.1 ...
lr_factor, lr = self.log(params, total_epoch)
conditional_block
main.py
import argparse import os import random import shutil import time import warnings import numpy as np from torchvision import datasets from functions import * from imagepreprocess import * from model_init import * from src.representation import * import torch import torch.nn as nn import torch.nn.parallel import torc...
def validate(val_loader, model, criterion): batch_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() # switch to evaluate mode model.eval() with torch.no_grad(): end = time.time() for i, (input, target) in enumerate(val_loader): ...
batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() # switch to train mode model.train() end = time.time() for i, (input, target) in enumerate(train_loader): # measure data loading time data_time.upd...
identifier_body
main.py
import argparse import os import random import shutil import time import warnings import numpy as np from torchvision import datasets from functions import * from imagepreprocess import * from model_init import * from src.representation import * import torch import torch.nn as nn import torch.nn.parallel import torc...
help='url used to set up distributed training') parser.add_argument('--dist-backend', default='gloo', type=str, help='distributed backend') parser.add_argument('--seed', default=None, type=int, help='seed for initializing training. ') parser.add_argument('--gp...
parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,
random_line_split
shlex.go
/* Copyright 2012 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
func (classifier *TokenClassifier) ClassifyRune(rune int32) RuneTokenType { return classifier.typeMap[rune] } /* A type for turning an input stream in to a sequence of strings. Whitespace and comments are skipped. */ type Lexer struct { tokenizer *Tokenizer } /* Create a new lexer. */ func NewLexer(r io.Reader) (...
{ typeMap := map[int32]RuneTokenType{} addRuneClass(&typeMap, RUNE_CHAR, RUNETOKEN_CHAR) addRuneClass(&typeMap, RUNE_SPACE, RUNETOKEN_SPACE) addRuneClass(&typeMap, RUNE_ESCAPING_QUOTE, RUNETOKEN_ESCAPING_QUOTE) addRuneClass(&typeMap, RUNE_NONESCAPING_QUOTE, RUNETOKEN_NONESCAPING_QUOTE) addRuneClass(&typeMap, RUNE...
identifier_body
shlex.go
/* Copyright 2012 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
never equal another token. */ func (a *Token) Equal(b *Token) bool { if a == nil || b == nil { return false } if a.tokenType != b.tokenType { return false } return a.value == b.value } const ( RUNE_CHAR string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-,/@$*()+=><:;&^%~|...
random_line_split
shlex.go
/* Copyright 2012 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
(r io.Reader) (*Lexer, error) { tokenizer, err := NewTokenizer(r) if err != nil { return nil, err } lexer := &Lexer{tokenizer: tokenizer} return lexer, nil } /* Return the next word, and an error value. If there are no more words, the error will be io.EOF. */ func (l *Lexer) NextWord() (string, error) { var t...
NewLexer
identifier_name
shlex.go
/* Copyright 2012 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in ...
return subStrings, nil }
{ word, err := l.NextWord() if err != nil { if err == io.EOF { return subStrings, nil } return subStrings, err } subStrings = append(subStrings, word) }
conditional_block
mod.rs
mod console_tests; mod iterator; use std::borrow::Cow; use ansi_term::Style; use itertools::Itertools; use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; use iterator::{AnsiElementIterator, Element}; pub const ANSI_CSI_CLEAR_TO_EOL: &str = "\x1b[0K"; pub const ANSI_CSI_CLEAR_TO_BOL: ...
asure_text_width_osc_hyperlink_non_ascii() { assert_eq!(measure_text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/modバー.rs\x1b]8;;\x1b\\\x1b[0m"), measure_text_width("src/ansi/modバー.rs")); } #[test] fn test_parse_first_style() { let...
_text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/mod.rs\x1b]8;;\x1b\\\x1b[0m"), measure_text_width("src/ansi/mod.rs")); } #[test] fn test_me
identifier_body
mod.rs
mod console_tests; mod iterator; use std::borrow::Cow; use ansi_term::Style; use itertools::Itertools; use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; use iterator::{AnsiElementIterator, Element}; pub const ANSI_CSI_CLEAR_TO_EOL: &str = "\x1b[0K"; pub const ANSI_CSI_CLEAR_TO_BOL: ...
ure_text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/modバー.rs\x1b]8;;\x1b\\\x1b[0m"), measure_text_width("src/ansi/modバー.rs")); } #[test] fn test_parse_first_style() { let minus_line_from_unconfigured_git = "\x1b[31m-____\x1b[m\n"; ...
hyperlink_non_ascii() { assert_eq!(meas
identifier_name
mod.rs
mod console_tests; mod iterator; use std::borrow::Cow; use ansi_term::Style; use itertools::Itertools; use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; use iterator::{AnsiElementIterator, Element}; pub const ANSI_CSI_CLEAR_TO_EOL: &str = "\x1b[0K"; pub const ANSI_CSI_CLEAR_TO_BOL: ...
} Cow::from(format!("{result}{result_tail}")) } pub fn parse_style_sections(s: &str) -> Vec<(ansi_term::Style, &str)> { let mut sections = Vec::new(); let mut curr_style = Style::default(); for element in AnsiElementIterator::new(s) { match element { Element::Text(start, end) ...
{ result.push_str(t); }
conditional_block
mod.rs
mod console_tests; mod iterator; use std::borrow::Cow; use ansi_term::Style; use itertools::Itertools; use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; use iterator::{AnsiElementIterator, Element}; pub const ANSI_CSI_CLEAR_TO_EOL: &str = "\x1b[0K"; pub const ANSI_CSI_CLEAR_TO_BOL: ...
measure_text_width("src/ansi/mod.rs")); } #[test] fn test_measure_text_width_osc_hyperlink_non_ascii() { assert_eq!(measure_text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/modバー.rs\x1b]8;;\x1b\\\x1b[0m"), measure_text_w...
random_line_split
main.rs
#![no_std] #![no_main] #![feature(asm)] #![feature(collections)] extern crate stm32f7_discovery as stm32f7; extern crate collections; extern crate r0; pub mod plot; pub mod model; pub mod temp_sensor; pub mod time; pub mod util; pub mod pid; pub mod ramp; pub mod state_button; mod leak; use stm32f7::{system_clock,b...
let drag_color = Color::from_hex(0x000000); let grid_color = Color::from_hex(0x444444); // lcd controller let mut lcd = lcd::init(ltdc, rcc, &mut gpio); touch::check_family_id(&mut i2c_3).unwrap(); loop { SYSCLOCK.reset(); lcd.clear_screen(); lcd.set_background_color(Color::from_h...
gpio::Resistor::NoPull) .expect("Could not configure pwm pin"); let axis_color = Color::from_hex(0xffffff);
random_line_split
main.rs
#![no_std] #![no_main] #![feature(asm)] #![feature(collections)] extern crate stm32f7_discovery as stm32f7; extern crate collections; extern crate r0; pub mod plot; pub mod model; pub mod temp_sensor; pub mod time; pub mod util; pub mod pid; pub mod ramp; pub mod state_button; mod leak; use stm32f7::{system_clock,b...
(hw: board::Hardware) -> ! { let board::Hardware { rcc, pwr, flash, fmc, ltdc, gpio_a, gpio_b, gpio_c, gpio_d, gpio_e, gpio_f, gpio_g, gpio_h, gpio_i, gpio_j, gpio_k, spi_2, ...
main
identifier_name
main.rs
#![no_std] #![no_main] #![feature(asm)] #![feature(collections)] extern crate stm32f7_discovery as stm32f7; extern crate collections; extern crate r0; pub mod plot; pub mod model; pub mod temp_sensor; pub mod time; pub mod util; pub mod pid; pub mod ramp; pub mod state_button; mod leak; use stm32f7::{system_clock,b...
// WORKAROUND: rust compiler will inline & reorder fp instructions into #[inline(never)] // reset() before the FPU is initialized fn main(hw: board::Hardware) -> ! { let board::Hardware { rcc, pwr, flash, fmc, ltdc, gpio_a, ...
{ extern "C" { static __DATA_LOAD: u32; static __DATA_END: u32; static mut __DATA_START: u32; static mut __BSS_START: u32; static mut __BSS_END: u32; } let data_load = &__DATA_LOAD; let data_start = &mut __DATA_START; let data_end = &__DATA_END; let bss_s...
identifier_body
navtreeindex22.js
var NAVTREEINDEX22 = { "token-manufacturing_8h_source.htm":[4,0,71], "token-stack_8h.htm":[4,0,72], "token-stack_8h.htm#ga006255fff5ca38bbdfdb2989a565b178":[4,0,72,7], "token-stack_8h.htm#ga01aefbb730a37c874113d90b1a0f9af9":[4,0,72,32], "token-stack_8h.htm#ga022fc57c48683ed95b65884daa186bf2":[4,0,72,8], "token-stack_8h...
"zigbee-device-host_8h.htm#ga2f364bcec311543f51855d7409e31c10":[4,0,77,1], "zigbee-device-host_8h.htm#ga49488e5cefe8a5080dadef88b758b116":[4,0,77,2], "zigbee-device-host_8h.htm#ga82b8033689722e322fe47584188735b3":[4,0,77,3], "zigbee-device-host_8h.htm#gac234f5a3c0960f5deda51f70b8116282":[4,0,77,4], "zigbee-device-host_...
"zigbee-device-common_8h.htm#gaf8e641f05f5b8359571fa677ccb8c4b3":[4,0,76,0], "zigbee-device-common_8h_source.htm":[4,0,76], "zigbee-device-host_8h.htm":[4,0,77],
random_line_split
index.ts
import Chunk from '../Chunk'; import { optimizeChunks } from '../chunk-optimization'; import Graph from '../Graph'; import { createAddons } from '../utils/addons'; import { createAssetPluginHooks, finaliseAsset } from '../utils/assetHooks'; import commondir from '../utils/commondir'; import { Deprecation } from '../uti...
utOptions: InputOptions, plugin: Plugin) { if (plugin.options) return plugin.options(inputOptions) || inputOptions; return inputOptions; } function getInputOptions(rawInputOptions: GenericConfigObject): any { if (!rawInputOptions) { throw new Error('You must supply an options object to rollup'); } // inputOpti...
yOptionHook(inp
identifier_name
index.ts
import Chunk from '../Chunk'; import { optimizeChunks } from '../chunk-optimization'; import Graph from '../Graph'; import { createAddons } from '../utils/addons'; import { createAssetPluginHooks, finaliseAsset } from '../utils/assetHooks'; import commondir from '../utils/commondir'; import { Deprecation } from '../uti...
.then(addons => { // pre-render all chunks for (const chunk of chunks) { if (!inputOptions.experimentalPreserveModules) chunk.generateInternalExports(outputOptions); if (chunk.isEntryModuleFacade) chunk.exportMode = getExportMode(chunk, outputOptions); } ...
random_line_split
index.ts
import Chunk from '../Chunk'; import { optimizeChunks } from '../chunk-optimization'; import Graph from '../Graph'; import { createAddons } from '../utils/addons'; import { createAssetPluginHooks, finaliseAsset } from '../utils/assetHooks'; import commondir from '../utils/commondir'; import { Deprecation } from '../uti...
function checkInputOptions(options: InputOptions) { if (options.transform || options.load || options.resolveId || options.resolveExternal) { throw new Error( 'The `transform`, `load`, `resolveId` and `resolveExternal` options are deprecated in favour of a unified plugin API. See https://rollupjs.org/guide/en#plug...
{ const message = `The following options have been renamed — please update your config: ${deprecations .map(option => `${option.old} -> ${option.new}`) .join(', ')}`; warn({ code: 'DEPRECATED_OPTIONS', message, deprecations }); }
identifier_body
index.ts
import Chunk from '../Chunk'; import { optimizeChunks } from '../chunk-optimization'; import Graph from '../Graph'; import { createAddons } from '../utils/addons'; import { createAssetPluginHooks, finaliseAsset } from '../utils/assetHooks'; import commondir from '../utils/commondir'; import { Deprecation } from '../uti...
function checkOutputOptions(options: OutputOptions) { if (<string>options.format === 'es6') { error({ message: 'The `es6` output format is deprecated – use `es` instead', url: `https://rollupjs.org/guide/en#output-format-f-format` }); } if (!options.format) { error({ message: `You must specify outp...
throw new Error( 'The `transform`, `load`, `resolveId` and `resolveExternal` options are deprecated in favour of a unified plugin API. See https://rollupjs.org/guide/en#plugins' ); } }
conditional_block
model_probabilistic.py
#!/usr/bin/env python import os import pickle import numpy as np import tensorflow as tf import tensorflow_probability as tfp tf_bijs = tfp.bijectors tf_dist = tfp.distributions tf_mean_field = tfp.layers.default_mean_field_normal_fn #============================================================== class...
with self.sess.as_default(): output_scaled = [] for _ in range(self.NUM_SAMPLES): output_scaled.append(self.sess.run(self.net_out, feed_dict = {self.x_ph: input_scaled, self.is_training: False})) output_scaled = np.array(output_scaled) output_raw = self.get_raw_targets(output_scaled) output_raw_...
input_scaled = self.get_scaled_features(input_raw)
random_line_split
model_probabilistic.py
#!/usr/bin/env python import os import pickle import numpy as np import tensorflow as tf import tensorflow_probability as tfp tf_bijs = tfp.bijectors tf_dist = tfp.distributions tf_mean_field = tfp.layers.default_mean_field_normal_fn #============================================================== class...
return raw def set_hyperparameters(self, hyperparam_dict): for key, value in hyperparam_dict.items(): setattr(self, key, value) def construct_graph(self): act_funcs = { 'linear': lambda y: y, 'leaky_relu': lambda y: tf.nn.leaky_relu(y, 0.2), 'relu': lambda y: tf.nn.relu(y), 'so...
raw = targets
conditional_block
model_probabilistic.py
#!/usr/bin/env python import os import pickle import numpy as np import tensorflow as tf import tensorflow_probability as tfp tf_bijs = tfp.bijectors tf_dist = tfp.distributions tf_mean_field = tfp.layers.default_mean_field_normal_fn #============================================================== class...
def predict(self, input_raw): input_scaled = self.get_scaled_features(input_raw) with self.sess.as_default(): output_scaled = [] for _ in range(self.NUM_SAMPLES): output_scaled.append(self.sess.run(self.net_out, feed_dict = {self.x_ph: input_scaled, self.is_training: False})) output_scaled = np.a...
if not self.is_graph_constructed: self.construct_inference() self.sess = tf.compat.v1.Session(graph = self.graph) self.saver = tf.compat.v1.train.Saver() try: self.saver.restore(self.sess, model_path) return True except AttributeError: return False
identifier_body
model_probabilistic.py
#!/usr/bin/env python import os import pickle import numpy as np import tensorflow as tf import tensorflow_probability as tfp tf_bijs = tfp.bijectors tf_dist = tfp.distributions tf_mean_field = tfp.layers.default_mean_field_normal_fn #============================================================== class...
(self, graph, dataset_details, config, scope, batch_size, max_iter = 10**8): self.graph = graph self.scope = scope self.config = config self.batch_size = batch_size self.dataset_details = dataset_details self.max_iter = max_iter self.is_graph_constructed = False ...
__init__
identifier_name
walk.py
import os import platform import shutil from datetime import datetime from functools import reduce from hashlib import md5 from math import inf from multiprocessing import cpu_count from multiprocessing.pool import Pool from operator import itemgetter from pathlib import Path from looptools import Timer from dirutili...
(path_list): """Pool process file hashing.""" return pool_process(md5_tuple, path_list, 'MD5 hashing') def remover(file_path): """Delete a file or directory path only if it exists.""" if os.path.isfile(file_path): os.remove(file_path) return True elif os.path.isdir(file_path): ...
pool_hash
identifier_name
walk.py
import os import platform import shutil from datetime import datetime from functools import reduce from hashlib import md5 from math import inf from multiprocessing import cpu_count from multiprocessing.pool import Pool from operator import itemgetter from pathlib import Path from looptools import Timer from dirutili...
class DirPaths: def __init__(self, directory, full_paths=False, topdown=True, to_include=None, to_exclude=None, min_level=0, max_level=inf, filters=None, non_e...
"""Pool process file creation dates.""" return pool_process(creation_date_tuple, path_list, 'File creation dates')
identifier_body
walk.py
import os import platform import shutil from datetime import datetime from functools import reduce from hashlib import md5 from math import inf from multiprocessing import cpu_count from multiprocessing.pool import Pool from operator import itemgetter from pathlib import Path from looptools import Timer from dirutili...
else: self.filters = False self.console_output = console_output self.console_stream = console_stream self._hash_files = hash_files self._printer = Printer(console_output, console_stream).printer self._printer('DIRPATHS') # Check that parallelizatio...
self.filters = PathFilters(to_include, to_exclude, min_level, max_level, filters, non_empty_folders)
conditional_block
walk.py
import os import platform import shutil from datetime import datetime from functools import reduce from hashlib import md5 from math import inf from multiprocessing import cpu_count from multiprocessing.pool import Pool from operator import itemgetter from pathlib import Path from looptools import Timer from dirutili...
return str(self.tree_dict) @property def dict(self): return self.tree_dict def _filter(self, folders, folder_or_file): for index in range(0, len(folders)): filters = self.branches[index][folder_or_file] if filters: exclude = filters.get ...
def __iter__(self): return iter(self.tree_dict.items()) def __str__(self):
random_line_split
utils.py
import numpy as np import pandas as pd import tensorflow as tf from sklearn.preprocessing import OneHotEncoder from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import rankdata import time import logging logger = logging.getLogger(__name__) def plot_lear...
pred_proba_samples: array of predicted probability samples with shape (n_mc_samples, n_examples, n_classes)/(n_mc_samples, n_examples) for multiclass/binary classification. (This is the shape returned by BNN_Classifier.predict). labels: array of one-hot encoded labels with shape (n_examples, n_clas...
Get the sampled accuracies over the entire test set from logit samples. Args:
random_line_split
utils.py
import numpy as np import pandas as pd import tensorflow as tf from sklearn.preprocessing import OneHotEncoder from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import rankdata import time import logging logger = logging.getLogger(__name__) def plot_lear...
return roc_curve_df def load_mnist(fashion, onehot_encode=True, flatten_x=False, crop_x=0, classes=None): """ Load the MNIST dataset Args: onehot_encode: Boolean indicating whether to one-hot encode training and test labels (default True) flatten_x: Boolean indicating whether to flatten the training...
for repeat_idx in range(np.amax(variable_importances["repeat_idx"].unique()+1)): df = variable_importances.loc[ (variable_importances["method"]==method) & (variable_importances["repeat_idx"]==repeat_idx) & (variable_importances[...
conditional_block
utils.py
import numpy as np import pandas as pd import tensorflow as tf from sklearn.preprocessing import OneHotEncoder from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import rankdata import time import logging logger = logging.getLogger(__name__) def plot_lear...
(pvals, SNPs): """ Compute the power for identifying causal predictors. Args: Ps: list of causal predictors Output: matrix with dimension (num. predictors, 2), where columns are FPR, TPR """ nsnps = len(pvals) all_snps = np.arange(0, nsnps) pos = SNPs negs = list(set(all_snps) - set(SNPs)) pvals_rank = ran...
compute_power
identifier_name
utils.py
import numpy as np import pandas as pd import tensorflow as tf from sklearn.preprocessing import OneHotEncoder from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import rankdata import time import logging logger = logging.getLogger(__name__) def plot_lear...
if crop_x > 0: x_train = crop(x_train, crop_x) x_test = crop(x_test, crop_x) # Flatten to 2d arrays (each example 1d) def flatten_image(X): return X.reshape(X.shape[0], X.shape[1]*X.shape[1]) if flatten_x: x_train = flatten_image(x_train) x_test = flatten_image(x_test) if onehot_encode: y_train ...
assert crop_x < X.shape[1]/2 assert crop_x < X.shape[2]/2 return X[:,crop_size:-crop_size,crop_size:-crop_size]
identifier_body
analysis.py
import itertools import pandas as pd import pingouin as pg import numpy as np from scipy.stats import wilcoxon from sklearn.decomposition import PCA from sklearn.covariance import EllipticEnvelope def preprocess_data(users, blocks, trials): """ Clean data. :param users: Data from users table :type u...
return vectors def get_pca_vectors_by(dataframe, by=None): """ Get principal components for each group as vectors. Vectors can then be used to annotate graphs. :param dataframe: Data holding 'df1' and 'df2' values as columns. :type dataframe: pandas.DataFrame :param by: Column to group data...
v = row[['x', 'y']].values * np.sqrt(row['var_expl']) * 3 # Scale up for better visibility. mean = row[['meanx', 'meany']].values mean_offset = (mean, mean + v) vectors.append(mean_offset)
conditional_block
analysis.py
import itertools import pandas as pd import pingouin as pg import numpy as np from scipy.stats import wilcoxon from sklearn.decomposition import PCA from sklearn.covariance import EllipticEnvelope def preprocess_data(users, blocks, trials): """ Clean data. :param users: Data from users table :type u...
def posthoc_ttests(dataframe, var_='dVz'): """ Pairwise posthoc t-tests on a variable in a mixed design. Between factor is 'condition', within factor is 'block'. :param dataframe: Aggregated data containing Fisher-z-transformed synergy index in long format. :type dataframe: pandas.DataFrame :p...
" 3 x (3) Two-way split-plot ANOVA with between-factor condition and within-factor block. :param dataframe: Aggregated data containing Fisher-z-transformed synergy index. :type dataframe: pandas.DataFrame :return: mixed-design ANOVA results. :rtype: pandas.DataFrame """ if dataframe['condit...
identifier_body
analysis.py
import itertools import pandas as pd import pingouin as pg import numpy as np from scipy.stats import wilcoxon from sklearn.decomposition import PCA from sklearn.covariance import EllipticEnvelope def preprocess_data(users, blocks, trials): """ Clean data. :param users: Data from users table :type u...
/ variances[['parallel', 'orthogonal']].sum(axis='columns') except KeyError: synergy_indices = pd.DataFrame(columns=["dV", "dVz"]) else: dVz = 0.5 * np.log((n/d + dV)/(n/(n-d) - dV)) synergy_indices = pd.DataFrame({"dV": dV, "dVz": dVz}) return synergy_indices def get_...
try: dV = n * (variances['parallel']/(n-d) - variances['orthogonal']/d) \
random_line_split
analysis.py
import itertools import pandas as pd import pingouin as pg import numpy as np from scipy.stats import wilcoxon from sklearn.decomposition import PCA from sklearn.covariance import EllipticEnvelope def preprocess_data(users, blocks, trials): """ Clean data. :param users: Data from users table :type u...
(dataframe): """ Get principal components as vectors. Vectors can then be used to annotate graphs. :param dataframe: Tabular PCA data. :type dataframe: pandas.DataFrame :return: Principal components as vector pairs in input space with mean as origin first and offset second. :rtype: list """...
get_pca_vectors
identifier_name
system_information.rs
use crate::{SMBiosStruct, UndefinedStruct}; use serde::{ser::SerializeStruct, Serialize, Serializer}; use core::{ array::TryFromSliceError, convert::{TryFrom, TryInto}, fmt, ops::Deref, any }; #[cfg(feature = "no_std")] use alloc::{string::String, format}; /// # System Information (Type 1) /// /// ...
fn parts(&self) -> &'a UndefinedStruct { self.parts } } impl<'a> SMBiosSystemInformation<'a> { /// Manufacturer pub fn manufacturer(&self) -> Option<String> { self.parts.get_field_string(0x04) } /// Product name pub fn product_name(&self) -> Option<String> { self.pa...
Self { parts } }
identifier_body
system_information.rs
use crate::{SMBiosStruct, UndefinedStruct}; use serde::{ser::SerializeStruct, Serialize, Serializer}; use core::{ array::TryFromSliceError, convert::{TryFrom, TryInto}, fmt, ops::Deref, any }; #[cfg(feature = "no_std")] use alloc::{string::String, format}; /// # System Information (Type 1) /// /// ...
/// Raw value /// /// _raw_ is most useful when _value_ is None. /// This is most likely to occur when the standard was updated but /// this library code has not been updated to match the current /// standard. pub raw: u8, /// The contained [SystemWakeUpType] value pub value: SystemW...
/// # System - Wake-up Type Data pub struct SystemWakeUpTypeData {
random_line_split
system_information.rs
use crate::{SMBiosStruct, UndefinedStruct}; use serde::{ser::SerializeStruct, Serialize, Serializer}; use core::{ array::TryFromSliceError, convert::{TryFrom, TryInto}, fmt, ops::Deref, any }; #[cfg(feature = "no_std")] use alloc::{string::String, format}; /// # System Information (Type 1) /// /// ...
>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(format!("{}", self).as_str()) } } /// # System - Wake-up Type Data pub struct SystemWakeUpTypeData { /// Raw value /// /// _raw_ is most useful when _value_ is None. /// This i...
rialize<S
identifier_name
loader.rs
extern crate xml; use std; use std::fs::File; use std::path::{Path, PathBuf}; use std::ffi::OsStr; use std::io::{BufReader, Cursor, Read}; use std::sync::mpsc::Sender; use std::collections::HashMap; use zip::read::{ZipArchive, ZipFile}; use loader::xml::reader::{EventReader, XmlEvent}; use rodio::source::Source; ...
println!("Unknown song field {}", name.local_name); xml_skip_tag(&mut reader).unwrap(); State::Song(None) } }, XmlEvent::EndElement { .. } => { if song_rhythm.is_empty() { // TODO: be graceful panic!("Empty rhythm"); } let song = SongData { name: song_nam...
"buildup" => State::Song(Some(SongField::Buildup)), "buildupRhythm" => State::Song(Some(SongField::BuildupRhythm)), _ => {
random_line_split
loader.rs
extern crate xml; use std; use std::fs::File; use std::path::{Path, PathBuf}; use std::ffi::OsStr; use std::io::{BufReader, Cursor, Read}; use std::sync::mpsc::Sender; use std::collections::HashMap; use zip::read::{ZipArchive, ZipFile}; use loader::xml::reader::{EventReader, XmlEvent}; use rodio::source::Source; ...
{ pub info: PackInfo, pub images: Vec<ImageLoader>, pub songs: Vec<Song>, } pub struct ImageLoader { //data: SurfaceContext pub name: String, pub fullname: Option<String>, pub data: Surface, pub source: Option<String>, pub source_other: Option<String>, } pub struct SongData { pub name: String, pub title: ...
ResPack
identifier_name
lib.rs
/////////////////////////////////////////////////////////////////////////////// // // Copyright 2018-2021 Robonomics Network <research@robonomics.network> // // 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 cop...
( uri: &str, technics: &TechnicsFor<Runtime>, economics: &EconomicsFor<Runtime>, ) -> (AccountId32, MultiSignature) { let pair = sr25519::Pair::from_string(uri, None).unwrap(); let sender = <MultiSignature as Verify>::Signer::from(pair.public()).into_account(); let si...
get_params_proof
identifier_name
lib.rs
/////////////////////////////////////////////////////////////////////////////// // // Copyright 2018-2021 Robonomics Network <research@robonomics.network> // // 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 cop...
/// How to report of agreement execution. type Report: dispatch::Parameter + Report<Self::Index, Self::AccountId>; /// The overarching event type. type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>; } pub type TechnicsFor<T> = <<T as Config>:...
/// How to make and process agreement between two parties. type Agreement: dispatch::Parameter + Processing + Agreement<Self::AccountId>;
random_line_split
vrf.go
// // Copyright 2017-2019 Nippon Telegraph and Telephone Corporation. // // 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 requi...
// Forward inbound packets to L3 Tunnel fts := createFiveTuples(ra, t.local, t.IPProto(), PortRange{}) for i, ft := range fts { if err := v.router.connect(vif.Inbound(), Match5Tuple, ft); err != nil { vif.disconnect(MatchIPv4Dst, &ra[0]) for _, addedFt := range fts[0:i] { v.router.disconnect(Match5Tupl...
{ return fmt.Errorf("Adding a rule to %v failed for L3 tunnel: %v", vif, err) }
conditional_block
vrf.go
// // Copyright 2017-2019 Nippon Telegraph and Telephone Corporation. // // 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 requi...
(name string) *VRF { vrfMgr.mutex.Lock() defer vrfMgr.mutex.Unlock() return vrfMgr.byName[name] } // GetVRFByIndex returns a VRF with the given index. func GetVRFByIndex(index VRFIndex) *VRF { vrfMgr.mutex.Lock() defer vrfMgr.mutex.Unlock() return vrfMgr.byIndex[int(index)] }
GetVRFByName
identifier_name
vrf.go
// // Copyright 2017-2019 Nippon Telegraph and Telephone Corporation. // // 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 requi...
// should be called with lock held func (vm *vrfManager) releaseIndex(vrf *VRF) { vm.byIndex[int(vrf.index)] = nil } // NewVRF creates a VRF instance. func NewVRF(name string) (*VRF, error) { if !vrfMgr.re.MatchString(name) { return nil, fmt.Errorf("Invalid VRF name: '%v'", name) } vrfMgr.mutex.Lock() defer ...
{ // try from the nextIndex to the end if vm.findSlot(vrf, vm.nextIndex, len(vm.byIndex)) { return true } // try from the head to the nextIndex return vm.findSlot(vrf, 0, vm.nextIndex) }
identifier_body
vrf.go
// // Copyright 2017-2019 Nippon Telegraph and Telephone Corporation. // // 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 requi...
vif.disconnect(MatchIPv4Dst, &(t.RemoteAddresses()[0])) } func createVxLANs(remotes []net.IP, local net.IP, dstPort uint16, vni uint32) []*VxLAN { vxlans := make([]*VxLAN, len(remotes)) for i, remote := range remotes { vxlan := &VxLAN{ Src: remote, Dst: local, DstPort: dstPort, VNI: vni, ...
if t.Security() == SecurityIPSec { for _, nat := range createFiveTuples(t.remotes, t.local, IPP_UDP, PortRange{Start: 4500}) { v.router.disconnect(Match5Tuple, nat) } }
random_line_split
brush.rs
// Copyright © 2020 Cormac O'Brien. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish,...
let texture = state.create_texture(None, lightmap.width(), lightmap.height(), &lightmap_data); let id = self.lightmaps.len(); self.lightmaps.push(texture); //self.lightmap_views //.push(self.lightmaps[id].create_view(&Default::default())); ...
lightmap: Cow::Borrowed(lightmap.data()), });
random_line_split
brush.rs
// Copyright © 2020 Cormac O'Brien. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish,...
pub fn pipeline(&self) -> &wgpu::RenderPipeline { &self.pipeline } pub fn bind_group_layouts(&self) -> &[wgpu::BindGroupLayout] { &self.bind_group_layouts } pub fn bind_group_layout(&self, id: BindGroupLayoutId) -> &wgpu::BindGroupLayout { assert!(id as usize >= BindGroupL...
let layout_refs: Vec<_> = world_bind_group_layouts .iter() .chain(self.bind_group_layouts.iter()) .collect(); self.pipeline = BrushPipeline::recreate(device, compiler, &layout_refs, sample_count); }
identifier_body
brush.rs
// Copyright © 2020 Cormac O'Brien. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish,...
BspTextureKind::Static(bsp_tex) => { BrushTexture::Static(self.create_brush_texture_frame( state, bsp_tex.mipmap(BspTextureMipmap::Full), tex.width(), tex.height(), tex.name(), ...
let primary_frames: Vec<_> = primary .iter() .map(|f| { self.create_brush_texture_frame( state, f.mipmap(BspTextureMipmap::Full), width, ...
conditional_block
brush.rs
// Copyright © 2020 Cormac O'Brien. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish,...
&self) -> &[wgpu::BindGroupLayout] { &self.bind_group_layouts } pub fn bind_group_layout(&self, id: BindGroupLayoutId) -> &wgpu::BindGroupLayout { assert!(id as usize >= BindGroupLayoutId::PerTexture as usize); &self.bind_group_layouts[id as usize - BindGroupLayoutId::PerTexture as usiz...
ind_group_layouts(
identifier_name
glsl3.rs
use std::mem::size_of; use std::ptr; use crossfont::RasterizedGlyph; use log::info; use alacritty_terminal::term::cell::Flags; use crate::display::content::RenderableCell; use crate::display::SizeInfo; use crate::gl; use crate::gl::types::*; use crate::renderer::shader::{ShaderProgram, ShaderVersion}; use crate::ren...
unsafe { self.program.set_rendering_pass(RenderingPass::Background); gl::DrawElementsInstanced( gl::TRIANGLES, 6, gl::UNSIGNED_INT, ptr::null(), self.batch.len() as GLsizei, ); self....
{ unsafe { gl::BindTexture(gl::TEXTURE_2D, self.batch.tex()); } *self.active_tex = self.batch.tex(); }
conditional_block
glsl3.rs
use std::mem::size_of; use std::ptr; use crossfont::RasterizedGlyph; use log::info; use alacritty_terminal::term::cell::Flags; use crate::display::content::RenderableCell; use crate::display::SizeInfo; use crate::gl; use crate::gl::types::*; use crate::renderer::shader::{ShaderProgram, ShaderVersion}; use crate::ren...
impl TextShaderProgram { pub fn new(shader_version: ShaderVersion) -> Result<TextShaderProgram, Error> { let program = ShaderProgram::new(shader_version, None, TEXT_SHADER_V, TEXT_SHADER_F)?; Ok(Self { u_projection: program.get_uniform_location(cstr!("projection"))?, u_cell_...
/// Rendering is split into two passes; one for backgrounds, and one for text. u_rendering_pass: GLint, }
random_line_split
glsl3.rs
use std::mem::size_of; use std::ptr; use crossfont::RasterizedGlyph; use log::info; use alacritty_terminal::term::cell::Flags; use crate::display::content::RenderableCell; use crate::display::SizeInfo; use crate::gl; use crate::gl::types::*; use crate::renderer::shader::{ShaderProgram, ShaderVersion}; use crate::ren...
<'a> { active_tex: &'a mut GLuint, batch: &'a mut Batch, atlas: &'a mut Vec<Atlas>, current_atlas: &'a mut usize, program: &'a mut TextShaderProgram, } impl<'a> TextRenderApi<Batch> for RenderApi<'a> { fn batch(&mut self) -> &mut Batch { self.batch } fn render_batch(&mut self) ...
RenderApi
identifier_name
glsl3.rs
use std::mem::size_of; use std::ptr; use crossfont::RasterizedGlyph; use log::info; use alacritty_terminal::term::cell::Flags; use crate::display::content::RenderableCell; use crate::display::SizeInfo; use crate::gl; use crate::gl::types::*; use crate::renderer::shader::{ShaderProgram, ShaderVersion}; use crate::ren...
#[inline] pub fn capacity(&self) -> usize { BATCH_MAX } #[inline] pub fn size(&self) -> usize { self.len() * size_of::<InstanceData>() } pub fn clear(&mut self) { self.tex = 0; self.instances.clear(); } } /// Text drawing program. /// /// Uniforms are...
{ self.instances.len() }
identifier_body
service.rs
use crate::{ common::client::{ClientId, Credentials, Token}, coordinator, }; use bytes::Bytes; use derive_more::From; use futures::{ready, stream::Stream}; use std::{ collections::HashMap, error::Error, future::Future, pin::Pin, task::{Context, Poll}, }; use tarpc::context::current as rpc_co...
/// A future that orchestrates the entire aggregator service. // TODO: maybe add a HashSet or HashMap of clients who already // uploaded their weights to prevent a client from uploading weights // multiple times. Or we could just remove that ID from the // `allowed_ids` map. // TODO: maybe add a HashSet for clients th...
random_line_split
service.rs
use crate::{ common::client::{ClientId, Credentials, Token}, coordinator, }; use bytes::Bytes; use derive_more::From; use futures::{ready, stream::Stream}; use std::{ collections::HashMap, error::Error, future::Future, pin::Pin, task::{Context, Poll}, }; use tarpc::context::current as rpc_co...
} impl<A> ServiceHandle<A> where A: Aggregator + 'static, { pub fn new() -> (Self, ServiceRequests<A>) { let (upload_tx, upload_rx) = unbounded_channel::<UploadRequest>(); let (download_tx, download_rx) = unbounded_channel::<DownloadRequest>(); let (aggregate_tx, aggregate_rx) = unboun...
{ Self { upload: self.upload.clone(), download: self.download.clone(), aggregate: self.aggregate.clone(), select: self.select.clone(), } }
identifier_body
service.rs
use crate::{ common::client::{ClientId, Credentials, Token}, coordinator, }; use bytes::Bytes; use derive_more::From; use futures::{ready, stream::Stream}; use std::{ collections::HashMap, error::Error, future::Future, pin::Pin, task::{Context, Poll}, }; use tarpc::context::current as rpc_co...
(&mut self, request: SelectRequest<A>) { info!("handling select request"); let SelectRequest { credentials, response_tx, } = request; let (id, token) = credentials.into_parts(); self.allowed_ids.insert(id, token); if response_tx.send(Ok(())).is_err...
handle_select_request
identifier_name
service.rs
use crate::{ common::client::{ClientId, Credentials, Token}, coordinator, }; use bytes::Bytes; use derive_more::From; use futures::{ready, stream::Stream}; use std::{ collections::HashMap, error::Error, future::Future, pin::Pin, task::{Context, Poll}, }; use tarpc::context::current as rpc_co...
pin.poll_aggregation(cx); Poll::Pending } } pub struct ServiceRequests<A>(Pin<Box<dyn Stream<Item = Request<A>> + Send>>) where A: Aggregator; impl<A> Stream for ServiceRequests<A> where A: Aggregator, { type Item = Request<A>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Co...
{ return Poll::Ready(()); }
conditional_block
utils.py
from mpi4py import MPI import matplotlib from tmm import coh_tmm import pandas as pd import os from numpy import pi from scipy.interpolate import interp1d from joblib import Parallel, delayed import numpy as np import glob import matplotlib.pyplot as plt import pickle as pkl import seaborn as sns from scipy.optimize im...
class TMM_sim(): def __init__(self, mats=['Ge'], wavelength=np.arange(0.38, 0.805, 0.01), substrate='Cr', substrate_thick=500): ''' This class returns the spectrum given the designed structures. ''' self.mats = mats # include substrate self.all_mats = mats + [substr...
for i in range(len(progress)): print(progress[i], 0) progress[i] = ['|'.join([l + ' ' + str(d) + ' nm' for l, d in zip(progress[i][0], progress[i][1])]), progress[i][2]] return progress
identifier_body
utils.py
from mpi4py import MPI import matplotlib from tmm import coh_tmm import pandas as pd import os from numpy import pi from scipy.interpolate import interp1d from joblib import Parallel, delayed import numpy as np import glob import matplotlib.pyplot as plt import pickle as pkl import seaborn as sns from scipy.optimize im...
res = Parallel(n_jobs=num_workers)(delayed(spectrum)(args) for args in zip(names_list, thickness_list)) res = np.array(res) Rs, Ts, As = res[:, 0, :], res[:, 1, :], res[:, 2, :] return Rs, Ts, As def merge_layers(categorie...
random_line_split
utils.py
from mpi4py import MPI import matplotlib from tmm import coh_tmm import pandas as pd import os from numpy import pi from scipy.interpolate import interp1d from joblib import Parallel, delayed import numpy as np import glob import matplotlib.pyplot as plt import pickle as pkl import seaborn as sns from scipy.optimize im...
return progress class TMM_sim(): def __init__(self, mats=['Ge'], wavelength=np.arange(0.38, 0.805, 0.01), substrate='Cr', substrate_thick=500): ''' This class returns the spectrum given the designed structures. ''' self.mats = mats # include substrate self.all_...
print(progress[i], 0) progress[i] = ['|'.join([l + ' ' + str(d) + ' nm' for l, d in zip(progress[i][0], progress[i][1])]), progress[i][2]]
conditional_block
utils.py
from mpi4py import MPI import matplotlib from tmm import coh_tmm import pandas as pd import os from numpy import pi from scipy.interpolate import interp1d from joblib import Parallel, delayed import numpy as np import glob import matplotlib.pyplot as plt import pickle as pkl import seaborn as sns from scipy.optimize im...
(categories, thicknesses): ''' Merges consecutive layers with the same material types. ''' thicknesses = thicknesses[1:-1] c_output = [categories[0]] t_output = [thicknesses[0]] for i, (c, d) in enumerate(zip(categories[1:], thicknesses[1:])): if c == c_output[-1]: t_ou...
merge_layers
identifier_name