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 |
|---|---|---|---|---|
bastion_test.go | securityGroupSuffix = "-sg"
imageID = "m-gw8c603eae9ygxgt2ig6"
)
var myPublicIP = ""
var (
accessKeyID = flag.String("access-key-id", "", "Alicloud access key id")
accessKeySecret = flag.String("access-key-secret", "", "Alicloud access key secret")
region = flag.String("region", "", "Ali... | else {
return "", fmt.Errorf("not valid IPv4 address")
}
cidr := net.IPNet{
IP: ip,
Mask: mask,
}
full := cidr.String()
_, ipnet, _ := net.ParseCIDR(full)
return ipnet.String(), nil
}
func verifyPort22IsOpen(ctx context.Context, c client.Client, bastion *extensionsv1alpha1.Bastion) {
By("check conn... | {
mask = net.CIDRMask(24, 32) // use a /24 net for IPv4
} | conditional_block |
bastion_test.go | gress: []extensionsv1alpha1.BastionIngressPolicy{
{IPBlock: networkingv1.IPBlock{
CIDR: myPublicIP,
}},
},
},
}
options, err := bastionctrl.DetermineOptions(bastion, cluster)
Expect(err).NotTo(HaveOccurred())
return bastion, options
}
func prepareVPCandShootSecurityGroup(ctx context.Context, cl... | {
By("delete bastion")
Expect(client.IgnoreNotFound(c.Delete(ctx, bastion))).To(Succeed())
By("wait until bastion is deleted")
err := extensions.WaitUntilExtensionObjectDeleted(ctx, c, logger, bastion, extensionsv1alpha1.BastionResource, 20*time.Second, 15*time.Minute)
Expect(err).NotTo(HaveOccurred())
} | identifier_body | |
bastion_test.go | securityGroupSuffix = "-sg"
imageID = "m-gw8c603eae9ygxgt2ig6"
)
var myPublicIP = ""
var (
accessKeyID = flag.String("access-key-id", "", "Alicloud access key id")
accessKeySecret = flag.String("access-key-secret", "", "Alicloud access key secret")
region = flag.String("region", "", "Ali... | () (string, error) {
suffix, err := gardenerutils.GenerateRandomStringFromCharset(5, "0123456789abcdefghijklmnopqrstuvwxyz")
if err != nil {
return "", err
}
return suffix, nil
}
func getMyPublicIPWithMask() (string, error) {
resp, err := http.Get("https://api.ipify.org")
if err != nil {
return "", err
}
... | randomString | identifier_name |
bastion_test.go | Flags() {
if len(*accessKeyID) == 0 {
panic("need an Alicloud access key id")
}
if len(*accessKeySecret) == 0 {
panic("need an Alicloud access key secret")
}
if len(*region) == 0 {
panic("need an Alicloud region")
}
}
type infrastructureIdentifiers struct {
vpcID *string
vswitchID *stri... | },
}
cluster := &controller.Cluster{
ObjectMeta: metav1.ObjectMeta{Name: name}, | random_line_split | |
WarningAlarm.js | V;
loadHistory();
}
});*/
});
function setPumpName(name, id) {
$(".pumpName input").val(name);
$(".pumpName input").attr("data-id", id);
}
function setJzName(name, id) {
$(".machName input").val(name);
$(".machName input").attr("data-id", id);
}
function parseUrl() {
... |
$.ajax({
url: '/V_YCJK/SearchAlarm',
data: {
"pumpID": pumpId,
"pumpJZID": jzId,
"pageIndex": raPageIndex,
"pageSize": 5, //搜索是pageSize值无效
"StartDate": '2016-01-01',//startDate
"EndDate": '2017-05-09'//endDate
},
... | ty();
var str = '';
for (var i = 0; i < realAlarmData.length; i++) {
var tempStr = '<li data-id="' + realAlarmData[i].BaseID + '" data-fKey="' + realAlarmData[i].FKey + '">\
<div class="line1_box .clearfix">\
<p class="real_pumpName" data-id="P... | identifier_body |
WarningAlarm.js | V;
loadHistory();
}
});*/
});
function setPumpName(name, id) {
$(".pumpName input").val(name);
$(".pumpName input").attr("data-id", id);
}
function setJzName(name, id) {
$(".machName input").val(name);
$(".machName input").attr("data-id", id);
}
function parseUrl() {
... | _alarmList").empty();
var str = '';
for (var i = 0; i < realAlarmData.length; i++) {
var tempStr = '<li data-id="' + realAlarmData[i].BaseID + '" data-fKey="' + realAlarmData[i].FKey + '">\
<div class="line1_box .clearfix">\
<p class="real_pump... | {
$(".ul | identifier_name |
WarningAlarm.js | V;
loadHistory();
}
});*/
});
function setPumpName(name, id) {
$(".pumpName input").val(name);
$(".pumpName input").attr("data-id", id);
}
function setJzName(name, id) {
$(".machName input").val(name);
$(".machName input").attr("data-id", id);
}
function parseUrl() {
... | var i = url.indexOf('?');
if (i == -1) { return };
var queryStr = url.substr(i + 1);
var arr1 = queryStr.split('&');
var arr2 = {};
for (j in arr1) {
var tar = arr1[j].split('=');
arr2[tar[0]] = tar[1];
};
return arr2;
}
laydate({
elem: "#startTime",
format: "YYY... | random_line_split | |
WarningAlarm.js | V;
loadHistory();
}
});*/
});
function setPumpName(name, id) {
$(".pumpName input").val(name);
$(".pumpName input").attr("data-id", id);
}
function setJzName(name, id) {
$(".machName input").val(name);
$(".machName input").attr("data-id", id);
}
function parseUrl() {
... | complete: loadingMiss,
error: function (data) {
console.log('错误:' + data.responseText);
}
});
}
function loadingFunction() {
var $div = $('<div class="loading" style="position:absolute;left: 50%;top:50%;margin-left: -150px;margin-top: -70px;width: 300px;color:black;text-alig... | a);
}
scrollOnoff = true;
},
| conditional_block |
host_segfault.rs | std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
use wasmtime::*;
const VAR_NAME: &str = "__TEST_TO_RUN";
const CONFIRM: &str = "well at least we ran up to the crash";
fn segfault() -> ! {
unsafe {
println!("{}", CONFIRM);
io::stdout().flush().unwrap();
*(0x4 as *mut i32) = 3;... | desc.push_str(&stderr.replace("\n", "\n "));
}
if stack_overflow {
if is_stack_overflow(&output.status, &stderr) {
assert!(
stdout.trim().ends_with(CONFIRM),
"failed to find confirmation in test `{}`\n{}",
name,
desc... | random_line_split | |
host_segfault.rs | ::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
use wasmtime::*;
const VAR_NAME: &str = "__TEST_TO_RUN";
const CONFIRM: &str = "well at least we ran up to the crash";
fn segfault() -> ! {
unsafe {
println!("{}", CONFIRM);
io::stdout().flush().unwrap();
*(0x4 as *mut i32) = 3;
... |
#[cfg(unix)]
fn is_stack_overflow(status: &ExitStatus, stderr: &str) -> bool {
use std::os::unix::prelude::*;
// The main thread might overflow or it might be from a fiber stack (SIGSEGV/SIGBUS)
stderr.contains("has overflowed its stack")
|| match status.signal() {
Some(libc::SIGSEGV)... | {
use std::os::unix::prelude::*;
match status.signal() {
Some(libc::SIGSEGV) => true,
_ => false,
}
} | identifier_body |
host_segfault.rs | ::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
use wasmtime::*;
const VAR_NAME: &str = "__TEST_TO_RUN";
const CONFIRM: &str = "well at least we ran up to the crash";
fn segfault() -> ! {
unsafe {
println!("{}", CONFIRM);
io::stdout().flush().unwrap();
*(0x4 as *mut i32) = 3;
... |
}
#[cfg(unix)]
fn is_segfault(status: &ExitStatus) -> bool {
use std::os::unix::prelude::*;
match status.signal() {
Some(libc::SIGSEGV) => true,
_ => false,
}
}
#[cfg(unix)]
fn is_stack_overflow(status: &ExitStatus, stderr: &str) -> bool {
use std::os::unix::prelude::*;
// The m... | {
if is_segfault(&output.status) {
assert!(
stdout.trim().ends_with(CONFIRM) && stderr.is_empty(),
"failed to find confirmation in test `{}`\n{}",
name,
desc
);
} else {
panic!("\n\nexpected a segfault on... | conditional_block |
host_segfault.rs | ::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
use wasmtime::*;
const VAR_NAME: &str = "__TEST_TO_RUN";
const CONFIRM: &str = "well at least we ran up to the crash";
fn segfault() -> ! {
unsafe {
println!("{}", CONFIRM);
io::stdout().flush().unwrap();
*(0x4 as *mut i32) = 3;
... | (ptr: *const ()) {
assert_eq!(ptr as usize, 5);
}
}
fn main() {
if cfg!(miri) {
return;
}
// Skip this tests if it looks like we're in a cross-compiled situation and
// we're emulating this test for a different platform. In that scenario
// emulators (like QEMU) tend to not repo... | drop | identifier_name |
builtins.go | .Sprintf("The gopherbot install directory is: %s", installPath))
msg = append(msg, fmt.Sprintf("My home directory ($GOPHER_HOME) is: %s", homePath))
if custom, ok := os.LookupEnv("GOPHER_CUSTOM_REPOSITORY"); ok {
msg = append(msg, fmt.Sprintf("My git repository is: %s", custom))
}
}
msg = append(msg, f... |
if want_specific && !specific {
continue
}
Log(robot.Trace, "Checking help for plugin %s (term: %s)", task.name, term)
if !hasKeyword { // if you ask for help without a term, you just get help for whatever commands are available to you
for _, phelp := range plugin.Help {
for _, helptext := ran... | {
continue
} | conditional_block |
builtins.go | GOPHER_HOME) is: %s", homePath))
if custom, ok := os.LookupEnv("GOPHER_CUSTOM_REPOSITORY"); ok {
msg = append(msg, fmt.Sprintf("My git repository is: %s", custom))
}
}
msg = append(msg, fmt.Sprintf("My software version is: Gopherbot %s, commit: %s", botVersion.Version, botVersion.Commit))
msg = append(m... | logging | identifier_name | |
builtins.go | .Sprintf("The gopherbot install directory is: %s", installPath))
msg = append(msg, fmt.Sprintf("My home directory ($GOPHER_HOME) is: %s", homePath))
if custom, ok := os.LookupEnv("GOPHER_CUSTOM_REPOSITORY"); ok {
msg = append(msg, fmt.Sprintf("My git repository is: %s", custom))
}
}
msg = append(msg, f... | if args[0] == task.name {
if plugin == nil {
r.Say("Task '%s' is a job, not a plugin", task.name)
return
}
found = true
c, _ := yaml.Marshal(plugin)
r.Fixed().Say("%s", c)
}
}
if !found {
r.Say("Didn't find a plugin named " + args[0])
}
case "listplugins":
joiner := ", "
... | found := false
for _, t := range r.tasks.t[1:] {
task, plugin, _ := getTask(t) | random_line_split |
builtins.go | if command == "help" || command == "help-all" {
tasks := r.tasks
var term, helpOutput string
hasKeyword := false
lineSeparator := "\n\n"
if len(args) == 1 && len(args[0]) > 0 {
hasKeyword = true
term = args[0]
Log(robot.Trace, "Help requested for term '%s'", term)
}
// Nothing we need will eve... | {
r := m.(Robot)
switch command {
case "init":
return
case "level":
setLogLevel(logStrToLevel(args[0]))
r.Say("I've adjusted the log level to %s", args[0])
Log(robot.Info, "User %s changed logging level to %s", r.User, args[0])
case "show":
page := 0
if len(args) == 1 {
page, _ = strconv.Atoi(args[0... | identifier_body | |
server.go | err)
}
return c
}
// Server is a wrapper for docker's client.ContainerAPIClient which operates on a specific container.
type Server struct {
client.ContainerAPIClient
ContainerName, ContainerID string
}
// New creates a new craft server container and returns a docker client for it.
// It is the equivalent of th... | () (net.Conn, error) {
waiter, err := s.ContainerAttach(
context.Background(),
s.ContainerID,
docker.ContainerAttachOptions{
Stdin: true,
Stream: true,
},
)
if err != nil {
return nil, err
}
return waiter.Conn, err
}
// LogReader returns a buffer with the stdout and stderr from the running mc se... | CommandWriter | identifier_name |
server.go | err)
}
return c
}
// Server is a wrapper for docker's client.ContainerAPIClient which operates on a specific container.
type Server struct {
client.ContainerAPIClient
ContainerName, ContainerID string
}
// New creates a new craft server container and returns a docker client for it.
// It is the equivalent of th... | logger.Error.Panicf("while stopping %s another error occurred: %s\n", s.ContainerName, err)
}
}
// Command attaches to the container and runs the given arguments separated by spaces.
func (s *Server) Command(args []string) error {
conn, err := s.CommandWriter()
if err != nil {
return err
}
commandString := s... | if err != nil { | random_line_split |
server.go | err)
}
return c
}
// Server is a wrapper for docker's client.ContainerAPIClient which operates on a specific container.
type Server struct {
client.ContainerAPIClient
ContainerName, ContainerID string
}
// New creates a new craft server container and returns a docker client for it.
// It is the equivalent of th... | return nil, &NotCraftError{Name: containerName}
}
return &c, nil
}
// Stop executes a stop command first in the server process cli then on the container itself, stopping the
// server. The server must be saved separately to persist the world and settings.
func (s *Server) Stop() error {
if err := s.Command([]st... | {
id, err := containerID(containerName, cl)
if err != nil {
return nil, err
}
c := Server{
ContainerAPIClient: cl,
ContainerName: containerName,
ContainerID: id,
}
containerJSON, err := cl.ContainerInspect(context.Background(), c.ContainerID)
if err != nil {
return nil, fmt.Errorf("inspec... | identifier_body |
server.go | )
}
return c
}
// Server is a wrapper for docker's client.ContainerAPIClient which operates on a specific container.
type Server struct {
client.ContainerAPIClient
ContainerName, ContainerID string
}
// New creates a new craft server container and returns a docker client for it.
// It is the equivalent of the fo... |
portBinding := nat.PortMap{containerPort: []nat.PortBinding{hostBinding}}
var mounts []mount.Mount
if mountVolume {
volName := fmt.Sprintf("%s-%s", volumeLabel, name)
vol, err := c.VolumeCreate(ctx, volume.VolumeCreateBody{
Name: volName,
})
if err != nil {
return nil, fmt.Errorf("creating vol '%s':... | {
return nil, fmt.Errorf("creating container port: %s", err)
} | conditional_block |
common.js | dd;
break;
default:
return yyyy + "-" + mm + "-" + dd ;
break;
}
}
catch(e){
return("")
}
}
}
//页面跳转到另一个页面
function JumpUrl(url){
window.location.href=url;
}
//弹出窗口
function winO... | getUrlParam(name){
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r!=null)
{return decodeURIComponent(r[2]);}
else
{return ""; }
}
function Trim(ss)
{
// 用正则表达式将前后空格
// 用空字符串替代。
return ss.replace(/(^\s*)|(\s*$)/g, "... | nction | identifier_name |
common.js | dd;
break;
default:
return yyyy + "-" + mm + "-" + dd ;
break;
}
}
catch(e){
return("")
}
}
}
//页面跳转到另一个页面
function JumpUrl(url){
window.location.href=url;
}
//弹出窗口
function winO... | rn offset;
}
function getParent(el){
return el.parentNode ? el.parentNode : el.parentElement;
}
//登录情况下从公共平台跳转到会员管理平台,参数tourl 例如:要修改会员信息就传hqenmanger(CompanyInfo/MemberModify.aspx)
//CompanyInfo代表栏目,MemberModify.aspx代表文件
function hqenmanger(tourl)
{
window.open("/Web/Hqen/"+encodeURIComponent(to... | getLeft(e){
var offset=e.offsetLeft;
if(e.offsetParent!=null) offset+=getLeft(e.offsetParent);
retu | identifier_body |
common.js | dd;
break;
default:
return yyyy + "-" + mm + "-" + dd ;
break;
}
}
catch(e){
return("")
}
}
}
//页面跳转到另一个页面
function JumpUrl(url){
window.location.href=url;
}
//弹出窗口
function winO... | if(obj.value!=value){
return false;
}
obj.value="";
obj.className = cname;
}
function g_logout()
{
g_ibs("/Web/Hqen/Logout.aspx", false);
}
function HTMLEnCode(str)
{
var s = "";
if(str.length == 0)
{
return "";
}
s = str.re... | //input去掉默认内容还原编辑样式
function g_on_setvalue(obj,value,cname)
{ | random_line_split |
gateway-sia-cachelayer.go |
// Sys returns system interface
func (o SiaFileInfo) Sys() interface{} {
return o.FileSys
}
// newSiaCacheLayer creates a new Sia cache layer
func newSiaCacheLayer(siadAddress string, cacheDir string, dbFile string, debug bool) (*SiaCacheLayer, error) {
cache := &SiaCacheLayer{
SiadAddress: siadAddress,
... | {
return o.FileIsDir
} | identifier_body | |
gateway-sia-cachelayer.go | range buckets {
objects, err := cache.ListObjects(bucket.Name)
if err != nil {
return err
}
for _, object := range objects {
// Only remove an object from cache here if:
// 1. Object is cached
// 1. Object was uploaded over PurgeAfter seconds ago
// 2. Object hasn't been fetched in over PurgeAf... | {
cache.MaxCacheSizeBytes = i
} | conditional_block | |
gateway-sia-cachelayer.go | , srcFile, 1)
if err != nil {
return err
}
// Tell Sia daemon to upload the object
siaObj := cache.getSiaObjectName(bucket, objectName)
derr := post(cache.SiadAddress, "/renter/upload/"+siaObj, "source="+srcFile)
if derr != nil {
cache.dbDeleteObject(bucket, objectName)
return &SiaServiceError{Code: "SiaEr... | waitTillSiaUploadCompletes | identifier_name | |
gateway-sia-cachelayer.go | Layer{ | UploadCheckFreqMs: 3000,
MaxCacheSizeBytes: 10000000000,
CacheTicker: nil,
Db: nil,
DbMutex: &sync.Mutex{},
}
cache.loadSiaEnv()
return cache, nil
}
// Start will start running the Cache Layer
func (cache *SiaCacheLayer) Start() *SiaServiceError {
cache.debugmsg("SiaCache... | SiadAddress: siadAddress,
CacheDir: cacheDir,
DbFile: dbFile,
DebugMode: debug,
ManagerDelaySec: 30, | random_line_split |
basic_unet.py |
###########################################################
# Define parameters
###########################################################
DATA = 'processed_data'
TRAIN = 'train'
MASKS = 'masks'
TEST = 'test'
OUTPUT = 'output'
SEED = 'some'
ids = np.array([f'image_{i}.png' for i in range(1,31)])
#################... | for param_group in optimizer.param_groups:
print("LR", param_group['lr'])
model.train() # Set model to training mode
else:
model.eval() # Set model to evaluate mode
metrics = defaultdict(float)
... | if phase == 'train': | random_line_split |
basic_unet.py |
###########################################################
# Define parameters
###########################################################
DATA = 'processed_data'
TRAIN = 'train'
MASKS = 'masks'
TEST = 'test'
OUTPUT = 'output'
SEED = 'some'
ids = np.array([f'image_{i}.png' for i in range(1,31)])
#################... |
# statistics
epoch_samples += inputs.size(0)
print_metrics(metrics, epoch_samples, phase)
epoch_loss = metrics['loss'] / epoch_samples
# collect statistics for figure and take lr step
if phase == 'train':
... | loss.backward()
optimizer.step() | conditional_block |
basic_unet.py |
###########################################################
# Define parameters
###########################################################
DATA = 'processed_data'
TRAIN = 'train'
MASKS = 'masks'
TEST = 'test'
OUTPUT = 'output'
SEED = 'some'
ids = np.array([f'image_{i}.png' for i in range(1,31)])
#################... | (metrics, epoch_samples, phase):
outputs = []
for k in metrics.keys():
outputs.append("{}: {:4f}".format(k, metrics[k] / epoch_samples))
print("{}: {}".format(phase, ", ".join(outputs)))
###########################################################
# Define training
###################... | print_metrics | identifier_name |
basic_unet.py |
###########################################################
# Define parameters
###########################################################
DATA = 'processed_data'
TRAIN = 'train'
MASKS = 'masks'
TEST = 'test'
OUTPUT = 'output'
SEED = 'some'
ids = np.array([f'image_{i}.png' for i in range(1,31)])
#################... |
###########################################################
# Test if dataset load works
###########################################################
#ds = ISBI_Dataset(tfms = simulation.get_aug_train())
#dl = DataLoader(ds,batch_size=4)
#imgs,masks = next(iter(dl))
#print(imgs.shape, masks.shape)
#print(imgs.dtype, ... | fname = self.fnames[idx]
img = cv2.imread(os.path.join(DATA,TRAIN,fname), cv2.IMREAD_GRAYSCALE)
mask = cv2.imread(os.path.join(DATA,MASKS,fname),cv2.IMREAD_GRAYSCALE)
if self.tfms is not None:
augmented = self.tfms(image=img,mask=mask)
img,mask = augmented['image'],augme... | identifier_body |
shared.go | URL)
serviceRuntime = runtime.NewServiceRuntime(configStore, dns, hostIP)
apps, err := configStore.ListAssignments(env, pool)
if err != nil {
log.Fatalf("ERROR: Could not retrieve service configs for /%s/%s: %s", env, pool, err)
}
workerChans = make(map[string]chan string)
for _, app := range apps {
appCfg... | () {
pools, err := configStore.ListPools(env)
if err != nil {
log.Fatalf("ERROR: Could not check pools: %s", err)
}
if strings.TrimSpace(pool) == "" {
log.Fatalf("ERROR: Need a pool. Use '-pool <pool>'. Existing pools are: %s", strings.Join(pools, ","))
}
}
func pullImageAsync(appCfg config.App, errChan ch... | ensurePool | identifier_name |
shared.go | )
serviceRuntime = runtime.NewServiceRuntime(configStore, dns, hostIP)
apps, err := configStore.ListAssignments(env, pool)
if err != nil {
log.Fatalf("ERROR: Could not retrieve service configs for /%s/%s: %s", env, pool, err)
}
workerChans = make(map[string]chan string)
for _, app := range apps {
appCfg, e... |
func ensurePool() {
pools, err := configStore.ListPools(env)
if err != nil {
log.Fatalf("ERROR: Could not check pools: %s", err)
}
if strings.TrimSpace(pool) == "" {
log.Fatalf("ERROR: Need a pool. Use '-pool <pool>'. Existing pools are: %s", strings.Join(pools, ","))
}
}
func pullImageAsync(appCfg confi... | {
envs, err := configStore.ListEnvs()
if err != nil {
log.Fatalf("ERROR: Could not check envs: %s", err)
}
if strings.TrimSpace(env) == "" {
log.Fatalf("ERROR: Need an env. Use '-env <env>'. Existing envs are: %s.", strings.Join(envs, ","))
}
} | identifier_body |
shared.go | ; i < desired-running; i++ {
container, err := serviceRuntime.Start(env, pool, appCfg)
if err != nil {
log.Errorf("ERROR: Could not start containers: %s", err)
return
}
log.Printf("Started %s version %s as %s\n", appCfg.Name(), appCfg.Version(), container.ID[0:12])
err = serviceRuntime.StopOldVersion(... | err = json.Unmarshal(js, &envDump) | random_line_split | |
shared.go | )
serviceRuntime = runtime.NewServiceRuntime(configStore, dns, hostIP)
apps, err := configStore.ListAssignments(env, pool)
if err != nil {
log.Fatalf("ERROR: Could not retrieve service configs for /%s/%s: %s", env, pool, err)
}
workerChans = make(map[string]chan string)
for _, app := range apps {
appCfg, e... |
continue
}
startService(appCfg, logOnce)
}
if cmd == "restart" {
err := serviceRuntime.Stop(appCfg)
if err != nil {
log.Errorf("ERROR: Could not stop %s: %s",
appCfg.Version(), err)
if !loop {
return
}
startService(appCfg, logOnce)
continue
}
}
... | {
return
} | conditional_block |
board.rs | : usize,
// _creature_rank_metric: usize,
// Fields relevant for time or history
year: f64,
// Fields relevant for temperature
pub climate: Climate,
// Miscelanious
pub selected_creature: SelectedCreature<B>,
}
impl<B: NeuralNet + GenerateRandom> Default for Board<B> {
fn default() -... | {
i += 1;
} | conditional_block | |
board.rs | so, removes it by setting `self.0` to `None`.
pub fn unselect_if_dead(&mut self, creature: HLSoftBody<B>) {
if let Some(sel_creature) = &self.0 {
// If `creature` isn't the same as `self.selected_creature`.
if *sel_creature != creature {
// Then don't change to `None... | board.maintain_creature_minimum();
return board;
}
/// Maintains the creature minimum by adding random creatures until there are at least `self.creature_minimum` creatures.
///
/// # Processing equivalent
/// This function is the equivalent of *Board.pde/maintainCreatureMinimum* wi... | random_line_split | |
board.rs | ATURE_MINIMUM;
let min_temp = DEFAULT_MIN_TEMP;
let max_temp = DEFAULT_MAX_TEMP;
return Board::new_random(
board_size,
noise_step_size,
creature_minimum,
min_temp,
max_temp,
);
}
}
impl<B: NeuralNet> Board<B> {
pub fn ... | get_current_growth_rate | identifier_name | |
board.rs | _minimum: usize,
min_temp: f64,
max_temp: f64,
) -> Self {
let creatures = Vec::with_capacity(creature_minimum);
// Initialize climate.
let mut climate = Climate::new(min_temp, max_temp);
climate.update(0.0);
let mut board = Board {
board_width: ... | {
self.creature_minimum
} | identifier_body | |
stream.rs | _run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(unix)] {
/// use interprocess::os::unix::udsocket::UdStream;
/// use std::io::prelude::*;
///
/// let mut conn = UdStream::connect("/tmp/example1.sock")?;
/// conn.write_all(b"Hello from client!")?;
/// let mut string_buffer = String::new();
/... | if !success {
unsafe { return Err(handle_fd_error(socket)) };
}
unsafe { enable_passcred(socket).map_err(close_by_error(socket))? };
Ok(unsafe { Self::from_raw_fd(socket) })
}
/// Receives bytes from the socket stream.
///
/// # System calls
/// - `read`... | {
let addr = path.try_to::<sockaddr_un>()?;
let socket = {
let (success, fd) = unsafe {
let result = libc::socket(AF_UNIX, SOCK_STREAM, 0);
(result != -1, result)
};
if success {
fd
} else {
r... | identifier_body |
stream.rs | _run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(unix)] {
/// use interprocess::os::unix::udsocket::UdStream;
/// use std::io::prelude::*;
///
/// let mut conn = UdStream::connect("/tmp/example1.sock")?;
/// conn.write_all(b"Hello from client!")?;
/// let mut string_buffer = String::new();
/... | (&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
self.fd.read_vectored(bufs)
}
/// Receives both bytes and ancillary data from the socket stream.
///
/// The ancillary data buffer is automatically converted from the supplied value, if possible. For that reason, mutable slices of bytes... | recv_vectored | identifier_name |
stream.rs | _run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(unix)] {
/// use interprocess::os::unix::udsocket::UdStream;
/// use std::io::prelude::*;
///
/// let mut conn = UdStream::connect("/tmp/example1.sock")?;
/// conn.write_all(b"Hello from client!")?;
/// let mut string_buffer = String::new();
/... |
};
let success = unsafe {
libc::connect(
socket,
&addr as *const _ as *const _,
size_of::<sockaddr_un>() as u32,
)
} != 1;
if !success {
unsafe { return Err(handle_fd_error(socket)) };
}
... | {
return Err(io::Error::last_os_error());
} | conditional_block |
stream.rs | no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(unix)] {
/// use interprocess::os::unix::udsocket::UdStream;
/// use std::io::prelude::*;
/// | /// conn.read_to_string(&mut string_buffer)?;
/// println!("Server answered: {}", string_buffer);
/// # }
/// # Ok(()) }
/// ```
pub struct UdStream {
fd: FdOps,
}
impl UdStream {
/// Connects to a Unix domain socket server at the specified path.
///
/// See [`ToUdSocketPath`] for an example of using va... | /// let mut conn = UdStream::connect("/tmp/example1.sock")?;
/// conn.write_all(b"Hello from client!")?;
/// let mut string_buffer = String::new(); | random_line_split |
services.js |
return null;
}
};
})
.factory('listPesonel',function(){
var listData=[
[{src:"img/1200.png",title:"我的卡卷", count:"6张"},
{src:"img/1005.png",title:"积分商城", count:""},
{src:"img/10067.png",title:"我的积分", count:"110积分"},
{src:"img/1008.png",titl... | {
if (chats[i].id === parseInt(chatId)) {
return chats[i];
}
} | conditional_block | |
services.js | remove: function(chat) {
chats.splice(chats.indexOf(chat), 1);
},
get: function(chatId) {
for (var i = 0; i < chats.length; i++) {
if (chats[i].id === parseInt(chatId)) {
return chats[i];
}
}
return null;
}
};
})
.factory('listPesonel',function(){
... | all: function() {
return chats;
}, | random_line_split | |
olympics.py | participated in the given event. When used with -n, restricts the query to all athletes from a certain NOC who have also participated in the specified event. When used with -g, restricts the query to all medals won by an NOC in the specified event.'
year_help = 'Queries the olympics database for every athlete tha... | query += item + ', '
# Removes the last comma from the query string
query = query[:-2] + '\n'
query += 'FROM '
for item in tables:
query += item + ', '
# Removes the last comma from the query string
query = query[:-2] + '\n'
query += 'WHERE '
for item in ... | where_statements.append('cast(games.year AS TEXT) LIKE cast(\'{games_year}\' AS TEXT)')
if medal:
where_statements.append('medals.medal NOT LIKE \'NA\'')
for item in fields:
| random_line_split |
olympics.py | ():
'''
Gets arguments from command line.
'''
# Help descriptions for each argument and the argparser.
arg_parse_description = '''Finds information about the athletes registered under a specific NOC (National Olympic Committee), the athletes who have participated in a given event, the athle... | get_parsed_arguments | identifier_name | |
olympics.py | participated in the given event. When used with -n, restricts the query to all athletes from a certain NOC who have also participated in the specified event. When used with -g, restricts the query to all medals won by an NOC in the specified event.'
year_help = 'Queries the olympics database for every athlete tha... |
def run_golden_query(cursor, event_name='', games_year=0):
event = False
if event_name != '':
event = True
year = False
if games_year != 0:
year = True
query = form_golden_query(event, year)
try:
cursor.execute(query.format(event_name=event_name, games_... | noc = False
if noc_code != '':
noc = True
event = False
if event_name != '':
event = True
year = False
if games_year != 0:
year = True
query = form_variable_query(noc, event, medal, year)
try:
cursor.execute(query.format(noc_code=noc_code, eve... | identifier_body |
olympics.py | event. When used with -g, restricts the query to all medals won by an NOC in the specified event.'
year_help = 'Queries the olympics database for every athlete that participated in the given year. When used with -n, restricts the query to all athletes from a certain NOC who participated in the given year. When us... | print(' Events' + ' ' * (54) + 'Sports')
print('=' * 100) | conditional_block | |
dbgap.go | return t, nil
}
pub, err := x509.ParsePKCS1PublicKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("parsing public key: %v", err)
}
t.publicKey = pub
return t, nil
}
// TranslateToken implements the ga4gh.Translator interface.
func (s *DbGapTranslator) TranslateToken(ctx context.Context, auth string) (... | {
return nil, fmt.Errorf("sign org ClaimAffiliationAndRole claim failed: %s", err)
} | conditional_block | |
dbgap.go | _info.cgi?${TOKEN}"
dbGapPassportURL = "https://dbgap.ncbi.nlm.nih.gov/aa/jwt/user_passport.cgi?${TOKEN}"
eraCommonsAuthority = "eRA"
visaScope = "openid"
fixedKeyID = "kid"
)
// DbGapTranslator is a ga4gh.Translator that converts dbGap identities into GA4GH identities.
type DbGapTranslator s... | (publicKey, selfIssuer string, signer kms.Signer) (*DbGapTranslator, error) {
if len(selfIssuer) == 0 {
return nil, fmt.Errorf("NewDbGapTranslator failed, selfIssuer or signingPrivateKey is empty")
}
jku := strings.TrimSuffix(selfIssuer, "/") + "/.well-known/jwks.json"
t := &DbGapTranslator{
visaIssuer: selfI... | NewDbGapTranslator | identifier_name |
dbgap.go | _info.cgi?${TOKEN}"
dbGapPassportURL = "https://dbgap.ncbi.nlm.nih.gov/aa/jwt/user_passport.cgi?${TOKEN}"
eraCommonsAuthority = "eRA"
visaScope = "openid"
fixedKeyID = "kid"
)
// DbGapTranslator is a ga4gh.Translator that converts dbGap identities into GA4GH identities.
type DbGapTranslator s... | }
t.publicKey = pub
return t, nil
}
// TranslateToken implements the ga4gh.Translator interface.
func (s *DbGapTranslator) TranslateToken(ctx context.Context, auth string) (*ga4gh.Identity, error) {
if err := ga4gh.VerifyTokenWithKey(s.publicKey, auth); err != nil {
return nil, fmt.Errorf("verifying user token... | {
if len(selfIssuer) == 0 {
return nil, fmt.Errorf("NewDbGapTranslator failed, selfIssuer or signingPrivateKey is empty")
}
jku := strings.TrimSuffix(selfIssuer, "/") + "/.well-known/jwks.json"
t := &DbGapTranslator{
visaIssuer: selfIssuer,
visaJKU: jku,
signer: signer,
}
block, _ := pem.Decode(... | identifier_body |
dbgap.go | /user_info.cgi?${TOKEN}"
dbGapPassportURL = "https://dbgap.ncbi.nlm.nih.gov/aa/jwt/user_passport.cgi?${TOKEN}"
eraCommonsAuthority = "eRA"
visaScope = "openid"
fixedKeyID = "kid"
)
// DbGapTranslator is a ga4gh.Translator that converts dbGap identities into GA4GH identities.
type DbGapTransla... | }
// TranslateToken implements the ga4gh.Translator interface.
func (s *DbGapTranslator) TranslateToken(ctx context.Context, auth string) (*ga4gh.Identity, error) {
if err := ga4gh.VerifyTokenWithKey(s.publicKey, auth); err != nil {
return nil, fmt.Errorf("verifying user token signature: %v", err)
}
userInfo, err... | t.publicKey = pub
return t, nil | random_line_split |
HandView.py | game specific, and methods that help with that
are in HandManagement.py.
Player can arrange their own hand, and prepare to play cards during other players' turns.
"""
def __init__(self, controller, display, ruleset):
self.controller = controller
self.display = display
self.rule... |
def discardConfirmation(self, confirmed, wrapped_discards):
""" Confirm a user is sure about a discard and then perform it once confirmed."""
discards = []
for element in wrapped_discards:
discards.append(element.card)
if self.discards != discards:
confirmed... | """ gathers selected cards
in order to take action on selected cards (either discarding them or preparing them)
"""
self.selected_list = []
for element in self.hand_info:
if element.status == 1:
self.selected_list.append(element)
return self.selected_l... | identifier_body |
HandView.py | game specific, and methods that help with that
are in HandManagement.py.
Player can arrange their own hand, and prepare to play cards during other players' turns.
""" | self.Meld_Threshold = controller._state.rules.Meld_Threshold
self.deal_size = controller._state.rules.Deal_Size
self.help_text = controller._state.rules.help_text
if ruleset == 'Liverpool':
self.buttons_per_player = self.Meld_Threshold[0][0] + self.Meld_Threshold[0][1]
... | def __init__(self, controller, display, ruleset):
self.controller = controller
self.display = display
self.ruleset = ruleset | random_line_split |
HandView.py | game specific, and methods that help with that
are in HandManagement.py.
Player can arrange their own hand, and prepare to play cards during other players' turns.
"""
def | (self, controller, display, ruleset):
self.controller = controller
self.display = display
self.ruleset = ruleset
self.Meld_Threshold = controller._state.rules.Meld_Threshold
self.deal_size = controller._state.rules.Deal_Size
self.help_text = controller._state.rules.help_t... | __init__ | identifier_name |
HandView.py | game specific, and methods that help with that
are in HandManagement.py.
Player can arrange their own hand, and prepare to play cards during other players' turns.
"""
def __init__(self, controller, display, ruleset):
self.controller = controller
self.display = display
self.rule... |
elif self.event.type == pygame.MOUSEMOTION:
self.RuleSetsButtons.MouseHiLight(self, pos)
HandManagement.MouseHiLight(self.hand_info, pos)
elif self.event.type == pygame.KEYDOWN:
if self.controller._state.rules.Buy_Option:
if s... | self.RuleSetsButtons.ClickedButton(self, pos)
for element in self.hand_info:
# cannot select prepared cards, so not included in logic below.
if element.img_clickable.isOver(pos):
if element.status == 1:
element.s... | conditional_block |
ft_cityscapes.py | _fwavacc_0.91834.pth', # empty string denotes no snapshot
'snapshot':'epoch_42_loss_0.00916_acc_0.95598_acc-cls_0.58651_mean-iu_0.50990.pth',
'print_freq': 30,
'val_batch_size': 16,
'val_save_to_img_file': False,
'val_img_sample_rate': 0.05 # randomly sample some validation results to display
}
def init_weight... |
def parse_args():
parser = argparse.ArgumentParser(description='Games Semantic Segmentation FCN8')
parser.add_argument('--gpu', type=str, default='0,1', help='gpu id')
parser.add_argument('--epochs', type=int, default=50, help='number of rpochs to run')
parser.add_argument('--seed', type=int, default=47, help='s... | torch.nn.init.xavier_uniform_(m.weight.data)
# torch.nn.init.xavier_uniform(m.bias.data, 0)
nn.init.constant_(m.bias, 0) | conditional_block |
ft_cityscapes.py | _fwavacc_0.91834.pth', # empty string denotes no snapshot
'snapshot':'epoch_42_loss_0.00916_acc_0.95598_acc-cls_0.58651_mean-iu_0.50990.pth',
'print_freq': 30,
'val_batch_size': 16,
'val_save_to_img_file': False,
'val_img_sample_rate': 0.05 # randomly sample some validation results to display
}
def init_weight... |
mean_std = ([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
# train_transforms = transforms.Compose([
# transforms.RandomCrop(args['crop_size']),
# transforms.RandomRotation(90),
# transforms.RandomHorizontalFlip(p=0.5),
# transforms.RandomVerticalFlip(p=0.5),
# ])
short_size = int(min(args['input_size']... | torch.backends.cudnn.benchmark = True
os.environ["CUDA_VISIBLE_DEVICES"] = '0,1'
device = torch.device('cuda:0' if torch.cuda.is_available() else "cpu")
# # if args.seed:
# random.seed(args.seed)
# np.random.seed(args.seed)
# torch.manual_seed(args.seed)
# # if args.gpu:
# torch.cuda.manual_seed_all(args.s... | identifier_body |
ft_cityscapes.py | _fwavacc_0.91834.pth', # empty string denotes no snapshot
'snapshot':'epoch_42_loss_0.00916_acc_0.95598_acc-cls_0.58651_mean-iu_0.50990.pth',
'print_freq': 30,
'val_batch_size': 16,
'val_save_to_img_file': False,
'val_img_sample_rate': 0.05 # randomly sample some validation results to display
}
def init_weight... | curr_iter = (epoch - 1) * len(train_loader)
targets_all, preds_all = [], []
for i, data in enumerate(train_loader):
inputs, targets = data
assert inputs.size()[2:] == targets.size()[1:]
N = inputs.size(0)
inputs, targets = inputs.to(device), targets.to(device)
optimizer.zero_grad()
outputs = net(inp... | net.train()
train_loss = AverageMeter() | random_line_split |
ft_cityscapes.py | _fwavacc_0.91834.pth', # empty string denotes no snapshot
'snapshot':'epoch_42_loss_0.00916_acc_0.95598_acc-cls_0.58651_mean-iu_0.50990.pth',
'print_freq': 30,
'val_batch_size': 16,
'val_save_to_img_file': False,
'val_img_sample_rate': 0.05 # randomly sample some validation results to display
}
def init_weight... | (train_loader, net, device, criterion, optimizer, epoch, train_args):
net.train()
train_loss = AverageMeter()
curr_iter = (epoch - 1) * len(train_loader)
targets_all, preds_all = [], []
for i, data in enumerate(train_loader):
inputs, targets = data
assert inputs.size()[2:] == targets.size()[1:]
N = input... | train | identifier_name |
load_csv.py | iterrows return a row object to access column names for each row
import csv
import os
import datetime
def euro(number):
return f'{number:.2f} €'.replace('.',',')
def date_s(date):
# accepts datetime, returns formatted string
return str(date.strftime("%d.%m.%Y"))
def convert_to_date... | elif head and column_names:
# TODO: check if len of column names is compatible
self.columns = list(column_names)
file_data = file_data[1:]
for col in self.columns:
self.data[col] = []
elif not head and column_names:
self.... | self.data[col] = []
| random_line_split |
load_csv.py | iterrows return a row object to access column names for each row
import csv
import os
import datetime
def euro(number):
return f'{number:.2f} €'.replace('.',',')
def date_s(date):
# accepts datetime, returns formatted string
return str(date.strftime("%d.%m.%Y"))
def convert_to_date... |
def read_csv(self, filename, head=True, column_names=[],
decimal=',', parse_dates=[], date_parser=None):
# make an array to store the csv data with shape (rows, columns)
if not os.path.isfile(filename):
print(f'Error: "{filename}" does not exist.')
r... | th open(filename, 'w+', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=sep)
if head:
writer.writerow(self.columns)
for i, row in self.iterrows():
str_row = [str(r).replace('.', decimal) for r in row]
writer.writero... | identifier_body |
load_csv.py | iterrows return a row object to access column names for each row
import csv
import os
import datetime
def euro(number):
return f'{number:.2f} €'.replace('.',',')
def date_s(date):
# accepts datetime, returns formatted string
return str(date.strftime("%d.%m.%Y"))
def convert_to_date... | else:
for i in range(len(file_data[0])):
self.columns.append(str(i))
self.data[str(i)] = []
for i, row in enumerate(file_data):
for j, col in enumerate(row):
# check if data is boolean
... | lf.columns = list(column_names)
for col in self.columns:
self.data[col] = []
| conditional_block |
load_csv.py | iterrows return a row object to access column names for each row
import csv
import os
import datetime
def euro(number):
return f'{number:.2f} €'.replace('.',',')
def date_s(date):
# accepts datetime, returns formatted string
return str(date.strftime("%d.%m.%Y"))
def convert_to_date... | elf, by=None, reverse=False):
'''
sorts the rows
"by" has to be a column name
'''
#temp_data = list(self.iterrows())
temp_data = [list(row) for i, row in self.iterrows()]
#print(temp_data)
if not by or by not in self.columns:
i = 0
... | rt(s | identifier_name |
client.rs | {
std::fs::create_dir(&workSpace)?;
}
let basic_auth = BasicAuth {
user: RpcUsername.to_string(),
password: RpcPassword.to_string(),
};
let res = container
.post("https://u2.dmhy.org/getrss.php")
... |
pub async fn getUserInfo(&self) -> Result<UserInfo> {
let context = self
.get(format!(
"https://u2.dmhy.org/userdetails.php?id={}",
self.uid
))
.await?;
let username = Document::from(context.as_str())
.find(Name("a"))... | {
let mut torrent = self.getWorkingTorrent().await?;
torrent.torrents.sort_by_key(|x| {
(
x.peers_getting_from_us.unwrap_or(0),
x.added_date.unwrap_or(0),
)
});
Ok(torrent.torrents.into_iter().take(5).collect())
} | identifier_body |
client.rs | 历史]")?;
let shareRate = U2client::matchRegex(&t, "分享率:[' ']*([0-9.]+)")?;
let upload = U2client::matchRegex(&t, "上传量:[' ']*([0-9.' ']+[TGMK]iB)")?;
let download = U2client::matchRegex(&t, "下载量:[' ']*([0-9.' ']+[TGMK]iB)")?;
let actualUpload = U2client::matchRegex(&t, "实际上传:[' ']*([0-9.' ... | e("td"))
| identifier_name | |
client.rs | .get("https://u2.dmhy.org/index.php")
.send()
.await?;
if x.url().path() == "/index.php" {
let context = x.text().await?;
let uid = Document::from(context.as_str())
.find(Name("a"))
.filter(|x| match x.attr("class") {
... | let x = container | random_line_split | |
main.py | .cached_property
def auth(self):
"""Shortcut to access the auth instance as a property."""
return auth.get_auth()
@webapp2.cached_property
def user_info(self):
"""Shortcut to access a subset of the user attributes that are stored
in the session.
The list of attributes to store in the session... | self._serve_page(failed)
def _serve_page(self, failed=False):
params = {
'failed': failed
}
self.render_template('tip.html', params)
def serve_profile_page(self):
user = self.user
params = {
'auth_id': user.auth_ids[0],
'first_name': user.name,
'last_name': user.last_name,
... | try:
tip.tip(user, tipReceiver, amount)
except:
failed=True
| random_line_split |
main.py | .cached_property
def auth(self):
"""Shortcut to access the auth instance as a property."""
return auth.get_auth()
@webapp2.cached_property
def user_info(self):
"""Shortcut to access a subset of the user attributes that are stored
in the session.
The list of attributes to store in the session... |
user_id = user.get_id()
token = self.user_model.create_signup_token(user_id)
verification_url = self.uri_for('verification', type='p', user_id=user_id,
signup_token=token, _full=True)
msg = 'Send an email to user in order to reset their password. \
They will be able to do so by visit... | logging.info('Could not find any user entry for username %s', username)
self._serve_page(not_found=True)
return | conditional_block |
main.py | .cached_property
def auth(self):
"""Shortcut to access the auth instance as a property."""
return auth.get_auth()
@webapp2.cached_property
def user_info(self):
"""Shortcut to access a subset of the user attributes that are stored
in the session.
The list of attributes to store in the session... | (self):
password = self.request.get('password')
old_token = self.request.get('t')
if not password or password != self.request.get('confirm_password'):
self.display_message('passwords do not match')
return
user = self.user
user.set_password(password)
user.put()
# remove signup ... | post | identifier_name |
main.py | .cached_property
def auth(self):
"""Shortcut to access the auth instance as a property."""
return auth.get_auth()
@webapp2.cached_property
def user_info(self):
"""Shortcut to access a subset of the user attributes that are stored
in the session.
The list of attributes to store in the session... |
self.display_message(msg.format(url=verification_url))
def _serve_page(self, not_found=False):
username = self.request.get('username')
params = {
'username': username,
'not_found': not_found
}
self.render_template('forgot.html', params)
class VerificationHandler(BaseHandler):
... | def get(self):
self._serve_page()
def post(self):
username = self.request.get('username')
user = self.user_model.get_by_auth_id(username)
if not user:
logging.info('Could not find any user entry for username %s', username)
self._serve_page(not_found=True)
return
user_id = user... | identifier_body |
tiles.rs | ylen: PosUnit,
}
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct MapChunk {
pub tiles: Tiles,
pub pos: Pos,
pub xlen: PosUnit,
pub ylen: PosUnit,
pub zlen: PosUnit,
}
pub fn init_map(root: &Path) -> Map {
info!("Initializing map");
let test_path = root.join("static/i... |
pub fn get_chunk(&self, pos: Pos, size: Pos) -> MapChunk {
let (x0, y0, z0) = pos;
let (xlen, ylen, zlen) = size;
let mut tiles = Tiles::new();
for x in x0..(x0 + xlen) {
for y in y0..(y0 + ylen) {
for z in z0..(z0 + zlen) {
let ind... | {
let (x, y, z) = pos;
self.tiles = vec![AIR_TILE; (x * y * z) as usize];
self.xlen = x;
self.ylen = y;
self.zlen = z;
} | identifier_body |
tiles.rs | ylen: PosUnit,
}
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct MapChunk {
pub tiles: Tiles,
pub pos: Pos,
pub xlen: PosUnit,
pub ylen: PosUnit,
pub zlen: PosUnit,
}
pub fn init_map(root: &Path) -> Map {
info!("Initializing map");
let test_path = root.join("static/i... | let zlen = min(CHUNK_TILES_Z, self.zlen - dz * CHUNK_TILES_Z);
let size = (xlen, ylen, zlen);
chunks.push(self.get_chunk(pos, size))
}
}
}
chunks
}
fn get_num_chunks(map_len: PosUnit, chunk_len: PosUnit) -... | let z = dz * CHUNK_TILES_Z;
let pos = (x, y, z);
let xlen = min(CHUNK_TILES_X, self.xlen - dx * CHUNK_TILES_X);
let ylen = min(CHUNK_TILES_Y, self.ylen - dy * CHUNK_TILES_Y); | random_line_split |
tiles.rs | ylen: PosUnit,
}
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct | {
pub tiles: Tiles,
pub pos: Pos,
pub xlen: PosUnit,
pub ylen: PosUnit,
pub zlen: PosUnit,
}
pub fn init_map(root: &Path) -> Map {
info!("Initializing map");
let test_path = root.join("static/inc/maps/smol_map_excel.sfm.csv");
let path_str = test_path
.to_str()
... | MapChunk | identifier_name |
rotas.component.ts | title: c.rota.nome+' - '+c.nome
});
if (c.rota.img != 'semRota') {
var image = {
url: '../../assets/img/' + c.rota.img + '.png',
// The anchor for this image is the base of the flagpole at (0, 32).
anchor: new google.maps.Point(0, 16),
// This marker is 20 p... |
var cliLatLng = new google.maps.LatLng(parseFloat(cli.latitude), parseFloat(cli.longitude));
if (google.maps.geometry.poly.containsLocation(cliLatLng, this.selectedOverlay) === true) {
cli.checked = true;
//console.log('qtd clientesSelec ****'+this.clientesSelec.length);
... | random_line_split | |
rotas.component.ts | (let cli of this.clientesSelec) {
console.log('Nome: ' + cli.nome + ' checked? ' + cli.checked);
}
this.larguraMapa = '8';
this.ativarAutalizacaoCliente = false;
this.ativarCriacaoRotaClientes = true;
}
/**
laço de repedicao usado para idt clientes q nao foram
marcados no mapa mas vi... | dCli() { // right | identifier_name | |
rotas.component.ts | : c.rota.nome+' - '+c.nome
});
if (c.rota.img != 'semRota') {
var image = {
url: '../../assets/img/' + c.rota.img + '.png',
// The anchor for this image is the base of the flagpole at (0, 32).
anchor: new google.maps.Point(0, 16),
// This marker is 20 pixels ... | } else {
var cliLatLng = new google.maps.LatLng(parseFloat(cli.latitude), parseFloat(cli.longitude));
if (google.maps.geometry.poly.containsLocation(cliLatLng, this.selectedOverlay) === true) {
cli.checked = true;
//console.log('qtd clientesSelec ****'+this.client... | cli.checked = true;
//console.log('qtd clientesSelec ****'+this.clientesSelec.length);
var encontrado = false;
//laco for para testar no momento de faze varios poligonos no mapa
//nao sera colocado mais de 1x o cliente na lista
for (let client of this.clientesSe... | conditional_block |
main.js | fully support the CSS solution
else {
if (EdgeCheck) console.log("Smooth scrolling enabled on Edge, but might not work as smooth as possible due to some limitations, for ex. links with # will probably not scroll smoothly!");
else console.log("Smooth scrolling enabled but might not work properly ... |
document.addEventListener('scroll', () => {
startForm();
});
/* Toggle contact methods dropdown */
let connectBtn = $('#contact-methods .contact-methods-container h3');
let connectList = $('#contact-methods .contact-methods-container .contact-methods-list');
connectBtn.on('clic... | {
if(startedForm == 0) {
// $('.contact-content-container').html('<div data-tf-widget="zdz53C" data-tf-opacity="100" data-tf-iframe-props="title=Contact Form Submission" data-tf-transitive-search-params data-tf-medium="snippet" style="width:100%;height:600px;"></div>');
// $('.contact... | identifier_body |
main.js | not fully support the CSS solution
else {
if (EdgeCheck) console.log("Smooth scrolling enabled on Edge, but might not work as smooth as possible due to some limitations, for ex. links with # will probably not scroll smoothly!");
else console.log("Smooth scrolling enabled but might not work prope... | () {
if(startedForm == 0) {
// $('.contact-content-container').html('<div data-tf-widget="zdz53C" data-tf-opacity="100" data-tf-iframe-props="title=Contact Form Submission" data-tf-transitive-search-params data-tf-medium="snippet" style="width:100%;height:600px;"></div>');
// $('.cont... | startForm | identifier_name |
main.js | not fully support the CSS solution
else {
if (EdgeCheck) console.log("Smooth scrolling enabled on Edge, but might not work as smooth as possible due to some limitations, for ex. links with # will probably not scroll smoothly!");
else console.log("Smooth scrolling enabled but might not work prope... | connectBtn.on('click', function() {
if ( $(connectList).css('display') === 'none' ) {
$(connectBtn).addClass('connectListToggled');
$(connectList).css('display', 'inline-block');
} else {
$(connectBtn).removeClass('connectListToggled');
$(connect... | random_line_split | |
main.js | fully support the CSS solution
else {
if (EdgeCheck) console.log("Smooth scrolling enabled on Edge, but might not work as smooth as possible due to some limitations, for ex. links with # will probably not scroll smoothly!");
else console.log("Smooth scrolling enabled but might not work properly ... |
if ( clickCounter >= 35 ) { $('.easter-egg-container p').text('I would get bored at this point but go on champ \u{1f64c}'); }
if ( clickCounter >= 50 ) { $('.easter-egg-container p').text('Meh, continue I guess'); }
if ( clickCounter >= 65 ) { $('.easter-egg-container p').text('The person in... | { $('.easter-egg-container p').text('Does this look fun to you?'); } | conditional_block |
finetuning.py | kriz/cifar-100-python.tar.gz"
filename = "cifar-100-python.tar.gz"
tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85'
train_list = [
['train', '16019d7e3df5f24257cddd939b257f8d'],
]
test_list = [
['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc'],
]
meta = {
'filename': 'meta',
... |
def forward(self, x, toExtract=False):
x = self.net(x, toExtract)
return x
@torch.no_grad()
def classify(self,images):
self.net.train(False)
_, preds=torch.max(self.forward(images,False), dim=1)
mapped=[]
for pred in preds:
mapped.append(list(self.dic.keys())[list(self.dic.val... | super(iCaRLNet, self).__init__()
self.net = resnet32()
self.n_classes = 0
self.n_known = 0
self.classes_known=[]
self.new_classes=[]
self.dic={}
self.count_per_dic=0
self.loss=BCEWithLogitsLoss() | identifier_body |
finetuning.py | _names',
'md5': '7973b15100ade9c7d40fb424638fde48',
}
"""**MODEL**"""
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
... | print(f"In test {lista_tot}")
train_set = iCIFAR100(root='./data',train=True,classes=list_classes[s],download=True,transform=transform_train)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=128,shuffle=True, num_workers=2) | random_line_split | |
finetuning.py | iz/cifar-100-python.tar.gz"
filename = "cifar-100-python.tar.gz"
tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85'
train_list = [
['train', '16019d7e3df5f24257cddd939b257f8d'],
]
test_list = [
['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc'],
]
meta = {
'filename': 'meta',
... | (self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
... | forward | identifier_name |
finetuning.py |
return index, img, target
def __len__(self):
return len(self.data)
def get_image_class(self, label):
return self.data[np.array(self.targets) == label]
def append(self, images, labels):
self.data = np.concatenate((self.data, images), axis=0)
self.targets = self.targets + labels
class ... | target = self.target_transform(target) | conditional_block | |
produce_evaluation.py | , ax = plt.subplots()
ax.set_xscale('log')
methods = results.opf_method.unique()
min_val = np.min(results.time_taken)
max_val = np.max(results.time_taken)
n_bins = 100
# bin_lims = np.linspace(min_val, max_val, n_bins + 1)
bin_lims = np.logspace(np.log10(min_val), np.log10(max_val), n_bins... |
return np.percentile(x, n)
percentile_.__name__ = 'percentile_%s' % n
return percentile_
def statistical_summary(results, filter_by_solved):
group_by = ["opf_method"]
if filter_by_solved:
results = results[results["solved"] == 1]
grouped_results = results.groupby(group_by)
agg_... | entile_(x): | identifier_name |
produce_evaluation.py | , ax = plt.subplots()
ax.set_xscale('log')
methods = results.opf_method.unique()
min_val = np.min(results.time_taken)
max_val = np.max(results.time_taken)
n_bins = 100
# bin_lims = np.linspace(min_val, max_val, n_bins + 1)
bin_lims = np.logspace(np.log10(min_val), np.log10(max_val), n_bins... |
d
ef main(results_file, base_csv=None, take_from_base=None):
pp = pprint.PrettyPrinter(indent=4)
results = pd.read_csv(results_file)
| f_results = results[results.opf_method == "ac_opf"]
model_ac_opf_results = results[results.opf_method == "model_ac_opf"]
dcacopf_results = results[results.opf_method == "dcac_opf"]
for scen in acopf_results.scenario_id.unique():
acopf = acopf_results[acopf_results.scenario_id == scen]
modela... | identifier_body |
produce_evaluation.py | format(hours)
d["M"] = '{:02d}'.format(minutes)
d["S"] = '{:02d}'.format(seconds)
t = DeltaTemplate(fmt)
return t.substitute(**d)
def format_time(seconds):
time = datetime.timedelta(seconds=seconds)
if seconds == 0:
return "< 1s"
if seconds < 60:
return str(seconds) + "s"
... | parser = ArgumentParser() | random_line_split | |
produce_evaluation.py | fig, ax = plt.subplots()
ax.set_xscale('log')
methods = results.opf_method.unique()
min_val = np.min(results.time_taken)
max_val = np.max(results.time_taken)
n_bins = 100
# bin_lims = np.linspace(min_val, max_val, n_bins + 1)
bin_lims = np.logspace(np.log10(min_val), np.log10(max_val), n_... | fig.savefig("./relative_runtimes.svg", bbox_inches='tight')
fig.savefig("./relative_runtimes.pdf", bbox_inches='tight')
fig.savefig("./relative_runtimes.png", dpi=200, bbox_inches='tight')
return fig
def solved_in_n_seconds(n_seconds, results, filter_by_methods=None):
filter_by_methods = filter_by_met... | .set_fontsize(26)
| conditional_block |
main.rs |
// Get the size of the given type in bytes
fn size_of<T>() -> i32 {
mem::size_of::<T>() as i32
}
// Get an offset in bytes for n units of type T
fn offset<T>(n: u32) -> *const c_void {
(n * mem::size_of::<T>() as u32) as *const T as *const c_void
}
fn read_triangles_from_file() -> Result<Vec<f32>, ()> {
... | {
&val[0] as *const T as *const c_void
} | identifier_body | |
main.rs |
}
}
// Get a null pointer (equivalent to an offset of 0)
// ptr::null()
// let p = 0 as *const c_void
// == // Modify and complete the function below for the first task
unsafe fn init_vao(vertices: &Vec<f32>, indices: &Vec<u32>, colors: &Vec<f32>) -> u32 {
// Returns the ID of the newly instantiated vertex a... | {
println!("Error message: {}", error);
std::process::exit(1);
} | conditional_block | |
main.rs | ::clone(&arc_mouse_delta);
// Spawn a separate thread for rendering, so event handling doesn't block rendering
let render_thread = thread::spawn(move || {
// Acquire the OpenGL Context and load the function pointers. This has to be done inside of the rendering thread, because
// an active OpenG... | VirtualKeyCode::Left => {
rot_y -= rot_step;
}, | random_line_split | |
main.rs | <T>(n: u32) -> *const c_void {
(n * mem::size_of::<T>() as u32) as *const T as *const c_void
}
fn read_triangles_from_file() -> Result<Vec<f32>, ()> {
// Takes in an arbitraray amount of trinagles from a file
let mut vertices: Vec<f32>;
match File::open(".\\src\\triangles.txt") {
Ok(mut file) =... | offset | identifier_name | |
index.js | -post-btn").hide();
$("#save-post-btn").show();
$("#write-modal").addClass("is-active");
});
//체크박스 하나 선택해서 게시물 삭제
$("#delete-btn").click(function() {
let checked_count = $("input:checkbox[name=check]:checked").length;
if(checked_count > 1) {
alert("하나만 선택해주세요"... | let total_pages = response["totalPages"].toString(); //총 페이지 수
paging(current_page, result_count, result_length, page_number, total_pages);
selectPage(select_page);
}
});
}
//게시물 데이터 모두 가져와 목록 만들기
function getPosts(url, current_page) {
let url_include_page = "";
... | random_line_split | |
index.js | -post-btn").hide();
$("#save-post-btn").show();
$("#write-modal").addClass("is-active");
});
//체크박스 하나 선택해서 게시물 삭제
$("#delete-btn").click(function() {
let checked_count = $("input:checkbox[name=check]:checked").length;
if(checked_count > 1) {
alert("하나만 선택해주세요"... | (0,10);
let content = response["content"];
if(created | "name"];
let created_at_date = response["createdAt"].substr(0,10);
let modified_at_date = response["modifiedAt"].substr | identifier_body |
index.js | -btn").hide();
$("#save-post-btn").show();
$("#write-modal").addClass("is-active");
});
//체크박스 하나 선택해서 게시물 삭제
$("#delete-btn").click(function() {
let checked_count = $("input:checkbox[name=check]:checked").length;
if(checked_count > 1) {
alert("하나만 선택해주세요");
... | <td onclick="event.cancelBubble=true">
<input id="${id}-checkbox" name="check" type="checkbox" value="${id}">
</td>
<th id="${id}">${id}</th>
<td id="${id}-title">${title}</td>
... | `<tr onclick="showDetail('${id}')">
| conditional_block |
index.js | ").val("");
$("#write-content").val("");
$("#write-modal").removeClass("is-active");
}
});
//다음 페이지 단위로 이동
//previous 버튼에 있는 값은 페이징 처리 시 페이지 번호의 십의자리 숫자임
$("#pagination-next").click(function() {
let current_previous_val = parseInt($("#pagination-previous").attr... | identifier_name | ||
tgsrv.go | + strings.Replace(v, "delete ", "", -1) + "\n"
}
msgList.Text = txt + "\n"
}
bot.Send(msgList)
}
}
default:
bot.Send(msgCancel)
}
} else {
//unknown cmd
bot.Send(msgCancel)
}
}
}
} else {
if update.Message == n... | {
channelName := "@" + parts[len(parts)-1]
m := tgbotapi.NewMessageToChannel(channelName, "Ok")
m.DisableWebPagePreview = true
reply, err := bot.Send(m)
if err != nil {
s := err.Error()
if strings.Contains(s, "orbidden") {
m := tgbotapi.NewMessage(msg.Chat.ID, "Add @telefeedbot as ad... | conditional_block | |
tgsrv.go | msgCancel := tgbotapi.NewEditMessageText(update.CallbackQuery.Message.Chat.ID,
update.CallbackQuery.Message.MessageID,
"ZzZzZzzz ...")
if strings.HasPrefix(data, "delete"+params.Feed) {
feed := strings.Replace(data, "delete"+params.Feed, "", -1)
b := httputils.HttpGet(params.Feeds+feed, nil)
i... | {
var err error
tlgrmtoken, err := ioutil.ReadFile(params.Telefeedfile)
catch(err)
tgtoken := strings.Replace(strings.Replace(string(tlgrmtoken), "\n", "", -1), "\r", "", -1)
bot, err = tgbotapi.NewBotAPI(tgtoken)
catch(err)
bot.Debug = false
log.Printf("Authorized on account %s", bot.Self.UserName)
u := tgb... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.