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 |
|---|---|---|---|---|
answer_identification.old.py | from src.question_classifier import *
from nltk.corpus import stopwords
import nltk
import text_analyzer
import re
import string
def num_occurrences_time_regex(tokens):
dates_pattern = r'[[0-9]{1,2}/]*[0-9]{1,2}/[0-9]{2,4}|[0-9]{4}|january|february|march|april|may|june|july|' \
r'august|septem... |
except:
pass
def test_who1():
question_sentence = "Who is the principal of South Queens Junior High School?"
answer_sentence = "Principal Betty Jean Aucoin says the club is a first for a Nova Scotia public school."
test = get_answer_phrase(question_sentence, answer_sentence)
print(test)
... | [tree.leaves() for tree in qp_phrases],
key=lambda x: num_occurrences_quant_regex(x)
))
# todo: non-measure cases! (mostly thinking about "how did/does") | random_line_split |
Lt.ts | import { Lang } from '../models/Lang';
export class | {
public static Lt: Lang = {
// Side menu
menuMain: 'Pagrindinis',
menuOrganizations: 'Organizacijos',
menuProjects: 'Projektai',
menuSavedProjects: 'Išsaugoti projektai',
menuSelectedProjects: 'Pasirinkti projektai',
menuCreatedProjects: 'Sukurti projektai',... | Lt | identifier_name |
Lt.ts | import { Lang } from '../models/Lang';
export class Lt {
public static Lt: Lang = {
// Side menu
menuMain: 'Pagrindinis',
menuOrganizations: 'Organizacijos',
menuProjects: 'Projektai',
menuSavedProjects: 'Išsaugoti projektai',
menuSelectedProjects: 'Pasirinkti projek... | volunteersAll: 'Visi užsiregistravę vartotojai',
volunteersNone: 'Nėra informacijos',
volunteersAnonymousName: 'Anoniminis ',
volunteersAnonymousLast: 'vartotojas',
volunteersGoBack: 'Grįžti',
// Modal volunteer
modalVAnonymous: 'Anoniminis vartotojas',
mo... | volunteersHeader: 'Savanorių puslpapis',
volunteersYourVolunteers: 'Jūsų projekto savanoriai', | random_line_split |
card.go | package goker
import (
"fmt"
"math"
"math/rand"
"os"
"sort"
"time"
)
type Suit uint8
const (
_ Suit = iota
Spade
Club
Diamond
Heart
)
const (
minSuit = Spade
maxSuit = Heart
)
var suits = [...]Suit{Spade, Club, Diamond, Heart}
type Rank uint8
const (
_ Rank = iota
Two
Three
Four
Five
Six
Seve... |
func GetHand(n int, deck Deck) (Hand, Deck) {
var hand Hand
cards := deck[:n]
hand = append(hand, cards...)
return hand, shuffle(deck[n:])
}
func Less(cards []Card) func(i, j int) bool {
return func(i, j int) bool {
return cards[i].Rank < cards[j].Rank
}
}
func areConsecutive(cards []Card) bool {
for i := 0... | for i, v := range perm {
newD[v] = d[i]
}
return newD
} | random_line_split |
card.go | package goker
import (
"fmt"
"math"
"math/rand"
"os"
"sort"
"time"
)
type Suit uint8
const (
_ Suit = iota
Spade
Club
Diamond
Heart
)
const (
minSuit = Spade
maxSuit = Heart
)
var suits = [...]Suit{Spade, Club, Diamond, Heart}
type Rank uint8
const (
_ Rank = iota
Two
Three
Four
Five
Six
Seve... | return 2, r2[0].HandType, r2[0].Cards
}
}
func containsAction(actions []Action, x Action) (int, bool) {
for i, a := range actions {
if x == a {
return i, true
}
}
return 0, false
}
func (game *Game) ActionHandler(action Action, val *Money) {
switch action {
case PutBlind:
game.MainPot.value += BLIND ... | rn 1, r1[0].HandType, r1[0].Cards
} else {
| conditional_block |
card.go | package goker
import (
"fmt"
"math"
"math/rand"
"os"
"sort"
"time"
)
type Suit uint8
const (
_ Suit = iota
Spade
Club
Diamond
Heart
)
const (
minSuit = Spade
maxSuit = Heart
)
var suits = [...]Suit{Spade, Club, Diamond, Heart}
type Rank uint8
const (
_ Rank = iota
Two
Three
Four
Five
Six
Seve... | ([]Card, []Card, bool) {
cards3, ok3 := nOfSameRank(h, 3)
h = intersection(cards3, h)
cards2, ok2 := nOfSameRank(h, 2)
if ok2 && ok3 {
return cards3, cards2, true
}
return nil, nil, false
}
//500-Flush
func isFlush(h Hand) ([]Card, bool) {
return nOfSameSuit(h, 5)
}
//400-Straight
func isStraight(h Hand) ([... | use(h Hand) | identifier_name |
card.go | package goker
import (
"fmt"
"math"
"math/rand"
"os"
"sort"
"time"
)
type Suit uint8
const (
_ Suit = iota
Spade
Club
Diamond
Heart
)
const (
minSuit = Spade
maxSuit = Heart
)
var suits = [...]Suit{Spade, Club, Diamond, Heart}
type Rank uint8
const (
_ Rank = iota
Two
Three
Four
Five
Six
Seve... | OfSameRank(h Hand, n int) ([]Card, bool) {
m := make(map[Rank][]Card)
for i := len(h) - 1; i >= 0; i-- {
m[h[i].Rank] = append(m[h[i].Rank], h[i])
if len(m[h[i].Rank]) == n {
sort.Slice(m[h[i].Rank], Less(m[h[i].Rank]))
return m[h[i].Rank], true
}
}
return nil, false
}
func nPair(h Hand, n int) ([]Card,... | make(map[Suit][]Card)
for i := len(h) - 1; i >= 0; i-- {
m[h[i].Suit] = append(m[h[i].Suit], h[i])
if len(m[h[i].Suit]) == n {
sort.Slice(m[h[i].Suit], Less(m[h[i].Suit]))
return m[h[i].Suit], true
}
}
return nil, false
}
func n | identifier_body |
loading.rs | extern crate quicksilver;
extern crate json;
use quicksilver::prelude::*;
use std::collections::HashMap;
use itertools::Itertools;
use std::iter;
use crate::game_logic::{BoardState};
use crate::game_control::*;
use crate::game_objects::*;
use crate::ai::AI;
use crate::automaton::{AutomatonState, GameEvent};
use std::m... | (json: &serde_json::value::Value, node_name: &str, card_factory: &CardFactory) -> Deck {
let deck_node = {
json.get(node_name)
.expect(format!("Deck node \"{}\" not found", node_name).as_str())
.clone()
};
let data: HashMap<String, usize> = serde_json::from_value(deck_node)
... | parse_deck | identifier_name |
loading.rs | extern crate quicksilver;
extern crate json;
use quicksilver::prelude::*;
use std::collections::HashMap;
use itertools::Itertools;
use std::iter;
use crate::game_logic::{BoardState};
use crate::game_control::*;
use crate::game_objects::*;
use crate::ai::AI;
use crate::automaton::{AutomatonState, GameEvent};
use std::m... |
match game_type.to_lowercase().as_str() {
"vs" => {
assert_eq!(players.len(), 2, "For VS game, only 2 players are possible");
players[0].opponent_idx = 1;
players[1].opponent_idx = 0;
},
_ => panic!("Unknown game type")
}
players
}
pub fn lo... | .expect("game type not specified")
.as_str()
.expect("game type not string"); | random_line_split |
loading.rs | extern crate quicksilver;
extern crate json;
use quicksilver::prelude::*;
use std::collections::HashMap;
use itertools::Itertools;
use std::iter;
use crate::game_logic::{BoardState};
use crate::game_control::*;
use crate::game_objects::*;
use crate::ai::AI;
use crate::automaton::{AutomatonState, GameEvent};
use std::m... |
/// Loading state: loads all assets to memory and passes them to GameplayState.
///
/// The asset loading in Quicksilver (as described in tutorial) is awkward: it requires conditional
/// execution whenever any asset is used. As we don't have large amount of data, it is more ergonomic
/// to just load them all to RAM... | {
let store_node = "build_store";
let trade_row = "kaiju_store";
let hand_size = 5;
let draw_deck = parse_deck(&json, &player.starting_deck, card_factory);
//let bs_node = { json.get("build_store").expect("build_store node not found").clone() };
let build_store = parse_store(BoardZone::BuildSt... | identifier_body |
train_3d_occupancy.py | import sys
import os
sys.path.append( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) )
import numpy as np
import configargparse
import skvideo.io
from tqdm import tqdm
import time
import matplotlib.pyplot as plt
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
from t... |
if __name__ == '__main__':
parser = configargparse.ArgumentParser(config_file_parser_class=configargparse.YAMLConfigFileParser)
parser.add_argument('--experiment_id', default='vanilla', type=str)
parser.add_argument('-c', '--config_file', default=None, is_config_file=True)
parser.add_argument('--datas... | eval(
args,
model
) | conditional_block |
train_3d_occupancy.py | import sys
import os
sys.path.append( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) )
import numpy as np
import configargparse
import skvideo.io
from tqdm import tqdm
import time
import matplotlib.pyplot as plt
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
from t... | (theta, phi, radius):
c2w = trans_t(radius)
c2w = rot_phi(phi/180.*np.pi) @ c2w
c2w = rot_theta(theta/180.*np.pi) @ c2w
# c2w = np.array([[-1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]]) @ c2w
return c2w
def get_rays(H, W, focal, c2w):
i, j = np.meshgrid(np.arange(W), np.arange(H), indexing='xy')
... | pose_spherical | identifier_name |
train_3d_occupancy.py | import sys
import os
sys.path.append( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) )
import numpy as np
import configargparse
import skvideo.io
from tqdm import tqdm
import time
import matplotlib.pyplot as plt
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
from t... |
def as_mesh(scene_or_mesh):
"""
Convert a possible scene to a mesh.
If conversion occurs, the returned mesh has only vertex and face data.
"""
if isinstance(scene_or_mesh, trimesh.Scene):
if len(scene_or_mesh.geometry) == 0:
mesh = None # empty scene
else:
... | c0, c1 = corners
test_easy = np.random.uniform(size=[test_size, 3]) * (c1-c0) + c0
batch_pts, batch_normals = get_normal_batch(mesh, test_size)
test_hard = batch_pts + np.random.normal(size=[test_size,3]) * .001
return test_easy, test_hard | identifier_body |
train_3d_occupancy.py | import sys
import os
sys.path.append( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) )
import numpy as np
import configargparse
import skvideo.io
from tqdm import tqdm
import time
import matplotlib.pyplot as plt
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
from t... | mesh.vertices -= mesh.vertices.mean(0)
mesh.vertices /= np.max(np.abs(mesh.vertices))
mesh.vertices = .5 * (mesh.vertices + 1.)
def load_mesh(mesh_name, verbose=True):
mesh = trimesh.load(_mesh_paths[mesh_name])
mesh = as_mesh(mesh)
if verbose:
print(mesh.vertices.shape)
recenter_mesh(mesh)
c0,... | def recenter_mesh(mesh): | random_line_split |
gen.go | // +build ignore
package main
import (
"bytes"
"encoding/base64"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os/exec"
"regexp"
"sort"
"strconv"
"strings"
"github.com/rjeczalik/chromedp/kb"
)
var (
flagOut = flag.String("out", "keys.go", "out source")
flagPkg = flag.String("pkg", "kb", "out package nam... | () {
var err error
flag.Parse()
// special characters
keys := map[rune]kb.Key{
'\b': {"Backspace", "Backspace", "", "", int64('\b'), int64('\b'), false, false},
'\t': {"Tab", "Tab", "", "", int64('\t'), int64('\t'), false, false},
'\r': {"Enter", "Enter", "\r", "\r", int64('\r'), int64('\r'), false, true},
... | main | identifier_name |
gen.go | // +build ignore
package main
import (
"bytes"
"encoding/base64"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os/exec"
"regexp"
"sort"
"strconv"
"strings"
"github.com/rjeczalik/chromedp/kb"
)
var (
flagOut = flag.String("out", "keys.go", "out source")
flagPkg = flag.String("pkg", "kb", "out package nam... |
// getCode is a simple wrapper around parsing the code definition.
func getCode(s string) string {
if !strings.HasPrefix(s, `"`) || !strings.HasSuffix(s, `"`) {
panic(fmt.Sprintf("expected string, got: %s", s))
}
return s[1 : len(s)-1]
}
// addKey is a simple map add wrapper to panic if the key is already defi... | {
if strings.HasPrefix(s, "0x") {
i, err := strconv.ParseInt(s, 0, 16)
if err != nil {
panic(err)
}
return rune(i)
}
if !strings.HasPrefix(s, "'") || !strings.HasSuffix(s, "'") {
panic(fmt.Sprintf("expected character, got: %s", s))
}
if len(s) == 4 {
if s[1] != '\\' {
panic(fmt.Sprintf("expecte... | identifier_body |
gen.go | // +build ignore
package main
import (
"bytes"
"encoding/base64"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os/exec"
"regexp"
"sort"
"strconv"
"strings" |
"github.com/rjeczalik/chromedp/kb"
)
var (
flagOut = flag.String("out", "keys.go", "out source")
flagPkg = flag.String("pkg", "kb", "out package name")
)
const (
// chromiumSrc is the base chromium source repo location
chromiumSrc = "https://chromium.googlesource.com/chromium/src"
// domUsLayoutDataH contains... | random_line_split | |
gen.go | // +build ignore
package main
import (
"bytes"
"encoding/base64"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os/exec"
"regexp"
"sort"
"strconv"
"strings"
"github.com/rjeczalik/chromedp/kb"
)
var (
flagOut = flag.String("out", "keys.go", "out source")
flagPkg = flag.String("pkg", "kb", "out package nam... |
return keyboardCodeMap, nil
}
var keyboardCodeRE = regexp.MustCompile(`(?m)^\s+(VKEY_.+?)\s+=\s+(.+?),`)
// loadKeyboardCodes loads the enum definition from the specified path, saving
// the resolved symbol value to the specified position for the resulting dom
// key name in the vkeyCodeMap.
func loadKeyboardCodes... | {
return nil, err
} | conditional_block |
XGBoost_BayesOpt.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 20 12:45:16 2018
@author: jeremywatkins
"""
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import xgboost as xgb
from scipy import stats
from scipy.stats ... |
def xgb_eval_multi(min_child_weight,colsample_bytree,max_depth,subsample,gamma,alpha):
random_state=42
eta=.05
xtrain=train
xfeatures=features
params = {
"objective": "reg:logistic",
"booster" : "gbtree",
"eval_metric": "auc",
"eta": eta,
"tree_m... | random_state=42
eta=.05
xtrain=train
xfeatures=features
params = {
"objective": "reg:logistic",
"booster" : "gbtree",
"eval_metric": "auc",
"eta": eta,
"tree_method": 'exact',
"max_depth": max_depth,
"silent": 1,
"seed": random_state,... | identifier_body |
XGBoost_BayesOpt.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 20 12:45:16 2018
@author: jeremywatkins
"""
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import xgboost as xgb
from scipy import stats
from scipy.stats ... | (min_child_weight,colsample_bytree,max_depth,subsample,gamma,alpha):
random_state=42
eta=.05
xtrain=train
xfeatures=features
params = {
"objective": "reg:logistic",
"booster" : "gbtree",
"eval_metric": "auc",
"eta": eta,
"tree_method": 'exact',
... | xgb_eval_single | identifier_name |
XGBoost_BayesOpt.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 20 12:45:16 2018
@author: jeremywatkins
"""
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import xgboost as xgb
from scipy import stats
from scipy.stats ... | params['alpha'] = max(alpha, 0)
score =optim_run_single(xtrain, xfeatures, target, params, random_state)
return -1*score
def xgb_eval_multi(min_child_weight,colsample_bytree,max_depth,subsample,gamma,alpha):
random_state=42
eta=.05
xtrain=train
xfeatures=features
... | params['subsample'] = max(min(subsample, 1), 0)
params['gamma'] = max(gamma, 0) | random_line_split |
XGBoost_BayesOpt.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 20 12:45:16 2018
@author: jeremywatkins
"""
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import xgboost as xgb
from scipy import stats
from scipy.stats ... |
features=col_list[:]
merge['d0_pred'] = np.where(merge['d0']>0, 1, 0)
features.remove('year')
features.remove('valid_start')
features.remove('valid_end')
features.remove('date')
features.remove('state')
features.remove('county')
features.remove('d0')
features.remove('d1')
features.remove('d2')
features.remove('d... | for i in range(4,11):
merge[each+'_'+str(i+1)+'_Week_lag']=merge.groupby("fips")[each].shift(i)
lags.append(each+'_'+str(i+1)+'_Week_lag') | conditional_block |
action.go | package xweb
import (
"bytes"
"code.google.com/p/go-uuid/uuid"
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"github.com/astaxie/beego/session"
"html/template"
"io"
"io/ioutil"
"log"
"mime"
"mime/multipart"
"net/http"
"os"
"reflect"
"strco... |
}
}
return err
}
func (c *Action) getTemplate(tmpl string) ([]byte, error) {
if c.App.AppConfig.CacheTemplates {
return c.App.TemplateMgr.GetTemplate(tmpl)
}
path := c.App.getTemplatePath(tmpl)
if path == "" {
return nil, errors.New(fmt.Sprintf("No template file %v found", path))
}
return ioutil.ReadFi... | {
_, err = c.ResponseWriter.Write(tplcontent)
} | conditional_block |
action.go | package xweb
import (
"bytes"
"code.google.com/p/go-uuid/uuid"
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"github.com/astaxie/beego/session"
"html/template"
"io"
"io/ioutil"
"log"
"mime"
"mime/multipart"
"net/http"
"os"
"reflect"
"strco... |
func (c *Action) Go(m string, anotherc ...interface{}) error {
var t reflect.Type
if len(anotherc) > 0 {
t = reflect.TypeOf(anotherc[0]).Elem()
} else {
t = reflect.TypeOf(c.C.Interface()).Elem()
}
root, ok := c.App.Actions[t]
if !ok {
return NotFound()
}
uris := strings.Split(m, "?")
tag, ok := t.F... | {
return c.Request.Method
} | identifier_body |
action.go | package xweb
import (
"bytes"
"code.google.com/p/go-uuid/uuid"
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"github.com/astaxie/beego/session"
"html/template"
"io"
"io/ioutil"
"log"
"mime"
"mime/multipart"
"net/http"
"os"
"reflect"
"strco... | () string {
return c.Request.Method
}
func (c *Action) Go(m string, anotherc ...interface{}) error {
var t reflect.Type
if len(anotherc) > 0 {
t = reflect.TypeOf(anotherc[0]).Elem()
} else {
t = reflect.TypeOf(c.C.Interface()).Elem()
}
root, ok := c.App.Actions[t]
if !ok {
return NotFound()
}
uris := ... | Method | identifier_name |
action.go | package xweb
import (
"bytes"
"code.google.com/p/go-uuid/uuid"
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"github.com/astaxie/beego/session"
"html/template"
"io"
"io/ioutil"
"log"
"mime"
"mime/multipart"
"net/http"
"os"
"reflect"
"strco... |
type Mapper struct {
}
type T map[string]interface{}
func XsrfName() string {
return XSRF_TAG
}
func (c *Action) XsrfValue() string {
var val string = ""
cookie, err := c.GetCookie(XSRF_TAG)
if err != nil {
val = uuid.NewRandom().String()
c.SetCookie(NewCookie(XSRF_TAG, val, c.App.AppConfig.SessionTimeout))... | Session session.SessionStore
T T
f T
RootTemplate *template.Template
} | random_line_split |
cnos_network_driver_rest.py | # Copyright 2016 OpenStack Foundation
# 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 requ... | ############ Private Methods ############################
def _dbg_str(self, host, op, vlan_id,
vlan_name=None, interface=None, intf_type=None):
"""
Construct a string displayed in debug messages or exceptions
for the main operations
"""
dbg_fmt = "host %s ... | random_line_split | |
cnos_network_driver_rest.py | # Copyright 2016 OpenStack Foundation
# 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 requ... |
elif vlist == "none":
return []
elif type(vlist) is not list:
raise Exception("Unexpected vlan list: " + str(vlist))
else:
return vlist
def _add_intf_to_vlan(self, conn, vlan_id, interface):
"""
Internal method to add an interface to a v... | return list(range(1, 4095)) | conditional_block |
cnos_network_driver_rest.py | # Copyright 2016 OpenStack Foundation
# 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 requ... |
def _rem_intf_from_vlan(self, conn, vlan_id, interface):
"""
Internal method to remove an interface from a vlan
Parameters:
conn - connection handler
vlan_id - vlan identifier
interface - interface identifier (name)
"""
obj = self.VLAN_... | """
Internal method to add an interface to a vlan
Parameters:
conn - connection handler
vlan_id - vlan identifier
interface - interface identifier (name)
"""
obj = self.VLAN_IFACE_REST_OBJ + quote(interface, safe='')
resp = conn.get(obj)
... | identifier_body |
cnos_network_driver_rest.py | # Copyright 2016 OpenStack Foundation
# 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 requ... | (self, conn, vlan_id, vlan_name):
"""
Internal method to create the vlan
Parameters:
conn - connection handler
vlan_id - vlan identifier
vlan_name - vlan name
"""
req_js = {}
req_js['vlan_id'] = vlan_id
req_js['vlan_name'] = ... | _create_vlan | identifier_name |
DiffUtils.py | ##############################################################################
#
# Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved.
# Yoshinori Okuji <yo@nexedi.com>
# Christophe Dumez <christophe@nexedi.com>
#
# WARNING: This program as such is intended to be ... |
class SubCodeBlock:
""" a SubCodeBlock contain 0 or 1 modification (not more)
"""
def __init__(self, code):
self.body = code
self.modification = self._getModif()
self.old_code_length = self._getOldCodeLength()
self.new_code_length = self._getNewCodeLength()
# Choosing background color
if... | """ Return code after modification
"""
tmp = []
for child in self.children:
tmp.extend(child.getNewCodeList())
return tmp | identifier_body |
DiffUtils.py | ##############################################################################
#
# Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved.
# Yoshinori Okuji <yo@nexedi.com>
# Christophe Dumez <christophe@nexedi.com>
#
# WARNING: This program as such is intended to be ... | # along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################
"""
Provide a feature not present into difflib, which is generate a colored diff
from a diff fil... | #
# You should have received a copy of the GNU General Public License | random_line_split |
DiffUtils.py | ##############################################################################
#
# Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved.
# Yoshinori Okuji <yo@nexedi.com>
# Christophe Dumez <christophe@nexedi.com>
#
# WARNING: This program as such is intended to be ... | (self):
""" Return type of modification :
addition, deletion, none
"""
nb_plus = 0
nb_minus = 0
for line in self.body.splitlines():
if line.startswith("-"):
nb_minus -= 1
elif line.startswith("+"):
nb_plus += 1
if (nb_plus == 0 and nb_minus == 0):
return... | _getModif | identifier_name |
DiffUtils.py | ##############################################################################
#
# Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved.
# Yoshinori Okuji <yo@nexedi.com>
# Christophe Dumez <christophe@nexedi.com>
#
# WARNING: This program as such is intended to be ... |
return 'change'
def _getOldCodeLength(self):
""" Private function to return old code length
"""
nb_lines = 0
for line in self.body.splitlines():
if not line.startswith("+"):
nb_lines += 1
return nb_lines
def _getNewCodeLength(self):
""" Private function to return new cod... | return 'deletion' | conditional_block |
memorycache.js |
//
// memorycache.js
//
// Openpux Internet Of Things (IOT) Framework.
//
// Copyright (C) 2014,2015 Menlo Park Innovation LLC
//
// menloparkinnovation.com
// menloparkinnovation@gmail.com
//
// Snapshot License
//
// This license is for a specific snapshot of a base work of
// Menlo Par... |
//
// Set a value into the cache.
//
// If the cache is at capacity, timeCount entries are
// removed.
//
// A reference to the object is stored by the key, the object
// is not copied.
//
// val - object reference
//
// Returns:
// true - entry was entered
// false - cache is full, and trimCount was... | {
this.moduleName = "MemoryCache";
this.maxEntries = maxEntries;
this.trimCount = trimCount;
this.entryCount = 0;
// A Javascript object is a map
this.cacheMap = new Object();
} | identifier_body |
memorycache.js |
//
// memorycache.js
//
// Openpux Internet Of Things (IOT) Framework.
//
// Copyright (C) 2014,2015 Menlo Park Innovation LLC
//
// menloparkinnovation.com
// menloparkinnovation@gmail.com
//
// Snapshot License
//
// This license is for a specific snapshot of a base work of
// Menlo Par... |
return items;
}
//
// Select last itemCount items
//
// itemName - itemName such as "/account/1/sensor/1/readings"
//
// timestamp - timestamp to begin search by
//
MemoryCache.prototype.buildSelectLastItemsStatement =
function(itemName, timestamp, itemcount) {
// To support in memory que... | {
var key = keys[index];
// Validate if name is an immediate decendent and an object
var child = utility.getImmediateChildObject(parentName, key);
if (child != null) {
var o = {itemName: key, item: this.cacheMap[key]}
items.push(o);
itemCoun... | conditional_block |
memorycache.js |
//
// memorycache.js
//
// Openpux Internet Of Things (IOT) Framework.
//
// Copyright (C) 2014,2015 Menlo Park Innovation LLC
//
// menloparkinnovation.com
// menloparkinnovation@gmail.com
//
// Snapshot License
//
// This license is for a specific snapshot of a base work of
// Menlo Par... | (maxEntries, trimCount) {
this.moduleName = "MemoryCache";
this.maxEntries = maxEntries;
this.trimCount = trimCount;
this.entryCount = 0;
// A Javascript object is a map
this.cacheMap = new Object();
}
//
// Set a value into the cache.
//
// If the cache is at capacity, timeCoun... | MemoryCache | identifier_name |
memorycache.js | //
// memorycache.js
//
// Openpux Internet Of Things (IOT) Framework.
//
// Copyright (C) 2014,2015 Menlo Park Innovation LLC
//
// menloparkinnovation.com
// menloparkinnovation@gmail.com
//
// Snapshot License
//
// This license is for a specific snapshot of a base work of
// Menlo Park ... | //
// Example:
//
// If the object store has the following entries:
//
// /accounts/1/sensors/1
// /accounts/1/sensors/1/settings
// /accounts/1/sensors/1/readings/2015-11-11T15:41:26.969Z
// /accounts/1/sensors/1/readings/2015-11-11T15:41:27.992Z
//
// Then a query of parentName /accounts/1/sensors/1 with
/... | //
// result is an array of childNames.
| random_line_split |
__init__.py | """
Utilities used by other modules.
"""
import csv
import datetime
import hashlib
import json
import re
import string
import subprocess
import uuid
import xml.etree.ElementTree as ET
from alta import ConfigurationFromYamlFile
from pkg_resources import resource_filename
from ..__details__ import __appname__
from appd... |
def get_indexed_reads(self):
reads = self.get_reads()
return filter(lambda item: item["IsIndexedRead"] == "Y", reads)
def get_index_cycles(self):
indexed_reads = self.get_indexed_reads()
return dict(
index=next((item['NumCycles'] for item in indexed_reads
... | return reads | random_line_split |
__init__.py | """
Utilities used by other modules.
"""
import csv
import datetime
import hashlib
import json
import re
import string
import subprocess
import uuid
import xml.etree.ElementTree as ET
from alta import ConfigurationFromYamlFile
from pkg_resources import resource_filename
from ..__details__ import __appname__
from appd... |
if write:
self.tree.write(self.xml_file)
def is_paired_end_sequencing(self):
reads = self.get_reads()
reads = filter(lambda item: item["IsIndexedRead"] == "N", reads)
if len(reads) == 1:
return False
return True
class LogBook:
"""
Logbook... | if read.attrib["IsIndexedRead"] == "Y":
if read.attrib['Number'] == '2':
read.attrib.update(NumCycles=index_cycles.get('index', DEFAULT_INDEX_CYCLES['index']))
else:
read.attrib.update(NumCycles=index_cycles.get('index', DEFAULT_INDEX_CYCLES['index... | conditional_block |
__init__.py | """
Utilities used by other modules.
"""
import csv
import datetime
import hashlib
import json
import re
import string
import subprocess
import uuid
import xml.etree.ElementTree as ET
from alta import ConfigurationFromYamlFile
from pkg_resources import resource_filename
from ..__details__ import __appname__
from appd... | (self, f):
self.xml_file = f
self.tree = ET.parse(self.xml_file)
self.root = self.tree.getroot()
def get_reads(self):
reads = [r.attrib for r in self.root.iter('Read')]
return reads
def get_indexed_reads(self):
reads = self.get_reads()
return filter(lamb... | __init__ | identifier_name |
__init__.py | """
Utilities used by other modules.
"""
import csv
import datetime
import hashlib
import json
import re
import string
import subprocess
import uuid
import xml.etree.ElementTree as ET
from alta import ConfigurationFromYamlFile
from pkg_resources import resource_filename
from ..__details__ import __appname__
from appd... |
def get_body(self, label='Sample_Name', new_value='', replace=True):
def sanitize(mystr):
"""
Sanitize string in accordance with Illumina's documentation
bcl2fastq2 Conversion Software v2.17 Guide
"""
retainlist = "_-"
return re.sub(r... | return False if self.get_barcode_mask() is None else True | identifier_body |
kidney_utils.py | import kidney_ndds
from kidney_digraph import *
EPS = 0.00001
class KidneyOptimException(Exception):
pass
def check_validity(opt_result, digraph, ndds, max_cycle, max_chain, min_chain = None):
"""Check that the solution is valid.
This method checks that:
- all used edges exist
- no vertex or... | initiated by ndd i (True if v is within the chain cap of ndd i, False otherwise)
"""
for v in digraph.vs:
v.can_be_in_chain_list = [False for _ in ndds]
for i_ndd,ndd in enumerate(ndds):
# Get a set of donor-patient pairs who are the target of an edge from an NDD
ndd_targets = ... | which is a list of booleans: can_be_in_chain_list[i] = True if v can be in a chain | random_line_split |
kidney_utils.py | import kidney_ndds
from kidney_digraph import *
EPS = 0.00001
class KidneyOptimException(Exception):
pass
def check_validity(opt_result, digraph, ndds, max_cycle, max_chain, min_chain = None):
|
def get_dist_from_nearest_ndd(digraph, ndds):
""" For each donor-patient pair V, this returns the length of the
shortest path from an NDD to V, or 999999999 if no path from an NDD
to V exists.
"""
# Get a set of donor-patient pairs who are the target of an edge from an NDD
ndd_targets = s... | """Check that the solution is valid.
This method checks that:
- all used edges exist
- no vertex or NDD is used twice (which also ensures that no edge is used twice)
- cycle and chain caps are respected
- chain does not contain cycle (check for repeated tgt vertices)
"""
# all used... | identifier_body |
kidney_utils.py | import kidney_ndds
from kidney_digraph import *
EPS = 0.00001
class KidneyOptimException(Exception):
pass
def check_validity(opt_result, digraph, ndds, max_cycle, max_chain, min_chain = None):
"""Check that the solution is valid.
This method checks that:
- all used edges exist
- no vertex or... |
# no vertex or NDD is used twice
ndd_used = [False] * len(ndds)
vtx_used = [False] * len(digraph.vs)
for chain in opt_result.chains:
if ndd_used[chain.ndd_index]:
raise KidneyOptimException("NDD {} used more than once".format(chain.ndd_index))
ndd_used[chain... | raise KidneyOptimException("Edge from vertex {} to vertex {} is used but does not exist".format(
cycle[i-1].id, cycle[i].id)) | conditional_block |
kidney_utils.py | import kidney_ndds
from kidney_digraph import *
EPS = 0.00001
class KidneyOptimException(Exception):
pass
def check_validity(opt_result, digraph, ndds, max_cycle, max_chain, min_chain = None):
"""Check that the solution is valid.
This method checks that:
- all used edges exist
- no vertex or... | (v_id, next_vv):
path = [v_id]
while v_id in next_vv:
v_id = next_vv[v_id]
path.append(v_id)
return path
def find_selected_cycle(v_id, next_vv):
cycle = [v_id]
while v_id in next_vv:
v_id = next_vv[v_id]
if v_id in cycle:
return cycle
else... | find_selected_path | identifier_name |
mapi.js | //a focus blur
function checkUrl() {
var pattern = /%3C|%3E|[<>'"\(\)]/ig; //格式 RegExp("定义特殊过滤字符")
var url = decodeURI(window.location.href);
if (pattern.test(url)) {
var safeUrl = '';
for (var i = 0; i < url.length; i++) {
safeUrl = safeUrl + url.substr(i, 1).replace(... | //第一张图片设置zIndex为10,其它图片透明度设置为透明(0代表透明,1代表不透明)
each(me.arrImgs, function(elem, idx, arr) {
if (idx == 0) {
elem.style.zIndex = 10;
} else {
setOpacity(elem, 0);
}
}, me);
//为所... | me.arrImgs = $(container).children('a');
me.arrNums = $(numbers).children();
me.arrNums[0].className = "on";
| random_line_split |
mapi.js | //a focus blur
function checkUrl() {
var pattern = /%3C|%3E|[<>'"\(\)]/ig; //格式 RegExp("定义特殊过滤字符")
var url = decodeURI(window.location.href);
if (pattern.test(url)) {
var safeUrl = '';
for (var i = 0; i < url.length; i++) {
safeUrl = safeUrl + url.substr(i, 1).replace(... | setTimeout(function() {
setOpacity(elem, pos);
}, i * 25);
})(i);
}
}
/**
* 设置透明度
*/
function setOpacity(elem, level) {
if (elem.filters) { //IE
elem.style.filter = "alpha(opacity=" + level + ")";
... | setOpacity(elem, pos);
}, i * 25);
})(i);
}
}
/**
* 淡出效果
*/
function fadeOut(elem) {
for (var i = 0; i <= LOOP_NUMBER; i++) {
(function(i) {
var pos = 100 - i * 5;
| identifier_body |
mapi.js | //a focus blur
function checkUrl() {
var pattern = /%3C|%3E|[<>'"\(\)]/ig; //格式 RegExp("定义特殊过滤字符")
var url = decodeURI(window.location.href);
if (pattern.test(url)) {
var safeUrl = '';
for (var i = 0; i < url.length; i++) {
safeUrl = safeUrl + url.substr(i, 1).replace(... | i) {
var pos = i * 5;
setTimeout(function() {
setOpacity(elem, pos);
}, i * 25);
})(i);
}
}
/**
* 淡出效果
*/
function fadeOut(elem) {
for (var i = 0; i <= LOOP_NUMBER; i++) {
(fu... |
for (var i = 0; i <= LOOP_NUMBER; i++) {
(function( | conditional_block |
mapi.js | //a focus blur
function checkUrl() {
var pattern = /%3C|%3E|[<>'"\(\)]/ig; //格式 RegExp("定义特殊过滤字符")
var url = decodeURI(window.location.href);
if (pattern.test(url)) {
var safeUrl = '';
for (var i = 0; i < url.length; i++) {
safeUrl = safeUrl + url.substr(i, 1).replace(... | ument.getElementById(whichID).style.display = 'block';
}
//修改, by wjp
if (typeof BMap != 'undefined') {
var map = new BMap.Map("mmap");
var point = new BMap.Point(116.307852, 40.057031);
map.centerAndZoom(point, 15);
var opts = {
width: 250, // 信息窗口宽度
height: 80, // 信息窗口高度
... | ) {
doc | identifier_name |
episode.rs | use std::cmp;
use std::path::Path;
use std::u32;
use byteorder::{ByteOrder, BE};
use fst::{self, IntoStreamer, Streamer};
use crate::error::{Error, Result};
use crate::index::csv_file;
use crate::record::Episode;
use crate::util::{IMDB_EPISODE, fst_set_builder_file, fst_set_file};
/// The name of the episode index f... | Err(err) => bug!("episode id invalid UTF-8: {}", err),
Ok(tvshow_id) => tvshow_id,
};
let mut i = nul + 1;
let season = from_optional_u32(&bytes[i..]);
i += 4;
let epnum = from_optional_u32(&bytes[i..]);
i += 4;
let tvshow_id = match String::from_utf8(bytes[i..].to_vec()) ... | None => bug!("could not find nul byte"),
};
let id = match String::from_utf8(bytes[..nul].to_vec()) { | random_line_split |
episode.rs | use std::cmp;
use std::path::Path;
use std::u32;
use byteorder::{ByteOrder, BE};
use fst::{self, IntoStreamer, Streamer};
use crate::error::{Error, Result};
use crate::index::csv_file;
use crate::record::Episode;
use crate::util::{IMDB_EPISODE, fst_set_builder_file, fst_set_file};
/// The name of the episode index f... |
}
| {
let ctx = TestContext::new("small");
let idx = Index::create(ctx.data_dir(), ctx.index_dir()).unwrap();
let ep = idx.episode(b"tt0701063").unwrap().unwrap();
assert_eq!(ep.tvshow_id, "tt0096697");
} | identifier_body |
episode.rs | use std::cmp;
use std::path::Path;
use std::u32;
use byteorder::{ByteOrder, BE};
use fst::{self, IntoStreamer, Streamer};
use crate::error::{Error, Result};
use crate::index::csv_file;
use crate::record::Episode;
use crate::util::{IMDB_EPISODE, fst_set_builder_file, fst_set_file};
/// The name of the episode index f... | (ep: &Episode) -> Result<u32> {
match ep.episode {
None => Ok(u32::MAX),
Some(x) => {
if x == u32::MAX {
bug!("unsupported episode number {} for {:?}", x, ep);
}
Ok(x)
}
}
}
fn u32_to_bytes(n: u32) -> [u8; 4] {
let mut buf = [0u8; ... | to_optional_epnum | identifier_name |
import_export_classes.py | import tqdm
import logging
import os
import time
from .document_class import Document
from collections import Counter
from .search_utils import document_generator
from .filenames import id2filename
import zipfile
import gzip
import tarfile
import bz2
import os
import re
logger = logging.getLogger("INCA:" + __name__)
... | (
self,
query="*",
destination="exports/",
overwrite=False,
batchsize=None,
*args,
**kwargs
):
"""Exports documents from the INCA elasticsearch index
DO NOT OVERWRITE
This method is the common-caller for the exporter functionality. Co... | run | identifier_name |
import_export_classes.py | import tqdm
import logging
import os
import time
from .document_class import Document
from collections import Counter
from .search_utils import document_generator
from .filenames import id2filename
import zipfile
import gzip
import tarfile
import bz2
import os
import re
logger = logging.getLogger("INCA:" + __name__)
... |
def load(self):
""" To be implemented in subclasses
normally called through the 'run' method. Please add to your documentation:
Parameters
---
mapping : dict
A dictionary that specifies the from_key :=> to_key relation
between loaded documents and ... | """Apply a given mapping to a document
Parameters
---
document : dict
A document as loaded by the load function
mapping : dict
A dictionary that specifies the from_key :=> to_key relation
between loaded documents and documents as they should be index... | identifier_body |
import_export_classes.py | import tqdm
import logging
import os
import time
from .document_class import Document
from collections import Counter
from .search_utils import document_generator
from .filenames import id2filename
import zipfile
import gzip
import tarfile
import bz2
import os
import re
logger = logging.getLogger("INCA:" + __name__)
... |
Filenames are generated with extensions declared in 'self.extention'
overwrite : bool (default=False)
Whether to write over an existing file (stop if False)
batchsize : int
Size of documents to keep in memory for each batch
*args & **kwargs
Subcla... |
If the destination is a folder, a filename will be generated. | random_line_split |
import_export_classes.py | import tqdm
import logging
import os
import time
from .document_class import Document
from collections import Counter
from .search_utils import document_generator
from .filenames import id2filename
import zipfile
import gzip
import tarfile
import bz2
import os
import re
logger = logging.getLogger("INCA:" + __name__)
... |
if compression == "gz":
return gzip.open(filename, mode=mode)
if compression == "bz2":
return bz2.open(filename, mode=mode)
return fileobj
def open_dir(
self, path, mode="r", match=".*", force=False, compression="autodetect"
):
"""Generator that... | filename += "." + compression | conditional_block |
main.rs | extern crate docopt;
#[macro_use]
extern crate serde_derive;
use docopt::Docopt;
#[macro_use]
extern crate log;
use log::{Level, LevelFilter, Metadata, Record};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader, Seek, SeekFrom};
use std::path::Path;
static MY_LOGGER: Simp... | (&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"{} {} {:?}",
self.file_path.display(),
self.delimiter,
self.quote
)
}
}
fn parse_args<'a>(
path_arg: &'a String,
delimiter_arg: &'a String,
quote_arg: &'a S... | fmt | identifier_name |
main.rs | extern crate docopt;
#[macro_use]
extern crate serde_derive;
use docopt::Docopt;
#[macro_use]
extern crate log;
use log::{Level, LevelFilter, Metadata, Record};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader, Seek, SeekFrom};
use std::path::Path;
static MY_LOGGER: Simp... |
}
struct CsvDesc<'a> {
file_path: &'a Path,
delimiter: char,
quote: Option<char>,
}
impl<'a> std::fmt::Display for CsvDesc<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"{} {} {:?}",
self.file_path.display(),
... | {} | identifier_body |
main.rs | extern crate docopt;
#[macro_use]
extern crate serde_derive;
use docopt::Docopt;
#[macro_use]
extern crate log;
use log::{Level, LevelFilter, Metadata, Record};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader, Seek, SeekFrom};
use std::path::Path;
static MY_LOGGER: Simp... | Err(e) => panic!("failed getting csv row #2: {}", e),
};
info!("comparing {}:", row_key);
info!("line #1: {:?}", row_1);
info!("line #2: {:?}", row_2);
for col in &cols_to_compare {
let col_index_1 = *csv_col_index_1.get(*col).unwrap();
let c... | let row_2 = match get_csv_row(&csv_desc_2, index_2) {
Ok(row) => row, | random_line_split |
verify.rs | use std::ffi::OsStr;
use std::fmt::Write as _;
use std::fs::File;
use std::path::{Path, PathBuf};
use crate::cache::caches::RegistrySuperCache;
use crate::cache::*;
use crate::remove::remove_file;
use flate2::read::GzDecoder;
use rayon::iter::*;
use tar::Archive;
use walkdir::WalkDir;
#[derive(Debug, Clone, PartialE... |
/// look into the .gz archive and get all the contained files+sizes
fn sizes_of_archive_files(path: &Path) -> Vec<FileWithSize> {
let tar_gz = File::open(path).unwrap();
// extract the tar
let tar = GzDecoder::new(tar_gz);
let mut archive = Archive::new(tar);
let archive_files = archive.entries(... | {
// for each directory, find the path to the corresponding .crate archive
// .cargo/registry/src/github.com-1ecc6299db9ec823/bytes-0.4.12
// corresponds to
// .cargo/registry/cache/github.com-1ecc6299db9ec823/bytes-0.4.12.crate
// reverse, and "pop" the front components
let mut dir = src_path.... | identifier_body |
verify.rs | use std::ffi::OsStr;
use std::fmt::Write as _;
use std::fs::File;
use std::path::{Path, PathBuf};
use crate::cache::caches::RegistrySuperCache;
use crate::cache::*;
use crate::remove::remove_file;
use flate2::read::GzDecoder;
use rayon::iter::*;
use tar::Archive;
use walkdir::WalkDir;
#[derive(Debug, Clone, PartialE... | diff.files_size_difference.push(FileSizeDifference {
path: fws.path.clone(),
size_archive: archive_file.size,
size_source: fws.size,
});
}
}
... | {
Some(fws) => {
if fws.size != archive_file.size { | random_line_split |
verify.rs | use std::ffi::OsStr;
use std::fmt::Write as _;
use std::fs::File;
use std::path::{Path, PathBuf};
use crate::cache::caches::RegistrySuperCache;
use crate::cache::*;
use crate::remove::remove_file;
use flate2::read::GzDecoder;
use rayon::iter::*;
use tar::Archive;
use walkdir::WalkDir;
#[derive(Debug, Clone, PartialE... |
None => unreachable!(), // we already checked this
};
}
}
let files_of_archive: Vec<&PathBuf> = files_of_archive.iter().map(|fws| &fws.path).collect();
for source_file in files_of_source_paths
.iter()
.filter(|path| path.file_name().unwrap() != ".cargo-ok... | {
if fws.size != archive_file.size {
diff.files_size_difference.push(FileSizeDifference {
path: fws.path.clone(),
size_archive: archive_file.size,
size_source: fws.size,
... | conditional_block |
verify.rs | use std::ffi::OsStr;
use std::fmt::Write as _;
use std::fs::File;
use std::path::{Path, PathBuf};
use crate::cache::caches::RegistrySuperCache;
use crate::cache::*;
use crate::remove::remove_file;
use flate2::read::GzDecoder;
use rayon::iter::*;
use tar::Archive;
use walkdir::WalkDir;
#[derive(Debug, Clone, PartialE... | (src_path: &Path) -> PathBuf {
// for each directory, find the path to the corresponding .crate archive
// .cargo/registry/src/github.com-1ecc6299db9ec823/bytes-0.4.12
// corresponds to
// .cargo/registry/cache/github.com-1ecc6299db9ec823/bytes-0.4.12.crate
// reverse, and "pop" the front component... | map_src_path_to_cache_path | identifier_name |
load.rs | use std::collections::{HashMap, HashSet};
use std::fs;
use std::ops::RangeInclusive;
use std::sync::Arc;
use std::time::Instant;
use arc_swap::{ArcSwap, Guard};
use chrono::{Duration, Utc};
use lazy_static::lazy_static;
use log::error;
use regex::Regex;
use serde::{Deserialize, Serialize};
use crate::db;
use collecto... | let mut finished = 0;
while finished < unordered_queue.len() {
// The next level is those elements in the unordered queue which
// are ready to be benchmarked (i.e., those with parent in done or no
// parent).
let level_len = partition_in_place(unordered_queue[finished..].iter_mu... | // A topological sort, where each "level" is additionally altered such that
// try commits come first, and then sorted by PR # (as a rough heuristic for
// earlier requests).
| random_line_split |
load.rs | use std::collections::{HashMap, HashSet};
use std::fs;
use std::ops::RangeInclusive;
use std::sync::Arc;
use std::time::Instant;
use arc_swap::{ArcSwap, Guard};
use chrono::{Duration, Utc};
use lazy_static::lazy_static;
use log::error;
use regex::Regex;
use serde::{Deserialize, Serialize};
use crate::db;
use collecto... |
}
}
let mut already_tested = all_commits.clone();
let mut i = 0;
while i != queue.len() {
if !already_tested.insert(queue[i].0.sha.clone()) {
queue.remove(i);
} else {
i += 1;
}
}
sort_queue(all_commits.clone(), queue)
}
fn sort_queue(
... | {
// do nothing, for now, though eventually we'll want an artifact queue
} | conditional_block |
load.rs | use std::collections::{HashMap, HashSet};
use std::fs;
use std::ops::RangeInclusive;
use std::sync::Arc;
use std::time::Instant;
use arc_swap::{ArcSwap, Guard};
use chrono::{Duration, Utc};
use lazy_static::lazy_static;
use log::error;
use regex::Regex;
use serde::{Deserialize, Serialize};
use crate::db;
use collecto... |
#[test]
fn parse_published_stable_artifact() {
assert_eq!(
parse_published_artifact_tag(
"static.rust-lang.org/dist/2022-08-15/channel-rust-1.63.0.toml"
),
Some("1.63.0".to_string())
);
}
}
| {
assert_eq!(
parse_published_artifact_tag(
"static.rust-lang.org/dist/2022-08-15/channel-rust-beta.toml"
),
Some("beta-2022-08-15".to_string())
);
} | identifier_body |
load.rs | use std::collections::{HashMap, HashSet};
use std::fs;
use std::ops::RangeInclusive;
use std::sync::Arc;
use std::time::Instant;
use arc_swap::{ArcSwap, Guard};
use chrono::{Duration, Utc};
use lazy_static::lazy_static;
use log::error;
use regex::Regex;
use serde::{Deserialize, Serialize};
use crate::db;
use collecto... | {
pub sha: String,
pub parent_sha: String,
}
impl TryCommit {
pub fn sha(&self) -> &str {
self.sha.as_str()
}
pub fn comparison_url(&self) -> String {
format!(
"https://perf.rust-lang.org/compare.html?start={}&end={}",
self.parent_sha, self.sha
)
... | TryCommit | identifier_name |
create_cluster.go | // Copyright © 2019 Banzai Cloud
//
// 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 ... | region, kubernetesVersion, pkeVersion string, pkeImageNameGetter PKEImageNameGetter) (string, error) {
kubeVersion, err := semver.NewVersion(kubernetesVersion)
if err != nil {
return "", errors.WithDetails(err, "could not create semver from Kubernetes version", "kubernetesVersion", kubernetesVersion)
}
_ = kubeVe... | etDefaultImageID( | identifier_name |
create_cluster.go | // Copyright © 2019 Banzai Cloud
//
// 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 ... | GlobalRegion string
}
func (w CreateClusterWorkflow) Execute(ctx workflow.Context, input CreateClusterWorkflowInput) error {
ao := workflow.ActivityOptions{
ScheduleToStartTimeout: 10 * time.Minute,
StartToCloseTimeout: 20 * time.Minute,
WaitForCancellation: true,
}
ctx = workflow.WithActivityOptions(... | random_line_split | |
create_cluster.go | // Copyright © 2019 Banzai Cloud
//
// 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 ... |
type TokenGenerator interface {
GenerateClusterToken(orgID, clusterID uint) (string, string, error)
}
type CreateClusterWorkflowInput struct {
OrganizationID uint
ClusterID uint
ClusterUID string
ClusterName string
SecretID strin... |
kubeVersion, err := semver.NewVersion(kubernetesVersion)
if err != nil {
return "", errors.WithDetails(err, "could not create semver from Kubernetes version", "kubernetesVersion", kubernetesVersion)
}
_ = kubeVersion
if pkeImageNameGetter != nil {
ami, err := pkeImageNameGetter.PKEImageName("amazon", "pke", ... | identifier_body |
create_cluster.go | // Copyright © 2019 Banzai Cloud
//
// 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 ... | }
// PKE 0.4.19; K8s 1.13.10; OS Ubuntu
return map[string]string{
"ap-east-1": "ami-0ca8206236662e9ea", // Asia Pacific (Hong Kong).
"ap-northeast-1": "ami-029f1fff7d250aa95", // Asia Pacific (Tokyo).
"ap-northeast-2": "ami-0b2ea3e1fb7e0a0dc", // Asia Pacific (Seoul).
"ap-southeast-1": "ami-00d5d224c11... |
return ami, nil
}
| conditional_block |
pyod_tests.py | """
This file consists of utility functions, embedding model and function for model testing
"""
import numpy as np
import random
import os
from sklearn.model_selection import train_test_split
from keras.layers import Conv2D, MaxPooling2D, Input, Cropping2D, Add
from keras.layers import Flatten, Dense
from keras.model... |
print('max recall', max_recall)
print('max precision', max_precision)
best_params_precision = grid[max_precision_id]
best_params_recall = grid[max_recall_id]
print('best parameters set for precision', best_params_precision)
print('best parameters set for recall', best_params_recall)
if __na... | max_recall = recall
max_recall_id = i | conditional_block |
pyod_tests.py | """
This file consists of utility functions, embedding model and function for model testing
""" | import random
import os
from sklearn.model_selection import train_test_split
from keras.layers import Conv2D, MaxPooling2D, Input, Cropping2D, Add
from keras.layers import Flatten, Dense
from keras.models import Model
import glob
import cv2
import itertools
from utils import silent
from pyod.models.xgbod import XGBOD... |
import numpy as np | random_line_split |
pyod_tests.py | """
This file consists of utility functions, embedding model and function for model testing
"""
import numpy as np
import random
import os
from sklearn.model_selection import train_test_split
from keras.layers import Conv2D, MaxPooling2D, Input, Cropping2D, Add
from keras.layers import Flatten, Dense
from keras.model... | (dataset_path, classes):
"""
Function for creating train and test generators with image embeddigns
"""
model = embeddings(INPUT_DIM)
X_train, X_test, y_train, y_test = get_train_test_lists(dataset_path, classes)
# create data generators
batch_size = 16
train_batch_generator = image_batch... | generate_embeddings_gen | identifier_name |
pyod_tests.py | """
This file consists of utility functions, embedding model and function for model testing
"""
import numpy as np
import random
import os
from sklearn.model_selection import train_test_split
from keras.layers import Conv2D, MaxPooling2D, Input, Cropping2D, Add
from keras.layers import Flatten, Dense
from keras.model... |
def embeddings(input_dim, h=16, n_embeddings=64):
"""
Convolutional residual model for embeddings creations. Idea of this model is taken from this paper:
https://www.sciencedirect.com/science/article/pii/S2212827119302409
"""
input_shape = (input_dim, input_dim, 1)
inputs = Input(shape=input_... | """
residual block for convolutional encoder
"""
shape = input.shape
_, h, w, d = shape
l1 = Conv2D(n_filters, (5, 5), padding='valid', activation='elu')(input)
l2 = Conv2D(n_filters, (1, 1), padding='valid', activation='linear')(l1)
l3 = Cropping2D(cropping=2)(input)
added = Add()([l2, ... | identifier_body |
network.js | "use strict"
/**
Package for interacting on the network at a high level.
Copyright (c) 2014 Brian Muller
Copyright (c) 2015 OpenBazaar
**/
const ForgetfulStorage = require('./storage.js');
const KademliaProtocol = require('./protocol.js');
const Node = require('./node.js');
const Utils = require('./utils.js');
co... | (guid) {
/**
Given a guid return a `Node` object containing its ip and port or none if it's
not found.
Args:
guid: the 20 raw bytes representing the guid.
**/
console.log('[Kademlia Server] Crawling DHT to find IP for', guid);
let p = new Promise((resolve, reject) => {
let n... | resolveGUID | identifier_name |
network.js | "use strict"
/**
Package for interacting on the network at a high level.
Copyright (c) 2014 Brian Muller
Copyright (c) 2015 OpenBazaar
**/
const ForgetfulStorage = require('./storage.js');
const KademliaProtocol = require('./protocol.js');
const Node = require('./node.js');
const Utils = require('./utils.js');
co... |
bootstrap(addrs, promise) {
/**
Bootstrap the server by connecting to other known nodes in the network.
Args:
addrs: A `list` of (ip, port) `tuple` pairs. Note that only IP addresses
are acceptable - hostnames will cause an error.
**/
// If the transport hasn't been initialized y... | {
/**
Query an HTTP seed and return a `list` if (ip, port) `tuple` pairs.
Args:
Receives a list of one or more tuples Example [(seed, pubkey)]
seed: A `string` consisting of "ip:port" or "hostname:port"
pubkey: The hex encoded public key to verify the signature on the response
**/
... | identifier_body |
network.js | "use strict"
/**
Package for interacting on the network at a high level.
Copyright (c) 2014 Brian Muller
Copyright (c) 2015 OpenBazaar
**/
const ForgetfulStorage = require('./storage.js');
const KademliaProtocol = require('./protocol.js');
const Node = require('./node.js');
const Utils = require('./utils.js');
co... | // 'id': this.node.id,
// 'vendor': this.node.vendor,
// 'pubkey': this.node.pubkey,
// 'signing_key': this.protocol.signing_key,
// 'neighbors': this.bootstrappableNeighbors(),
// 'testnet': this.protocol.multiplexer.testne... | // 'alpha': this.alpha, | random_line_split |
network.js | "use strict"
/**
Package for interacting on the network at a high level.
Copyright (c) 2014 Brian Muller
Copyright (c) 2015 OpenBazaar
**/
const ForgetfulStorage = require('./storage.js');
const KademliaProtocol = require('./protocol.js');
const Node = require('./node.js');
const Utils = require('./utils.js');
co... | else {
for (let sp in listSeedPubkey) {
let seed = listSeedPubkey[sp][0];
let pubkey = listSeedPubkey[sp][1];
try {
console.log('Querying http://' + seed, 'for peers');
let address = seed.split(':');
http.get({
host: address[0],
port:... | {
console.log('Failed to query seed ', listSeedPubkey, ' from configuration file (ob.cfg).');
return nodes;
} | conditional_block |
attack.py | ## attack.py -- generate audio adversarial examples
##
## Copyright (C) 2019, Reto Weber <reto.a.weber@gmail.com>.
##
## This program is licenced under the BSD 2-Clause licence,
## contained in the LICENCE file in this directory.
import numpy as np
import tensorflow as tf
import argparse
import librosa
from shutil imp... | main(args, thisId) | conditional_block | |
attack.py | ## attack.py -- generate audio adversarial examples
##
## Copyright (C) 2019, Reto Weber <reto.a.weber@gmail.com>.
##
## This program is licenced under the BSD 2-Clause licence,
## contained in the LICENCE file in this directory.
import numpy as np
import tensorflow as tf
import argparse
import librosa
from shutil imp... | (self, audio, psyTh, lengths, target, regularizer = [0]):
sess = self.sess
# Initialize all of the variables
# TODO: each of these assign ops creates a new TF graph
# object, and they should be all created only once in the
# constructor. It works fine as long as you don't call
... | attack | identifier_name |
attack.py | ## attack.py -- generate audio adversarial examples
##
## Copyright (C) 2019, Reto Weber <reto.a.weber@gmail.com>.
##
## This program is licenced under the BSD 2-Clause licence,
## contained in the LICENCE file in this directory.
import numpy as np
import tensorflow as tf
import argparse
import librosa
from shutil imp... | else:
regularizer = np.array(list(map(lambda x: int(x), args.regularizer.split(','))))
deltas = attack.attack(audios,
psyThs,
lengths,
np.array(phrase),
regularizer=reg... | random_line_split | |
attack.py | ## attack.py -- generate audio adversarial examples
##
## Copyright (C) 2019, Reto Weber <reto.a.weber@gmail.com>.
##
## This program is licenced under the BSD 2-Clause licence,
## contained in the LICENCE file in this directory.
import numpy as np
import tensorflow as tf
import argparse
import librosa
from shutil imp... |
if __name__ == '__main__':
"""
Do the attack here.
This is all just boilerplate; nothing interesting
happens in this method.
We aonly support using the CTC-Loss.
"""
parser = argparse.ArgumentParser(description=None)
parser.add_argument('--in', type=str, dest="input",
... | print(thisId)
print(args)
with tf.Session() as sess:
audios = []
lengths = []
psyThs = []
psdMaxes = []
f = open(args.input, 'r')
temp = f.readlines()
temp = [row[:-1] for row in temp]
temp = [row.split(",") for row in temp]
inputFile... | identifier_body |
application.py | from flask import Flask, request, redirect, session, render_template, Response, make_response
from flask_cors import CORS, cross_origin
from flask_basicauth import BasicAuth
from datetime import datetime
from time import gmtime, strftime, mktime
from twilio.twiml.voice_response import Gather, VoiceResponse, Say
import ... |
# record new video/clip using Ziggeo
@app.route("/post-record", methods=["GET", "POST"])
@basic_auth.required
def post_record():
date = request.form['airdate']
zigURL = request.form['videoURL']
if date and zigURL:
print date
print zigURL
if save_to_s3_url(zigURL, date+".mp3") is True:
print "Ok, we downl... | return render_template(
'record.html',
name=os.environ['PODCASTNAME'],
key=os.environ['ZIGKEY']) | identifier_body |
application.py | from flask import Flask, request, redirect, session, render_template, Response, make_response
from flask_cors import CORS, cross_origin
from flask_basicauth import BasicAuth
from datetime import datetime
from time import gmtime, strftime, mktime
from twilio.twiml.voice_response import Gather, VoiceResponse, Say
import ... |
print "latest episode is: "+ tmp[-1]
return tmp[-1]
except Exception as e:
print "Error talking to s3"
raise
return False
# save file to s3
def s3save(filename, fileobj, folder):
try:
s3 = boto3.client( 's3', aws_access_key_id=os.environ['S3KI'], aws_secret_access_key=os.environ['S3SK'])
print "Conn... | fn = o['Key'].replace(os.environ['AUDIO'],'')
if "offair" in fn or fn is "":
pass
else:
#print fn
month, day, year, date = getdatefromfilename(fn)
if isvaliddate(month, day, year) is True and isnotfuturedate(month, day, year) is True:
tmp.append(fn)
#print tmp | conditional_block |
application.py | from flask import Flask, request, redirect, session, render_template, Response, make_response
from flask_cors import CORS, cross_origin
from flask_basicauth import BasicAuth
from datetime import datetime
from time import gmtime, strftime, mktime
from twilio.twiml.voice_response import Gather, VoiceResponse, Say
import ... | ():
print "start /play_schedule"
session['mp3url'] = request.values.get("RecordingUrl", None)
resp = VoiceResponse()
resp.say("Here's what you recorded")
resp.play(session['mp3url'])
# SCHEDULE
print "Gather digits for scheduling"
resp.say("Ok, we're almost done.")
gather = Gather(input='dtmf', timeout=15, nu... | play_schedule | identifier_name |
application.py | from flask import Flask, request, redirect, session, render_template, Response, make_response
from flask_cors import CORS, cross_origin
from flask_basicauth import BasicAuth
from datetime import datetime
from time import gmtime, strftime, mktime
from twilio.twiml.voice_response import Gather, VoiceResponse, Say
import ... | # amplify audio
amped_audio = amplify(audio)
# upload to s3
return s3save(filename, amped_audio, os.environ['AUDIO'])
except Exception as e:
print "Error getting, processing, or saving " + filename
raise
return False
def url_check(url):
ping = requests.get(url)
print(ping.status_code)
if ping.stat... | random_line_split | |
top500.py | urls = [
'http://facebook.com',
'http://twitter.com',
'http://google.com',
'http://youtube.com',
'http://linkedin.com',
'http://wordpress.org',
'http://instagram.com',
'http://pinterest.com',
'http://hugedomains.com',
'http://sedo.com',
'http://wikipedia.org',
'http://sedoparking.com',
'http://blogspot.com',
'http://ad... | 'http://bigcartel.com',
'http://acquirethisname.com',
'http://wp.me',
'http://cloudfront.net',
'http://unesco.org',
'http://ocn.ne.jp',
'http://gizmodo.com',
'http://skype.com',
'http://fb.me',
'http://upenn.edu',
'http://beian.gov.cn',
'http://a8.net',
'http://geocities.jp',
'http://storify.com',
'http://washington.ed... | 'http://ed.gov',
'http://phpbb.com',
'http://nbcnews.com',
'http://jiathis.com', | random_line_split |
broker.go | package doko
import (
"github.com/nine-bytes/log"
"github.com/nine-bytes/util"
"crypto/tls"
"net"
"time"
"runtime/debug"
"errors"
"sync"
)
type AuthenticateFunc func(authMsg *Auth) error
type ReqBrokerPermission func(reqBrokerMsg *ReqBroker) error
type Broker struct {
getAuthenticate AuthenticateFunc
r... |
// Remove a tunnel connection from the pool and return it
// If not tunnel connections are in the pool, request one
// and wait until it is available
// Returns an error if we couldn't get a tunnel because it took too long
// or the tunnel is closing
func (nc *NodeController) getTunnel(reqBrokerMsg *ReqBroker) (tunCo... | {
defer func() {
if err := recover(); err != nil {
log.Error("NodeController::stopper recover with error: %v, stack: %s", err, debug.Stack())
}
}()
defer nc.shutdown.Complete()
// wait until we're instructed to shutdown
nc.shutdown.WaitBegin()
nc.stopRWMutex.Lock()
nc.stopping = true
nc.stopRWMutex.Un... | identifier_body |
broker.go | package doko
import (
"github.com/nine-bytes/log"
"github.com/nine-bytes/util"
"crypto/tls"
"net"
"time"
"runtime/debug"
"errors"
"sync"
)
type AuthenticateFunc func(authMsg *Auth) error
type ReqBrokerPermission func(reqBrokerMsg *ReqBroker) error
type Broker struct {
getAuthenticate AuthenticateFunc
r... |
//log.Debug("NodeController::manager PING")
if _, ok := mRaw.(*Ping); ok {
nc.lastPing = time.Now()
// don't crash on panic
if err := util.PanicToError(func() { nc.out <- new(Pong) }); err != nil {
log.Debug("NodeController::manager send message to bc.out error: %v", err)
return
}
... | {
log.Debug("NodeController::manager chan bc.in closed")
return
} | conditional_block |
broker.go | package doko
import (
"github.com/nine-bytes/log"
"github.com/nine-bytes/util"
"crypto/tls"
"net"
"time"
"runtime/debug"
"errors"
"sync"
)
type AuthenticateFunc func(authMsg *Auth) error
type ReqBrokerPermission func(reqBrokerMsg *ReqBroker) error
type Broker struct {
getAuthenticate AuthenticateFunc
r... | // wait until we're instructed to shutdown
nc.shutdown.WaitBegin()
nc.stopRWMutex.Lock()
nc.stopping = true
nc.stopRWMutex.Unlock()
// close all plumbers
nc.plumbers.Each(func(elem interface{}) { elem.(*Plumber).Close() })
nc.plumbers.Clean()
// remove myself from the control registry
nc.broker.controllers... | }
}()
defer nc.shutdown.Complete()
| random_line_split |
broker.go | package doko
import (
"github.com/nine-bytes/log"
"github.com/nine-bytes/util"
"crypto/tls"
"net"
"time"
"runtime/debug"
"errors"
"sync"
)
type AuthenticateFunc func(authMsg *Auth) error
type ReqBrokerPermission func(reqBrokerMsg *ReqBroker) error
type Broker struct {
getAuthenticate AuthenticateFunc
r... | (getAuthenticate AuthenticateFunc, reqBrokerPermission ReqBrokerPermission) *Broker {
return &Broker{
getAuthenticate: getAuthenticate,
reqBrokerPermission: reqBrokerPermission,
controllers: util.NewRegistry(),
}
}
func (b *Broker) ListenAddr() net.Addr {
return b.listener.Addr()
}
func (b *Broke... | NewBroker | identifier_name |
iso_spec.rs | //! This module contains implementation of specification, its segments and associated operations
//!
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::io::Cursor;
use crate::iso8583::{bitmap, IsoError};
use crate::iso8583::field::{Field, ParseError};
use crate::iso8583::yaml_de::YMessageSegme... |
impl Spec {
/// Returns a IsoMsg after parsing data or an ParseError on failure
pub fn parse(&'static self, data: &mut Vec<u8>) -> Result<IsoMsg, ParseError> {
let msg = self.get_msg_segment(data);
if msg.is_err() {
return Err(ParseError { msg: msg.err().unwrap().msg });
}
... | {
IsoMsg {
spec,
msg: seg,
fd_map: HashMap::new(),
bmp: Bitmap::new(0, 0, 0),
}
} | identifier_body |
iso_spec.rs | //! This module contains implementation of specification, its segments and associated operations
//!
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::io::Cursor;
use crate::iso8583::{bitmap, IsoError};
use crate::iso8583::field::{Field, ParseError};
use crate::iso8583::yaml_de::YMessageSegme... | }
/// Sets F64 or F128 based on algo, padding and key provided via cfg
pub fn set_mac(&mut self, cfg: &Config) -> Result<(), IsoError> {
if cfg.get_mac_algo().is_none() || cfg.get_mac_padding().is_none() || cfg.get_mac_key().is_none() {
return Err(IsoError { msg: format!("missing mac_al... | } | random_line_split |
iso_spec.rs | //! This module contains implementation of specification, its segments and associated operations
//!
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::io::Cursor;
use crate::iso8583::{bitmap, IsoError};
use crate::iso8583::field::{Field, ParseError};
use crate::iso8583::yaml_de::YMessageSegme... |
match generate_pin_block(&cfg.get_pin_fmt().as_ref().unwrap(), pin, pan, &hex::decode(cfg.get_pin_key().as_ref().unwrap().as_str()).unwrap()) {
Ok(v) => {
self.set_on(52, hex::encode(v).as_str())
}
Err(e) => {
Err(IsoError { msg: e.msg })
... | {
return Err(IsoError { msg: format!("missing pin_format or key in call to set_pin") });
} | conditional_block |
iso_spec.rs | //! This module contains implementation of specification, its segments and associated operations
//!
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::io::Cursor;
use crate::iso8583::{bitmap, IsoError};
use crate::iso8583::field::{Field, ParseError};
use crate::iso8583::yaml_de::YMessageSegme... | (_name: &str) -> &'static Spec {
//TODO:: handle case of multiple specs, for now just return the first
ALL_SPECS.iter().find_map(|(_k, v)| Some(v)).unwrap()
}
/// Returns a empty IsoMsg that can be used to create a message
pub fn new_msg(spec: &'static Spec, seg: &'static MessageSegment) -> IsoMsg {
IsoMsg... | spec | identifier_name |
spatial.rs | use inle_alloc::temp::*;
use inle_app::app::Engine_State;
use inle_ecs::ecs_world::{Ecs_World, Entity, Evt_Entity_Destroyed};
use inle_events::evt_register::{with_cb_data, wrap_cb_data, Event_Callback_Data};
use inle_math::vector::Vec2f;
use inle_physics::collider::C_Collider;
use inle_physics::phys_world::{Collider_Ha... |
}
pub struct World_Chunks {
chunks: HashMap<Chunk_Coords, World_Chunk>,
to_destroy: Event_Callback_Data,
}
#[derive(Default, Debug)]
pub struct World_Chunk {
pub colliders: Vec<Collider_Handle>,
}
impl World_Chunks {
pub fn new() -> Self {
Self {
chunks: HashMap::new(),
... | {
Vec2f {
x: self.x as f32 * CHUNK_WIDTH,
y: self.y as f32 * CHUNK_HEIGHT,
}
} | identifier_body |
spatial.rs | use inle_alloc::temp::*;
use inle_app::app::Engine_State;
use inle_ecs::ecs_world::{Ecs_World, Entity, Evt_Entity_Destroyed};
use inle_events::evt_register::{with_cb_data, wrap_cb_data, Event_Callback_Data};
use inle_math::vector::Vec2f;
use inle_physics::collider::C_Collider;
use inle_physics::phys_world::{Collider_Ha... | pub fn to_world_pos(self) -> Vec2f {
Vec2f {
x: self.x as f32 * CHUNK_WIDTH,
y: self.y as f32 * CHUNK_HEIGHT,
}
}
}
pub struct World_Chunks {
chunks: HashMap<Chunk_Coords, World_Chunk>,
to_destroy: Event_Callback_Data,
}
#[derive(Default, Debug)]
pub struct Worl... | x: (pos.x / CHUNK_WIDTH).floor() as i32,
y: (pos.y / CHUNK_HEIGHT).floor() as i32,
}
}
| random_line_split |
spatial.rs | use inle_alloc::temp::*;
use inle_app::app::Engine_State;
use inle_ecs::ecs_world::{Ecs_World, Entity, Evt_Entity_Destroyed};
use inle_events::evt_register::{with_cb_data, wrap_cb_data, Event_Callback_Data};
use inle_math::vector::Vec2f;
use inle_physics::collider::C_Collider;
use inle_physics::phys_world::{Collider_Ha... | (&self) -> usize {
self.chunks.len()
}
pub fn add_collider(&mut self, cld_handle: Collider_Handle, pos: Vec2f, extent: Vec2f) {
let mut chunks = vec![];
self.get_all_chunks_containing(pos, extent, &mut chunks);
for coords in chunks {
self.add_collider_coords(cld_hand... | n_chunks | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.