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
Lt.ts
{ 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
ugoti', projectsToVolunteer: 'Aš noriu savanoriauti', projectSaved: 'Išsaugotas', projectsYouVolunteer: 'Jūs esate savanoris', projectStart: 'Projektas prasidės', projectEnd: 'Projektas baigsis', projectGoBack: 'Grįžti', projectHeader: 'Projekto puslapis', ...
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
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
Hand) contains(card Card) bool { for _, c := range h { if (c.Suit == card.Suit) && (c.Rank == card.Rank) { return true } } return false } func nonRepeatingCards(h Hand) Hand { var ret Hand m := make(map[Rank]bool) for _, card := range h { if _, ok := m[card.Rank]; !ok { ret = append(ret, card) m[...
rn 1, r1[0].HandType, r1[0].Cards } else {
conditional_block
card.go
...) 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; i < len(cards)-1; i++ { if cards[i+1].Rank-cards[i].Rank != 1 { return false } } return true } ...
([]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
...) 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; i < len(cards)-1; i++ { if cards[i+1].Rank-cards[i].Rank != 1 { return false } } return true } ...
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
const CARD_TITLE_FONT: &'static str = "Teko-Regular.ttf"; pub const CARD_BACKGROUND_IMG: &'static str = "card_bg.png"; #[derive(Derivative, Default)] #[derivative(Debug)] pub struct Assets { #[derivative(Debug = "ignore")] pub fonts: HashMap<String, Box<Font>>, // we borrow fonts to create new data: there's n...
(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
const CARD_TITLE_FONT: &'static str = "Teko-Regular.ttf"; pub const CARD_BACKGROUND_IMG: &'static str = "card_bg.png"; #[derive(Derivative, Default)] #[derivative(Debug)] pub struct Assets { #[derivative(Debug = "ignore")] pub fonts: HashMap<String, Box<Font>>, // we borrow fonts to create new data: there's n...
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
const CARD_TITLE_FONT: &'static str = "Teko-Regular.ttf"; pub const CARD_BACKGROUND_IMG: &'static str = "card_bg.png"; #[derive(Derivative, Default)] #[derivative(Debug)] pub struct Assets { #[derivative(Debug = "ignore")] pub fonts: HashMap<String, Box<Font>>, // we borrow fonts to create new data: there's n...
PlayerControl::Human => None, PlayerControl::AI => Some(AI::new()) }; println!("Loading done"); BoardState { player: player, turn: 1, hand: Box::new(hand), deck: Box::new(draw_deck), globals: NumberMap::new(), stores: Box::new(vec!(build_stor...
{ 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
, mesh.faces.shape[0], [bsize])) batch_barys = np.array(uniform_bary(np.random.uniform(size=[bsize, 2]))) batch_faces = mesh.faces[batch_face_inds] batch_normals = mesh.face_normals[batch_face_inds] batch_pts = np.sum(mesh.vertices[batch_faces] * batch_barys[...,None], 1) return batch_pts, batch_normals gt...
eval( args, model )
conditional_block
train_3d_occupancy.py
} - Outside obj: {np.sum(1 - test_labels_easy):d}") print(f"Test points [hard] - Inside obj: {np.sum(test_labels_hard):d} - Outside obj: {np.sum(1 - test_labels_hard):d}") return { 'easy': (test_pts_easy, test_labels_easy), 'hard': (test_pts_hard, test_labels_hard) } ##################...
(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
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
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
() { 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
, *flagPkg, string(constBuf), string(mapBuf))), 0644, ) if err != nil { log.Fatal(err) } // format err = exec.Command("goimports", "-w", *flagOut).Run() if err != nil { log.Fatal(err) } // format err = exec.Command("gofmt", "-s", "-w", *flagOut).Run() if err != nil { log.Fatal(err) } } // loadKeys...
if len(s) != 3 { panic(fmt.Sprintf("expected character, got: %s", s)) } return rune(s[1]) } // 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)) } r...
{ 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
"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
[0] key.Windows = sc[1] } keys[r] = key } var printableKeyRE = regexp.MustCompile(`\{DomCode::(.+?), \{(.+?), (.+?)\}\}`) // loadPrintable loads the printable key definitions. func loadPrintable(keys map[rune]kb.Key, keycodeConverterMap, domKeyMap map[string][]string, layoutBuf []byte, scanCodeMap map[string][]i...
{ return nil, err }
conditional_block
XGBoost_BayesOpt.py
_y']) merge['ground_ratio'] = merge['gro_wat_3']/merge['total_withdrawal_3'] merge['fresh_ratio'] = merge['total_withdrawal_1']/merge['total_withdrawal_3'] merge['industry_ratio'] = merge['ind_9']/merge['total_withdrawal_3'] merge['irrigation_ratio'] = merge['irrigation_3']/merge['total_withdrawal_3'] merge['livesto...
params['max_depth'] = int(max_depth) params['subsample'] = max(min(subsample,
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
_y']) merge['ground_ratio'] = merge['gro_wat_3']/merge['total_withdrawal_3'] merge['fresh_ratio'] = merge['total_withdrawal_1']/merge['total_withdrawal_3'] merge['industry_ratio'] = merge['ind_9']/merge['total_withdrawal_3'] merge['irrigation_ratio'] = merge['irrigation_3']/merge['total_withdrawal_3'] merge['livesto...
(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
total_withdrawal_3'] merge['fresh_ratio'] = merge['total_withdrawal_1']/merge['total_withdrawal_3'] merge['industry_ratio'] = merge['ind_9']/merge['total_withdrawal_3'] merge['irrigation_ratio'] = merge['irrigation_3']/merge['total_withdrawal_3'] merge['livestock_ratio'] = merge['livestock_3']/merge['total_withdrawal_...
params['subsample'] = max(min(subsample, 1), 0) params['gamma'] = max(gamma, 0)
random_line_split
XGBoost_BayesOpt.py
_y']) merge['ground_ratio'] = merge['gro_wat_3']/merge['total_withdrawal_3'] merge['fresh_ratio'] = merge['total_withdrawal_1']/merge['total_withdrawal_3'] merge['industry_ratio'] = merge['ind_9']/merge['total_withdrawal_3'] merge['irrigation_ratio'] = merge['irrigation_3']/merge['total_withdrawal_3'] merge['livesto...
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
.Sprintf(`<input type="hidden" name="%v" value="%v"/>`, XSRF_TAG, c.XsrfValue())) } // WriteString writes string data into the response object. func (c *Action) WriteBytes(bytes []byte) error { _, err := c.ResponseWriter.Write(bytes) if err != nil { c.App.Server.Logger.Println("Error during write: ", err) } re...
} } 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
.Sprintf(`<input type="hidden" name="%v" value="%v"/>`, XSRF_TAG, c.XsrfValue())) } // WriteString writes string data into the response object. func (c *Action) WriteBytes(bytes []byte) error { _, err := c.ResponseWriter.Write(bytes) if err != nil { c.App.Server.Logger.Println("Error during write: ", err) } re...
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
.Sprintf(`<input type="hidden" name="%v" value="%v"/>`, XSRF_TAG, c.XsrfValue())) } // WriteString writes string data into the response object. func (c *Action) WriteBytes(bytes []byte) error { _, err := c.ResponseWriter.Write(bytes) if err != nil { c.App.Server.Logger.Println("Error during write: ", err) } re...
() 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
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
KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Implements CNOS config over REST API Client """ from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils from networking_lenovo.ml2...
############ 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
KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Implements CNOS config over REST API Client """ from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils from networking_lenovo.ml2...
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
KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Implements CNOS config over REST API Client """ from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils from networking_lenovo.ml2...
pvid = intf_info['pvid'] mode = 'trunk' resp = self._conf_intf(conn, interface, mode, pvid, new_vlist) self._check_process_resp(resp) def _rem_intf_from_vlan(self, conn, vlan_id, interface): """ Internal method to remove an interface from a vlan Parameters...
""" 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
KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Implements CNOS config over REST API Client """ from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils from networking_lenovo.ml2...
(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
USA. # ############################################################################## """ Provide a feature not present into difflib, which is generate a colored diff from a diff file/string. This code is original form ERP5VCS and was moved to here for be used in general ERP5. XXX The organisation of DiffUtils...
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
# 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
USA. # ############################################################################## """ Provide a feature not present into difflib, which is generate a colored diff from a diff file/string. This code is original form ERP5VCS and was moved to here for be used in general ERP5. XXX The organisation of DiffUtils...
(self): """ Return type of modification : addition, deletion, none
_getModif
identifier_name
DiffUtils.py
_TAB = NBSP*8 NO_DIFF_COLOR = 'white' MODIFIED_DIFF_COLOR = 'rgb(253, 228, 6);'#light orange DELETED_DIFF_COLOR = 'rgb(253, 117, 74);'#light red ADDITION_DIFF_COLOR = 'rgb(83, 253, 74);'#light green class DiffFile(object): """ # Members : - path : path of the modified file - children : sub codes modified ...
return 'deletion'
conditional_block
memorycache.js
// you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASI...
// // 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
; // // var cache = new memoryCache.MemoryCache(maxEntries, trimCount); // // cache.set(key, val); // // var val = cache.get(key); // // // maxEntries - Maximum entries for cache. // // A value of 0 means no limit. // // Remember, a cache without reasonable bounds is a memory le...
{ 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
// you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASI...
(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
you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS,...
// // 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
GRESS_STATUS = dict(COMPLETED='completed', STARTED='started', TODO='todo') class IEMRunInfoReader: """ Illumina Experimental Manager RunInfo xml reader. """ def __init__(self, f): self.xml_file = f self.tree = ET.parse(self.xml_file) self.root = self.tree.getroot() def ge...
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
_STATUS = dict(COMPLETED='completed', STARTED='started', TODO='todo') class IEMRunInfoReader: """ Illumina Experimental Manager RunInfo xml reader. """ def __init__(self, f): self.xml_file = f self.tree = ET.parse(self.xml_file) self.root = self.tree.getroot() def get_rea...
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
_STATUS = dict(COMPLETED='completed', STARTED='started', TODO='todo') class IEMRunInfoReader: """ Illumina Experimental Manager RunInfo xml reader. """ def
(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
GRESS_STATUS = dict(COMPLETED='completed', STARTED='started', TODO='todo') class IEMRunInfoReader: """ Illumina Experimental Manager RunInfo xml reader. """ def __init__(self, f): self.xml_file = f self.tree = ET.parse(self.xml_file) self.root = self.tree.getroot() def ge...
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
format(chain.ndd_index)) ndd_used[chain.ndd_index] = True for vtx_index in chain.vtx_indices: if vtx_used[vtx_index]: raise KidneyOptimException("Vertex {} used more than once".format(vtx_index)) vtx_used[vtx_index] = True for cycle in opt_result....
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
# 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.ndd_index] = True...
"""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
# 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
(chain.ndd_index)) ndd_used[chain.ndd_index] = True for vtx_index in chain.vtx_indices: if vtx_used[vtx_index]: raise KidneyOptimException("Vertex {} used more than once".format(vtx_index)) vtx_used[vtx_index] = True for cycle in opt_result.cycles...
(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
(var i = 0; i < document.links.length; i++) document.links[i].onfocus = function() { this.blur() } var script = document.createElement("script"); script.setAttribute("src", "static/guide.js?v=1.0"); script.setAttribute("type", "text/javascript"); script.setAttribute("charset", "utf-8"...
//第一张图片设置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
(var i = 0; i < document.links.length; i++) document.links[i].onfocus = function() { this.blur() } var script = document.createElement("script"); script.setAttribute("src", "static/guide.js?v=1.0"); script.setAttribute("type", "text/javascript"); script.setAttribute("charset", "utf-8"...
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
(var i = 0; i < document.links.length; i++) document.links[i].onfocus = function() { this.blur() } var script = document.createElement("script"); script.setAttribute("src", "static/guide.js?v=1.0"); script.setAttribute("type", "text/javascript"); script.setAttribute("charset", "utf-8"...
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
(var i = 0; i < document.links.length; i++) document.links[i].onfocus = function() { this.blur() } var script = document.createElement("script"); script.setAttribute("src", "static/guide.js?v=1.0"); script.setAttribute("type", "text/javascript"); script.setAttribute("charset", "utf-8"...
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
UL` byte. This lets us do /// a range query on the set when given the episode ID to find the TV show ID. const TVSHOWS: &str = "episode.tvshows.fst"; /// An episode index that supports retrieving season and episode information /// quickly. #[derive(Debug)] pub struct Index { seasons: fst::Set, tvshows: fst::Se...
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
let Some(episode_bytes) = stream.next() { episodes.push(read_episode(episode_bytes)?); } Ok(episodes) } /// Return a sequence of episodes for the given TV show IMDb identifier and /// season number. /// /// The episodes are sorted in order of episode number. Episodes wi...
{ 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
We claim it is safe to open the following memory map because we // don't mutate them and no other process (should) either. let seasons = unsafe { fst_set_file(index_dir.join(SEASONS))? }; let tvshows = unsafe { fst_set_file(index_dir.join(TVSHOWS))? }; Ok(Index { seasons: se...
to_optional_epnum
identifier_name
import_export_classes.py
_on_fail=False, verbose=True): self.processed = 0 self.failed = 0 self.failed_ids = [] self.missing_keys = Counter() self.raise_on_fail = raise_on_fail self.verbose = verbose from .basic_utils import dotkeys def _detect_zip(self, path): filename = os.pa...
( 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
_on_fail=False, verbose=True): self.processed = 0 self.failed = 0 self.failed_ids = [] self.missing_keys = Counter() self.raise_on_fail = raise_on_fail self.verbose = verbose from .basic_utils import dotkeys def _detect_zip(self, path): filename = os.pa...
""" if not mapping: return document new_document = {v: document[k] for k, v in mapping.items() if k in document} # Keep track of missing keys self.missing_keys.update([k for k in mapping if k not in document]) # Document errors for missing documents i...
"""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
path): filename = os.path.basename(path) for zip_ext in ["gz", "bz2"]: if filename[-len(zip_ext) :] == zip_ext: return zip_ext return False def open_file(self, filename, mode="r", force=False, compression="autodetect"): if mode not in ["w", "wb", "wt", "...
If the destination is a folder, a filename will be generated.
random_line_split
import_export_classes.py
_on_fail=False, verbose=True): self.processed = 0 self.failed = 0 self.failed_ids = [] self.missing_keys = Counter() self.raise_on_fail = raise_on_fail self.verbose = verbose from .basic_utils import dotkeys def _detect_zip(self, path): filename = os.pa...
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
> std::fmt::Display for CsvDesc<'a> { fn
(&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
} 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
= BufReader::new(csv_file); let mut csv_line_iter = csv_reader.lines(); let csv_header: String = match csv_line_iter.next() { Some(result) => match result { Err(why) => return Err(format!("error getting csv header: {}", why)), Ok(header) => header, }, None => r...
let row_2 = match get_csv_row(&csv_desc_2, index_2) { Ok(row) => row,
random_line_split
verify.rs
is_nfkc(path) => path.chars().nfc().collect::<String>().into(), _ => path, } } impl FileWithSize { fn from_disk(path_orig: &Path, krate_root: &OsStr) -> Self { // we need to cut off .cargo/registry/src/github.com-1ecc6299db9ec823/ let index = path_orig .iter() .e...
dir.push(&comp1_with_crate_ext); // bytes-0.4.12.crate dir.into_iter().collect::<PathBuf>() } /// 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 = GzD...
{ // 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
!is_nfkc(path) => path.chars().nfc().collect::<String>().into(), _ => path, } } impl FileWithSize { fn from_disk(path_orig: &Path, krate_root: &OsStr) -> Self { // we need to cut off .cargo/registry/src/github.com-1ecc6299db9ec823/ let index = path_orig .iter() ...
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
is_nfkc(path) => path.chars().nfc().collect::<String>().into(), _ => path, } } impl FileWithSize { fn from_disk(path_orig: &Path, krate_root: &OsStr) -> Self { // we need to cut off .cargo/registry/src/github.com-1ecc6299db9ec823/ let index = path_orig .iter() .e...
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
is_nfkc(path) => path.chars().nfc().collect::<String>().into(), _ => path, } } impl FileWithSize { fn from_disk(path_orig: &Path, krate_root: &OsStr) -> Self { // we need to cut off .cargo/registry/src/github.com-1ecc6299db9ec823/ let index = path_orig .iter() .e...
(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
= fs::read_to_string("site-config.toml") { toml::from_str(&s)? } else { Config { keys: Keys { github_api_token: std::env::var("GITHUB_API_TOKEN").ok(), github_webhook_secret: std::env::var("GITHUB_WEBHOOK_SECRET").ok(), ...
// 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
SiteCtxt` from database url pub async fn from_db_url(db_url: &str) -> anyhow::Result<Self> { let pool = Pool::open(db_url); let mut conn = pool.connection().await; let index = db::Index::load(&mut *conn).await; let config = if let Ok(s) = fs::read_to_string("site-config.toml") { ...
} } 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
{ // do nothing, for now, though eventually we'll want an artifact queue }
conditional_block
load.rs
( // InProgress MR go first (false < true) mr.parent_sha().is_some(), mr.pr().unwrap_or(0), c.sha.clone(), ) }); for (c, _) in level { done.insert(c.sha.clone()); } finished += level_len; ...
{ 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
{ 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
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
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-00d5d224c11f12854", // Asia Pacific...
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
"ap-northeast-1": "ami-029f1fff7d250aa95", // Asia Pacific (Tokyo). "ap-northeast-2": "ami-0b2ea3e1fb7e0a0dc", // Asia Pacific (Seoul). "ap-southeast-1": "ami-00d5d224c11f12854", // Asia Pacific (Singapore). "ap-southeast-2": "ami-03ad7f293fb551d91", // Asia Pacific (Sydney). "ap-south-1": "ami-03f5be5363...
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
} // 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
212827119302409 """ input_shape = (input_dim, input_dim, 1) inputs = Input(shape=input_shape) x = Conv2D(h, (7, 7), input_shape=input_shape, padding='valid', activation="elu")(inputs) x = MaxPooling2D(pool_size=(2, 2), strides=(2, 2))(x) x = residual(h, x) x = residual(h, x) x = residual...
max_recall = recall max_recall_id = i
conditional_block
pyod_tests.py
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
return img def image_generator(img_list): """ Image generator function from image list. Yields image and label. Label is taken from containing folder name """ while True: img = random.choice(img_list) label = os.path.basename(os.path.dirname(img)) # add label function according to...
(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
) return img def image_generator(img_list): """ Image generator function from image list. Yields image and label. Label is taken from containing folder name """ while True: img = random.choice(img_list) label = os.path.basename(os.path.dirname(img)) # add label function according ...
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
IP addresses are acceptable - hostnames will cause an error. **/ // If the transport hasn't been initialized yet, wait a second console.log('[DHT Server] Bootstrapping with', addrs.length, 'peers, finding neighbors...'); let ds = []; let that = this; for (let addrIndex in addrs) { ...
(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
let address = seed.split(':'); http.get({ host: address[0], port: address[1], path: '?format=json' }, (res) => { const statusCode = res.statusCode; const contentType = res.headers['content-type']; const encoding = res....
{ /** 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
.sha512(n.publicKey) // hash_pow = h[40:] // if int(hash_pow[:6], 16) >= 50 or hexlify(n.guid) != h[:40]: // raise Exception('Invalid GUID') // node = Node(n.guid, addr[0], addr[1], n.publicKey, // ...
// 'alpha': this.alpha,
random_line_split
network.js
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
= int(2**np.ceil(np.log2(frame_length))) win = np.sqrt(8.0 / 3.) * librosa.core.stft( y=audio, n_fft=n_fft, hop_length=frame_step, win_length=frame_length, center=False, pad_mode='constant') z = abs(win / window_size) psd = 10 * np.log10(z * z + 0.0000000...
main(args, thisId)
conditional_block
attack.py
_beam_search_decoder(logits, lengths, merge_repeated=False, beam_width=100) def clipBatch(self, delta, psyTh, regularizer, psdMaxes, max_audio_len, window_size, step_per_window): # This is the PsyClip. It can take a batch of deltas and clips five times to get below psyTh. deltaShape = delta.shape ...
attack
identifier_name
attack.py
# if we have (or if it's the final epoch) then we # should record our progress and decrease the # regularizer constant. for ii in range(self.batch_size): if(pl[ii] > regularizer[ii]): # PsyLoss (pl) is too highe...
random_line_split
attack.py
== 0: (d, d2, plWAV, loss, r_logits, new_input, r_out, regularizer) = sess.run(( self.delta, self.apply_delta, self.psyLoss, self.loss, self.logits, self.new_input, self.decoded, self.regu...
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
PODCASTNAME']+ ' ~ '+ date_locale feed['streamUrl'] = url else: print "off-air" # no content found feed['titleText'] = os.environ['PODCASTNAME']+' is off-air right now, check back again soon!' feed['streamUrl'] = os.environ['FPATH']+os.environ['AUDIO']+"offair_"+str(randint(0, 4))+".mp3" feed_json = json.dum...
return render_template( 'record.html', name=os.environ['PODCASTNAME'], key=os.environ['ZIGKEY'])
identifier_body
application.py
=os.environ['S3KI'], aws_secret_access_key=os.environ['S3SK']) print "Connected to s3!!" resp = s3.list_objects_v2( Bucket=os.environ['BUCKET'], Prefix=os.environ['AUDIO']) tmp = [] for o in resp['Contents']:
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
#AMPLIFY!!!! ff = FFmpeg( inputs={"pipe:0":None}, outputs={"pipe:1": "-y -af \"highpass=f=200, lowpass=f=3000, loudnorm=I=-14:TP=-2.0:LRA=11\" -b:a 256k -f mp3"} ) print ff.cmd stdout, stderr = ff.run( input_data=req_data, stdout=subprocess.PIPE) #print stdout #print stderr prin...
play_schedule
identifier_name
application.py
=os.environ['S3KI'], aws_secret_access_key=os.environ['S3SK']) print "Connected to s3!!" resp = s3.list_objects_v2( Bucket=os.environ['BUCKET'], Prefix=os.environ['AUDIO']) tmp = [] for o in resp['Contents']: fn = o['Key'].replace(os.environ['AUDIO'],'') if "offair" in fn or fn is "": ...
# 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
'http://yandex.ru', 'http://digg.com', 'http://mozilla.org', 'http://huffingtonpost.com', 'http://stumbleupon.com', 'http://123-reg.co.uk', 'http://issuu.com', 'http://creativecommons.org', 'http://wsj.com', 'http://miibeian.gov.cn', 'http://ovh.net', 'http://go.com', 'http://imdb.com', 'http://nih.gov', 'http://secure...
'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
(chan net.Conn, pxyPoolSize), lastPing: time.Now(), writerShutdown: util.NewShutdown(), readerShutdown: util.NewShutdown(), managerShutdown: util.NewShutdown(), shutdown: util.NewShutdown(), broker: b, plumbers: util.NewSet(0), } // register the control if old := b.cont...
{ 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
: b.control(conn, msg) case *RegTunnel: b.tunnel(conn, msg) case *ReqBroker: b.broker(conn, msg) default: conn.Close() } }(conn) } } func (b *Broker) control(ctlConn net.Conn, authMsg *Auth) { // authenticate firstly if err := b.getAuthenticate(authMsg); err != nil { ctlConn.SetWr...
//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
err.Error()}) ctlConn.Close() return } // create the object bc := &NodeController{ id: authMsg.Id, authMsg: authMsg, ctlConn: ctlConn, out: make(chan Message), in: make(chan Message), tunnels: make(chan net.Conn, pxyPoolSize), lastPing...
} }() defer nc.shutdown.Complete()
random_line_split
broker.go
(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
IsoError> { let mut selector = String::new(); let mut f2d_map = HashMap::new(); let mut in_buf = Cursor::new(data); for f in &self.header_fields { match f.parse(&mut in_buf, &mut f2d_map) { Ok(_) => { selector.extend(f.to_string(f2d_map....
{ IsoMsg { spec, msg: seg, fd_map: HashMap::new(), bmp: Bitmap::new(0, 0, 0), } }
identifier_body
iso_spec.rs
} /// This struct represents a segment in the Spec (a auth request, a response etc) pub struct MessageSegment { pub(in crate::iso8583) name: String, #[allow(dead_code)] pub(in crate::iso8583) id: u32, pub(in crate::iso8583) selector: Vec<String>, pub(in crate::iso8583) fields: Vec<Box<dyn Field>>, ...
} /// 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 struct represents a segment in the Spec (a auth request, a response etc) pub struct MessageSegment { pub(in crate::iso8583) name: String, #[allow(dead_code)] pub(in crate::iso8583) id: u32, pub(in crate::iso8583) selector: Vec<String>, pub(in crate::iso8583) fields: Vec<Box<dyn Field>>, ...
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
_from_header(&self, header_val: &str) -> Result<&MessageSegment, IsoError> { for msg in &self.messages { if msg.selector.contains(&header_val.to_string()) { return Ok(msg); } } return Err(IsoError { msg: format!("message not found for header - {}", header_...
spec
identifier_name
spatial.rs
pub fn from_pos(pos: Vec2f) -> Self { Self { x: (pos.x / CHUNK_WIDTH).floor() as i32, y: (pos.y / CHUNK_HEIGHT).floor() as i32, } } pub fn to_world_pos(self) -> Vec2f
} 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
pub fn from_pos(pos: Vec2f) -> Self { Self {
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
pub fn from_pos(pos: Vec2f) -> Self { Self { x: (pos.x / CHUNK_WIDTH).floor() as i32, y: (pos.y / CHUNK_HEIGHT).floor() as i32, } } pub fn to_world_pos(self) -> Vec2f { Vec2f { x: self.x as f32 * CHUNK_WIDTH, y: self.y as f32 * CHUNK_HEIG...
(&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
utils.py
: bool = False): logger = logging.getLogger() if debug: log_level = logging.DEBUG else: log_level = logging.INFO logger.setLevel(log_level) if not any(type(i) == logging.StreamHandler for i in logger.handlers): sh = logging.StreamHandler() sh.setLevel(log_level) ...
true = [] for i in tqdm(range(0, math.ceil(len(dataset) / n_batch))): data = dataset[n_batch * i:n_batch * (i + 1)] graph, label = model.batchify(data, ctx) output = model(graph) predictions = nd.argmax(output, axis=2) # Masking output to max(length_of_output, length_of_l...
''' Measures the mean (over instances) of the characterwise edit distance (Levenshtein distance) between predicted and true names ''' logged_example = False with data_loader as data_loader: cum_edit_distance = 0 for split_batch, batch_length in tqdm(data_loader, total=data_loader.total_b...
identifier_body