file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
main.js
// Dependencies import Map from 'ol/map'; import View from 'ol/view'; import TileLayer from 'ol/layer/tile'; import OSM from 'ol/source/osm' import Draw from 'ol/interaction/draw' import VectorSource from 'ol/source/vector' import VectorLayer from 'ol/layer/vector' import ImageLayer from 'ol/layer/image' import Proj fr...
){ var extent = map.getView().calculateExtent(); var resolution = map.getView().getResolution(); var radius = 40*resolution; for (var i in Speaker.eightChannelSpeakerCoordinateRatios){ var x = speakerCoordinateRatios[i][0]; var y = speakerCoordinateRatios[i][1]; var coord = [(extent[2]-extent[0])*x+...
ositionSpeakers(
identifier_name
main.js
// Dependencies import Map from 'ol/map'; import View from 'ol/view'; import TileLayer from 'ol/layer/tile'; import OSM from 'ol/source/osm' import Draw from 'ol/interaction/draw' import VectorSource from 'ol/source/vector' import VectorLayer from 'ol/layer/vector' import ImageLayer from 'ol/layer/image' import Proj fr...
function positionSpeakers(){ var extent = map.getView().calculateExtent(); var resolution = map.getView().getResolution(); var radius = 40*resolution; for (var i in Speaker.eightChannelSpeakerCoordinateRatios){ var x = speakerCoordinateRatios[i][0]; var y = speakerCoordinateRatios[i][1]; var coord ...
var resolution = map.getView().getResolution(); var radius = 15*resolution; for (var i in Remote.remotes){ //TODO some error here, seems like remotes gets out of sync somehow... Remote.remotes[i].getGeometry().setRadius(radius); } }
identifier_body
main.js
// Dependencies import Map from 'ol/map'; import View from 'ol/view'; import TileLayer from 'ol/layer/tile'; import OSM from 'ol/source/osm' import Draw from 'ol/interaction/draw' import VectorSource from 'ol/source/vector' import VectorLayer from 'ol/layer/vector' import ImageLayer from 'ol/layer/image' import Proj fr...
if (msg.type == "params"){ updateRemoteParams(msg.value) } else if (msg.type == "newRemote"){ console.log('new remote: '+msg.uid) var remote = new Remote(msg.uid, Proj.fromLonLat(msg.coordinates), audienceSource); var msg = {type:"subscribe", uid:msg.uid}; try{ nodeServerW...
random_line_split
main.js
// Dependencies import Map from 'ol/map'; import View from 'ol/view'; import TileLayer from 'ol/layer/tile'; import OSM from 'ol/source/osm' import Draw from 'ol/interaction/draw' import VectorSource from 'ol/source/vector' import VectorLayer from 'ol/layer/vector' import ImageLayer from 'ol/layer/image' import Proj fr...
else { cmdBox.hidden = true; cmdBox.innerHTML = "" } }); map.addInteraction(dragBox); map.addInteraction(select); // Connection Interaction function onConnectable(coordinate){ var features = audienceSource.getFeatures().map(function(f){return f.type}) var a = audienceSource.getFeaturesAtCoordinate(co...
cmdBox.hidden = false; cmdBox.innerHTML = ""; for(var i in innerHTML){ cmdBox.appendChild(innerHTML[i]) } }
conditional_block
iptool.py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Author:Cyan """ Try copying the cluttered IP range contents below to the file and use: python3 ipParse.py -f filename --smart 192.168.1.0 192.168.2.1/24,192.168.3.4-7,192.168.5.1-.192.168.5.34、192.176.34.6\26、192.187.34.2-67,192.111.111.111,192.168.5.1 - 192.168.5.34 19...
main()
if __name__ == '__main__':
random_line_split
iptool.py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Author:Cyan """ Try copying the cluttered IP range contents below to the file and use: python3 ipParse.py -f filename --smart 192.168.1.0 192.168.2.1/24,192.168.3.4-7,192.168.5.1-.192.168.5.34、192.176.34.6\26、192.187.34.2-67,192.111.111.111,192.168.5.1 - 192.168.5.34 19...
break else: print(info[0],info[1]) # print(sigleIP) for i,v in sigleIP.items(): print(f"### {i}\t"+ip_location(i)) for t in v: print(t) print("### Nmap") print(f"sudo nmap -Pn -sS -sV -T3 -p1-65535 --open {' '.join([ip for ip in sigleIP.keys()])}") def ...
if ip in sigleIP.keys(): sigleIP[ip].append(info[0])
conditional_block
iptool.py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Author:Cyan """ Try copying the cluttered IP range contents below to the file and use: python3 ipParse.py -f filename --smart 192.168.1.0 192.168.2.1/24,192.168.3.4-7,192.168.5.1-.192.168.5.34、192.176.34.6\26、192.187.34.2-67,192.111.111.111,192.168.5.1 - 192.168.5.34 19...
pawn(ip_location, ip), gevent.spawn(ip_reverse, ip), ] gevent.joinall(jobs) for job in jobs: print(job.value) print("-"*100) def extract_host(url): url=url.strip() if (not url.startswith("http") and not url.startswith("//")): url="https://"+ur...
# gevent.s
identifier_name
iptool.py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Author:Cyan """ Try copying the cluttered IP range contents below to the file and use: python3 ipParse.py -f filename --smart 192.168.1.0 192.168.2.1/24,192.168.3.4-7,192.168.5.1-.192.168.5.34、192.176.34.6\26、192.187.34.2-67,192.111.111.111,192.168.5.1 - 192.168.5.34 19...
def main(): Useage = """ single # ip # show local ip # ip 8.8.8.8 # show location && provider # ip www.baidu.com # show ip and location multi # ip -c 8.8.8.8/24 [--location] # show cidr # ip -f iplist.txt [--format] [--archive] [--tld] [--location] # list all ip #...
# print(info[1]) for info in info_pool: for ip in info[1]: if ip in sigleIP.keys(): sigleIP[ip].append(info[0]) break else: print(info[0],info[1]) # print(sigleIP) for i,v in sigleIP.items(): print(f"### {i}\t"+ip_...
identifier_body
electron.js
import React, { Component } from 'react'; import Prism from 'prismjs'; import { CodeBlock, Section, Link, ComponentDescription, SideScrollMenu, PageTitle, ComponentSubtitle, CodeInline, Helmet, } from '@components'; const sections = [ { name: 'Install' }, { name: 'Setup' }, { name: 'Usage' }, ...
render() { return ( <div style={styles.container}> <Helmet title={'React Native Electron'} /> <PageTitle>Electron</PageTitle> <ComponentSubtitle description={ 'Build cross platform desktop apps with JavaScript, HTML, and CSS' } /> <Si...
{ Prism.highlightAll(); }
identifier_body
electron.js
import React, { Component } from 'react'; import Prism from 'prismjs'; import { CodeBlock, Section, Link, ComponentDescription, SideScrollMenu, PageTitle, ComponentSubtitle, CodeInline, Helmet, } from '@components'; const sections = [ { name: 'Install' }, { name: 'Setup' }, { name: 'Usage' }, ...
() { Prism.highlightAll(); } render() { return ( <div style={styles.container}> <Helmet title={'React Native Electron'} /> <PageTitle>Electron</PageTitle> <ComponentSubtitle description={ 'Build cross platform desktop apps with JavaScript, HTML, and CSS' ...
componentDidMount
identifier_name
electron.js
import React, { Component } from 'react'; import Prism from 'prismjs'; import { CodeBlock, Section, Link, ComponentDescription, SideScrollMenu, PageTitle, ComponentSubtitle, CodeInline, Helmet, } from '@components'; const sections = [ { name: 'Install' }, { name: 'Setup' }, { name: 'Usage' }, ...
</BreadProvider> ); } }`; const html = `<!DOCTYPE html> <html> <head> <title>Material Bread Electron</title> <meta charset="utf-8" /> </head> <body> <div id="app"></div> <script type="text/javascript" src="http://localhost:7000/bundle.js" ></script> </body> </html> `...
random_line_split
nfa.rs
//! The structure for defining non-deterministic finite automata. use crate::automata::alphabet; use crate::automata::dfa::DFA; use crate::automata::dfa::RuleExecutable; use crate::automata::pattern::Pattern; use crate::automata::state::State; use crate::automata::state::Transition; use crate::automata::state; use cra...
for (state_ix, source) in self.states.iter().enumerate() { let targets = source.targets(&self.alphabet_segmentation); for (voc_ix, &target) in targets.iter().enumerate() { matrix[(state_ix,voc_ix)] = target; } } matrix } } // === Trait Impls ===...
;
identifier_name
nfa.rs
//! The structure for defining non-deterministic finite automata. use crate::automata::alphabet; use crate::automata::dfa::DFA; use crate::automata::dfa::RuleExecutable; use crate::automata::pattern::Pattern; use crate::automata::state::State; use crate::automata::state::Transition; use crate::automata::state; use cra...
_letter() { assert_eq!(DFA::from(&letter()),dfa::tests::letter()); } #[test] fn test_to_dfa_spaces() { assert_eq!(DFA::from(&spaces()),dfa::tests::spaces()); } #[test] fn test_to_dfa_letter_and_spaces() { assert_eq!(DFA::from(&letter_and_spaces()),dfa::tests::letter_and...
tate::from(vec![11]).named("group_0_rule_0"), State::from(vec![4]), State::from(vec![(32..=32,5)]), State::from(vec![6]), State::from(vec![7,10]), State::from(vec![8]), State::from(vec![(32..=32,9)]), State::...
identifier_body
nfa.rs
//! The structure for defining non-deterministic finite automata. use crate::automata::alphabet; use crate::automata::dfa::DFA; use crate::automata::dfa::RuleExecutable; use crate::automata::pattern::Pattern; use crate::automata::state::State; use crate::automata::state::Transition; use crate::automata::state; use cra...
DFA{alphabet_segmentation,links,callbacks} } } // =========== // == Tests == // =========== #[cfg(test)] pub mod tests { extern crate test; use crate::automata::dfa; use super::*; use test::Bencher; /// NFA that accepts a newline '\n'. pub fn newline() -> NFA { NFA { ...
} } let alphabet_segmentation = nfa.alphabet_segmentation.clone(); let links = dfa_mat;
random_line_split
compressed_arith.go
package sparse import ( "github.com/james-bowman/sparse/blas" "gonum.org/v1/gonum/mat" ) // MulMatRawVec computes the matrix vector product between lhs and rhs and stores // the result in out func MulMatRawVec(lhs *CSR, rhs []float64, out []float64) { m, n := lhs.Dims() if len(rhs) != n { panic(mat.ErrShape) }...
(n int) *SPA { return &SPA{ w: make([]int, n), y: make([]float64, n), } } // ScatterVec accumulates the sparse vector x by multiplying the elements // by alpha and adding them to the corresponding elements in the SPA // (SPA += alpha * x) func (s *SPA) ScatterVec(x *Vector, alpha float64, ind *[]int) { s.Scatte...
NewSPA
identifier_name
compressed_arith.go
package sparse import ( "github.com/james-bowman/sparse/blas" "gonum.org/v1/gonum/mat" ) // MulMatRawVec computes the matrix vector product between lhs and rhs and stores // the result in out func MulMatRawVec(lhs *CSR, rhs []float64, out []float64) { m, n := lhs.Dims() if len(rhs) != n { panic(mat.ErrShape) }...
lhs, isLCsr := a.(*CSR) rhs, isRCsr := b.(*CSR) if isLCsr && isRCsr { // handle CSR * CSR c.mulCSRCSR(lhs, rhs) return } if dia, ok := a.(*DIA); ok { if isRCsr { // handle DIA * CSR c.mulDIACSR(dia, rhs, false) return } // handle DIA * mat.Matrix c.mulDIAMat(dia, b, false) return } if...
{ defer restore() c = m }
conditional_block
compressed_arith.go
package sparse import ( "github.com/james-bowman/sparse/blas" "gonum.org/v1/gonum/mat" ) // MulMatRawVec computes the matrix vector product between lhs and rhs and stores // the result in out func MulMatRawVec(lhs *CSR, rhs []float64, out []float64) { m, n := lhs.Dims() if len(rhs) != n { panic(mat.ErrShape) }...
// spalloc ensures appropriate storage is allocated for the receiver sparse matrix // ensuring it is row * col dimensions and checking for any overlap or aliasing // between operands a or b with c in which case a temporary isolated workspace is // allocated and the returned value isTemp is true with restore represent...
{ w = getWorkspace(row, col, nnz, clear) return w, func() { c.cloneCSR(w) putWorkspace(w) } }
identifier_body
compressed_arith.go
package sparse import ( "github.com/james-bowman/sparse/blas" "gonum.org/v1/gonum/mat" ) // MulMatRawVec computes the matrix vector product between lhs and rhs and stores // the result in out func MulMatRawVec(lhs *CSR, rhs []float64, out []float64) { m, n := lhs.Dims() if len(rhs) != n { panic(mat.ErrShape) }...
for i := 0; i < ar; i++ { // each element t in row i of A for t := lhs.matrix.Indptr[i]; t < lhs.matrix.Indptr[i+1]; t++ { begin := rhs.matrix.Indptr[lhs.matrix.Ind[t]] end := rhs.matrix.Indptr[lhs.matrix.Ind[t]+1] spa.Scatter(rhs.matrix.Data[begin:end], rhs.matrix.Ind[begin:end], lhs.matrix.Data[t], &c.m...
spa := NewSPA(bc) // rows in C
random_line_split
IP6_Address.go
// SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved. // // This software is provided under under a slightly modified version // of the Apache Software License. See the accompanying LICENSE file // for more information. // import array from six import string_types type IP6_Address: struct {...
if group == "0" { start_index = index end_index = index //Find the end of this chain of zeroes while end_index < 7 and groups[end_index + 1] == "0": end_index += 1 ...
random_line_split
BasePersonFactory.ts
import { Action, actionSaveData } from '../Action/ActionFactory'; import { MyGame } from '../../Tool/System/Game'; import { SelfHome } from '../Building/SelfHome'; import ProgressNotice from '../../UI/Prefab/ProgressNotice_script'; export interface PersonPos { cityId: number; buildingId: number; } export inte...
inInHomePos(): boolean { return this.personPos.cityId === this.homePos; } /** * 获取物品的数量 */ getItemTotalNum(): number { let totalNum = 0; for (var key in this.itemObj) { if (!this.itemObj.hasOwnProperty(key)) { continue; } ...
}.bind(this)); } /** * 判断是否在自己家所在的城市 */
random_line_split
BasePersonFactory.ts
import { Action, actionSaveData } from '../Action/ActionFactory'; import { MyGame } from '../../Tool/System/Game'; import { SelfHome } from '../Building/SelfHome'; import ProgressNotice from '../../UI/Prefab/ProgressNotice_script'; export interface PersonPos { cityId: number; buildingId: number; } export inte...
identifier_body
BasePersonFactory.ts
import { Action, actionSaveData } from '../Action/ActionFactory'; import { MyGame } from '../../Tool/System/Game'; import { SelfHome } from '../Building/SelfHome'; import ProgressNotice from '../../UI/Prefab/ProgressNotice_script'; export interface PersonPos { cityId: number; buildingId: number; } export inte...
Math.floor(this.power * 100000) / 100000; MyGame.LogTool.showLog(`power change num is ${changePowerNum}`); MyGame.EventManager.send(MyGame.EventName.USER_ROLE_STATUS_CHANGE); } /** * 直接设置当前的体力数量 * @param newPowerNum */ setPowerNum(newPowerNum: number) { this.power =...
this.power =
identifier_name
BasePersonFactory.ts
import { Action, actionSaveData } from '../Action/ActionFactory'; import { MyGame } from '../../Tool/System/Game'; import { SelfHome } from '../Building/SelfHome'; import ProgressNotice from '../../UI/Prefab/ProgressNotice_script'; export interface PersonPos { cityId: number; buildingId: number; } export inte...
alCityMapPos: this.goalCityMapPos, nowMapPos: this.nowMapPos, goalCityId: this.goalCityId, itemObj: this.itemObj, money: this.money, power: this.power, inInBattle: this.inInBattle, nowActionIds: this.nowActionIds, nowActionD...
is.presonSkillIdArr, equipAttack: this.equipAttack, equipDef: this.equipDef, equipJewelry: this.equipJewelry, equipHorse: this.equipHorse, personId: this.personId, personPos: this.personPos, homePos: this.homePos, go
conditional_block
py2_whole_image_desc_server_ts.py
#!/usr/bin/env python # Tensorflow from __future__ import print_function import tensorflow as tf from tensorflow.keras import backend as K from tensorflow.python.platform import gfile from sensor_msgs.msg import Image # OpenCV import cv2 from cv_bridge import CvBridge, CvBridgeError # Misc Python packages import numpy...
dt_last = self.queue[-1].header.stamp.to_sec() - stamp.to_sec() rospy.logwarn("Finding failed, dt is {:3.2f}ms; If this number > 0 means swarm_loop is too slow".format(dt_last)*1000) if dt_last < 0: return None, 1 return None, 0 def handle_req( self, req ): ...
cv_image = imgmsg_to_cv2( self.queue[index] ) del self.queue[0:index+1] if cv_image.shape[0] != 240 or cv_image.shape[1] != 320: cv_image = cv2.resize(cv_image, (320, 240)) return cv_image, 0
conditional_block
py2_whole_image_desc_server_ts.py
#!/usr/bin/env python # Tensorflow from __future__ import print_function import tensorflow as tf from tensorflow.keras import backend as K from tensorflow.python.platform import gfile from sensor_msgs.msg import Image # OpenCV import cv2 from cv_bridge import CvBridge, CvBridgeError # Misc Python packages import numpy...
(self, stamp): print("Find...", stamp, "queue_size", len(self.queue), "lag is", (self.queue[-1].header.stamp.to_sec() - stamp.to_sec())*1000, "ms") index = -1 for i in range(len(self.queue)): if math.fabs(self.queue[i].header.stamp.to_sec() - stamp.to_sec()) < 0.001: ...
pop_image_by_timestamp
identifier_name
py2_whole_image_desc_server_ts.py
#!/usr/bin/env python # Tensorflow from __future__ import print_function import tensorflow as tf from tensorflow.keras import backend as K from tensorflow.python.platform import gfile from sensor_msgs.msg import Image # OpenCV import cv2 from cv_bridge import CvBridge, CvBridgeError # Misc Python packages import numpy...
return X class ProtoBufferModelImageDescriptor: """ This class loads the net structure from the .h5 file. This file contains the model weights as well as architecture details. In the argument `frozen_protobuf_file` you need to specify the full path (keras model file). """ def __in...
if msg.encoding == "8UC1" or msg.encoding=='mono8': X = np.frombuffer(msg.data, dtype=np.uint8).reshape(msg.height, msg.width)
random_line_split
py2_whole_image_desc_server_ts.py
#!/usr/bin/env python # Tensorflow from __future__ import print_function import tensorflow as tf from tensorflow.keras import backend as K from tensorflow.python.platform import gfile from sensor_msgs.msg import Image # OpenCV import cv2 from cv_bridge import CvBridge, CvBridgeError # Misc Python packages import numpy...
def handle_req( self, req ): """ The received image from CV bridge has to be [0,255]. In function makes it to intensity range [-1 to 1] """ start_time_handle = time.time() stamp = req.stamp.data cv_image = None for i in range(3): cv_image, fail ...
print("Find...", stamp, "queue_size", len(self.queue), "lag is", (self.queue[-1].header.stamp.to_sec() - stamp.to_sec())*1000, "ms") index = -1 for i in range(len(self.queue)): if math.fabs(self.queue[i].header.stamp.to_sec() - stamp.to_sec()) < 0.001: index = i ...
identifier_body
vaultdb_test.go
package vaultdb import ( "context" "database/sql" "fmt" "os" "runtime/pprof" "strings" "testing" "time" // "bg/common/briefpg" vaultapi "github.com/hashicorp/vault/api" logicalDb "github.com/hashicorp/vault/builtin/logical/database" vaulthttp "github.com/hashicorp/vault/http" "github.com/hashicorp/vault...
// testDBSecrets tests the basic functionality of vaultdb: that we can establish // a connection to the database using credentials from Vault that rotate // periodically. func testDBSecrets(t *testing.T, vc *vaultapi.Client, vconf vaultConfig) { assert := require.New(t) role := "myrole" // Use the database via Va...
{ assert := require.New(t) notifier := newfanout(make(chan struct{})) stopChan := make(chan struct{}) // We have to get the TokenAuth from a clone of passed-in client, or // we'll end up trying to get new tokens using a token that's about to // expire. Note that a Clone() doesn't clone the token, so we set that...
identifier_body
vaultdb_test.go
package vaultdb import ( "context" "database/sql" "fmt" "os" "runtime/pprof" "strings" "testing" "time" // "bg/common/briefpg" vaultapi "github.com/hashicorp/vault/api" logicalDb "github.com/hashicorp/vault/builtin/logical/database" vaulthttp "github.com/hashicorp/vault/http" "github.com/hashicorp/vault...
(t *testing.T, vc *vaultapi.Client, vconf vaultConfig) { assert := require.New(t) role := "myrole" vconf.createRole(t, role, 2, 5) notifier, stopChan := fakeVaultAuth(t, vc) defer func() { stopChan <- struct{}{} }() vdbc1 := NewConnector(vconf.dbURI, vc, notifier, vconf.path, role, zaptest.NewLogger(t).Named...
testMultiVDBC
identifier_name
vaultdb_test.go
package vaultdb import ( "context" "database/sql" "fmt" "os" "runtime/pprof" "strings" "testing" "time" // "bg/common/briefpg" vaultapi "github.com/hashicorp/vault/api" logicalDb "github.com/hashicorp/vault/builtin/logical/database" vaulthttp "github.com/hashicorp/vault/http" "github.com/hashicorp/vault...
return vaultConfig{ dbURI: cleanDBURI, path: path, vcl: vcl, } } // fakeVaultAuth mimics vaultgcpauth, except that we log in with the root token, // and rotate the passed-in client's token with a time-limited sub-token. func fakeVaultAuth(t *testing.T, vc *vaultapi.Client) (*fanout, chan struct{}) { asse...
{ t.Fatalf("Failed to configure DB engine in Vault: %v", err) }
conditional_block
vaultdb_test.go
package vaultdb import ( "context" "database/sql" "fmt" "os" "runtime/pprof" "strings" "testing" "time" // "bg/common/briefpg" vaultapi "github.com/hashicorp/vault/api" logicalDb "github.com/hashicorp/vault/builtin/logical/database" vaulthttp "github.com/hashicorp/vault/http" "github.com/hashicorp/vault...
"creation_statements": createSQL, "revocation_statements": revokeSQL, }) if err != nil { t.Fatalf("Failed to create DB role '%s' in Vault: %v", role, err) } } // setupVault creates a database and a secrets engine in Vault for it. func setupVault(t *testing.T, vc *vaultapi.Client, bpg *briefpg.BriefPG) vaul...
"db_name": "db", "default_ttl": ttl, "max_ttl": maxTTL,
random_line_split
helpers.py
from htm.encoders.rdse import RDSE, RDSE_Parameters from htm.bindings.sdr import SDR from collections import defaultdict from nnmnkwii.preprocessing import trim_zeros_frames from sklearn.metrics import f1_score, confusion_matrix, classification_report from attrdict import AttrDict from datetime import datetime import ...
def sort_dict(dict): return sorted(dict.items(), key=lambda x: x[1]) def sort_dict_reverse(dict): return sorted(dict.items(), key=lambda x: x[1], reverse=True) def sort_dict_by_len(dict): return sorted(dict.items(), key=lambda x: len(x[1])) class Experiment: def __init__(self, encoder, sdr_length,...
tensor_minus_mean = tensor - tensor.mean() return tensor_minus_mean / tensor_minus_mean.abs().max()
identifier_body
helpers.py
from htm.encoders.rdse import RDSE, RDSE_Parameters from htm.bindings.sdr import SDR from collections import defaultdict from nnmnkwii.preprocessing import trim_zeros_frames from sklearn.metrics import f1_score, confusion_matrix, classification_report from attrdict import AttrDict from datetime import datetime import ...
(data): data = data.astype(np.float64) amp = max(np.abs(np.max(data)), np.abs(np.min(data))) data = data / amp data.clip(-1, 1) return data def normalize(tensor): tensor_minus_mean = tensor - tensor.mean() return tensor_minus_mean / tensor_minus_mean.abs().max() def sort_dict(dict): re...
peak_normalize
identifier_name
helpers.py
from htm.encoders.rdse import RDSE, RDSE_Parameters from htm.bindings.sdr import SDR from collections import defaultdict from nnmnkwii.preprocessing import trim_zeros_frames from sklearn.metrics import f1_score, confusion_matrix, classification_report from attrdict import AttrDict from datetime import datetime import ...
def get_wavfile_list(path): wav_files = [] for dirpath, subdirs, files in os.walk(path): for x in files: if x.endswith(".wav"): wav_files.append(os.path.join(dirpath, x)) return wav_files def get_features(x, fs): # f0 calculate _f0, t = pw.dio(x, fs) f0 = pw....
import param
random_line_split
helpers.py
from htm.encoders.rdse import RDSE, RDSE_Parameters from htm.bindings.sdr import SDR from collections import defaultdict from nnmnkwii.preprocessing import trim_zeros_frames from sklearn.metrics import f1_score, confusion_matrix, classification_report from attrdict import AttrDict from datetime import datetime import ...
else: self.setting = setting self.split_ratio = self.setting.ratio self.input_path = input_path self.unknown = unknown self.sp2idx = self.speakers_to_idx() self.idx2sp = self.idx_to_speakers() self.encoder = self.create_encoder() self.experim...
with open(os.path.join(model_path, 'setting.json'), 'r') as f: self.setting = AttrDict(json.load(f))
conditional_block
kmip.go
/* Copyright 2022 The Rook Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to ...
_, err = conn.Write(req) if err != nil { return nil, nil, nil, fmt.Errorf("failed to write request onto connection: %w", err) } decoder := ttlv.NewDecoder(bufio.NewReader(conn)) resp, err := decoder.NextTTLV() if err != nil { return nil, nil, nil, fmt.Errorf("failed to read ttlv KMIP value: %w", err)...
{ return nil, nil, nil, fmt.Errorf("failed to ttlv marshal message: %w", err) }
conditional_block
kmip.go
/* Copyright 2022 The Rook Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to ...
if pv.ProtocolVersionMajor != protocolMajor || pv.ProtocolVersionMinor != protocolMinor { return fmt.Errorf("invalid discovered protocol version %v.%v expected %v.%v", pv.ProtocolVersionMajor, pv.ProtocolVersionMinor, protocolMajor, protocolMinor) } return nil } // send sends KMIP operation over tls connectio...
if len(respDiscoverVersionsPayload.ProtocolVersion) != 1 { return fmt.Errorf("invalid len of discovered protocol versions %v expected 1", len(respDiscoverVersionsPayload.ProtocolVersion)) } pv := respDiscoverVersionsPayload.ProtocolVersion[0]
random_line_split
kmip.go
/* Copyright 2022 The Rook Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to ...
// send sends KMIP operation over tls connection, returns // kmip response message, // ttlv Decoder to decode message into desired format, // batchItem ID, // and error. func (kms *kmipKMS) send( conn io.ReadWriter, operation kmip14.Operation, payload interface{}, ) (*kmip.ResponseMessage, *ttlv.Decoder, []byte, e...
{ respMsg, decoder, uniqueBatchItemID, err := kms.send(conn, kmip14.OperationDiscoverVersions, kmip.DiscoverVersionsRequestPayload{ ProtocolVersion: []kmip.ProtocolVersion{ { ProtocolVersionMajor: protocolMajor, ProtocolVersionMinor: protocolMinor, }, }, }) if err != nil { return err ...
identifier_body
kmip.go
/* Copyright 2022 The Rook Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to ...
(conn io.ReadWriter) error { respMsg, decoder, uniqueBatchItemID, err := kms.send(conn, kmip14.OperationDiscoverVersions, kmip.DiscoverVersionsRequestPayload{ ProtocolVersion: []kmip.ProtocolVersion{ { ProtocolVersionMajor: protocolMajor, ProtocolVersionMinor: protocolMinor, }, }, }) if ...
discover
identifier_name
views.py
# -*- coding: utf-8 -*- from time import strptime from datetime import datetime, date, time from django.conf import settings from django.shortcuts import render_to_response from django.core.urlresolvers import reverse from django.http import HttpResponse, HttpResponseRedirect from django.core.context_processors import...
tle, b_url=b_url, ) context_dict.update(csrf(request)) return render_to_response("guest_add.html", context_dict) if 'query' in request.GET.keys(): query = request.GET.get('query') lst = Guest.objects.filter(lastname__icontains=query).order_by("lastname") elif id > -1: lst = Guest.objects.filter(lastname__i...
f.pk post_values['date'] = datetime.now() post_values['is_free'] = True fi = FormInvitation(post_values) if fi.is_valid(): fi.save() else: fi = fi.errors url = reverse('r_guest', args=(0, )) return HttpResponseRedirect(url) context_dict = dict(request=request, p_title=p_ti
conditional_block
views.py
# -*- coding: utf-8 -*- from time import strptime from datetime import datetime, date, time from django.conf import settings from django.shortcuts import render_to_response from django.core.urlresolvers import reverse from django.http import HttpResponse, HttpResponseRedirect from django.core.context_processors import...
_start'): debts = Credits.objects.filter(client=v.contract.client).count() lst.append((debts,v)) glst = [] for gv in GuestVisits.objects.filter(is_online=-1).order_by('date_start'): debts = Credits.objects.filter(guest=gv.guest).count() glst.append((debts, gv)) elst = eVisits.objects.filter(date_end__isnul...
equest.POST.get('lastname') if isinstance(find, long): res = Contract.objects.filter(card=find, is_current=1) # if not find in the current try find in the prospect if res.count() < 1: res = Contract.objects.filter(card=find, is_current=2) employees = Employee.objects.filter(card=find,) else: ac ...
identifier_body
views.py
# -*- coding: utf-8 -*- from time import strptime from datetime import datetime, date, time from django.conf import settings from django.shortcuts import render_to_response from django.core.urlresolvers import reverse from django.http import HttpResponse, HttpResponseRedirect from django.core.context_processors import...
ery = request.GET.get('query') if len(query) > 0: clnts = Client.objects.filter(last_name__icontains=query).order_by("last_name") for c in Contract.objects.filter(contract_type__in=ct, is_current=1, client__in=clnts): invites = Invitation.objects.filter(contract=c) lst.append((c, invites)) ...
keys(): qu
identifier_name
views.py
# -*- coding: utf-8 -*- from time import strptime from datetime import datetime, date, time from django.conf import settings from django.shortcuts import render_to_response from django.core.urlresolvers import reverse from django.http import HttpResponse, HttpResponseRedirect from django.core.context_processors import...
if len(query) > 0: clnts = Client.objects.filter(last_name__icontains=query).order_by("last_name") for c in Contract.objects.filter(contract_type__in=ct, is_current=1, client__in=clnts): invites = Invitation.objects.filter(contract=c) lst.append((c, invites)) else: for c in Contract.obj...
query = request.GET.get('query')
random_line_split
warming.rs
use std::collections::HashSet; use std::ops::Deref; use std::sync::{Arc, Mutex, Weak}; use std::thread::JoinHandle; use std::time::Duration; use crate::{Executor, Inventory, Searcher, SearcherGeneration, TantivyError}; pub const GC_INTERVAL: Duration = Duration::from_secs(1); /// `Warmer` can be used to maintain seg...
/// Start tracking a new generation of [Searcher], and [Warmer::warm] it if there are active /// warmers. /// /// A background GC thread for [Warmer::garbage_collect] calls is uniquely created if there are /// active warmers. pub fn warm_new_searcher_generation(&self, searcher: &Searcher) -> cr...
})))) }
random_line_split
warming.rs
use std::collections::HashSet; use std::ops::Deref; use std::sync::{Arc, Mutex, Weak}; use std::thread::JoinHandle; use std::time::Duration; use crate::{Executor, Inventory, Searcher, SearcherGeneration, TantivyError}; pub const GC_INTERVAL: Duration = Duration::from_secs(1); /// `Warmer` can be used to maintain seg...
( &mut self, searcher: &Searcher, this: &Arc<Mutex<Self>>, ) -> crate::Result<()> { let warmers = self.pruned_warmers(); // Avoid threads (warming as well as background GC) if there are no warmers if warmers.is_empty() { return Ok(()); } se...
warm_new_searcher_generation
identifier_name
warming.rs
use std::collections::HashSet; use std::ops::Deref; use std::sync::{Arc, Mutex, Weak}; use std::thread::JoinHandle; use std::time::Duration; use crate::{Executor, Inventory, Searcher, SearcherGeneration, TantivyError}; pub const GC_INTERVAL: Duration = Duration::from_secs(1); /// `Warmer` can be used to maintain seg...
else { Executor::multi_thread(num_threads, "tantivy-warm-") } } #[cfg(test)] mod tests { use std::collections::HashSet; use std::sync::atomic::{self, AtomicUsize}; use std::sync::{Arc, RwLock, Weak}; use super::Warmer; use crate::core::searcher::SearcherGeneration; use crate::dire...
{ Ok(Executor::single_thread()) }
conditional_block
main.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Core RAMP-UA model. Created on Wed Apr 29 19:59:25 2020 @author: nick """ import sys import os os.environ['R_HOME'] = 'C:/Users/gy17m2a/AppData/Local/Programs/R/R-4.2.0' #path to your R installation os.environ['R_USER'] = 'C:/ProgramData/Anaconda3/envs/analyse_resul...
def run_opencl_model(individuals_df, activity_locations, time_activity_multiplier, iterations, data_dir, base_dir, use_gui, use_gpu, use_cache, initialise, calibration_params, disease_params): snapshot_cache_filepath = base_dir + "/microsim/opencl/snapshots/cache.npz" # Choose whether t...
if initialise: print("Have finished initialising model. -init flag is set so not running it. Exitting") return run_python_model(individuals, activity_locations, time_activity_multiplier, msim_args, iterations, repetitions, parameters_file)
conditional_block
main.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Core RAMP-UA model. Created on Wed Apr 29 19:59:25 2020 @author: nick """ import sys import os os.environ['R_HOME'] = 'C:/Users/gy17m2a/AppData/Local/Programs/R/R-4.2.0' #path to your R installation os.environ['R_USER'] = 'C:/ProgramData/Anaconda3/envs/analyse_resul...
(calibration_params, disease_params): current_risk_beta = disease_params["current_risk_beta"] # NB: OpenCL model incorporates the current risk beta by pre-multiplying the hazard multipliers with it location_hazard_multipliers = LocationHazardMultipliers( retail=calibration_params["hazard_location_m...
create_params
identifier_name
main.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Core RAMP-UA model. Created on Wed Apr 29 19:59:25 2020 @author: nick """ import sys import os os.environ['R_HOME'] = 'C:/Users/gy17m2a/AppData/Local/Programs/R/R-4.2.0' #path to your R installation os.environ['R_USER'] = 'C:/ProgramData/Anaconda3/envs/analyse_resul...
if __name__ == "__main__": main() print("End of program")
current_risk_beta = disease_params["current_risk_beta"] # NB: OpenCL model incorporates the current risk beta by pre-multiplying the hazard multipliers with it location_hazard_multipliers = LocationHazardMultipliers( retail=calibration_params["hazard_location_multipliers"]["Retail"] * current_risk_beta...
identifier_body
main.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Core RAMP-UA model. Created on Wed Apr 29 19:59:25 2020 @author: nick """ import sys import os os.environ['R_HOME'] = 'C:/Users/gy17m2a/AppData/Local/Programs/R/R-4.2.0' #path to your R installation os.environ['R_USER'] = 'C:/ProgramData/Anaconda3/envs/analyse_resul...
# Option A: copy current working directory: base_dir = os.getcwd() # get current directory data_dir = os.path.join(base_dir, data_dir) r_script_dir = os.path.join(base_dir, "R", "py_int") ### section for fetching data if not os.path.isdir(data_dir): print(f"No data directory detected....
# To fix file path issues, use absolute/full path at all times # Pick either: get working directory (if user starts this script in place, or set working directory
random_line_split
main.rs
#![feature(test)] #[macro_use] extern crate gfx; extern crate gfx_window_glutin; extern crate gfx_device_gl; extern crate glutin; extern crate rand; extern crate failure; #[macro_use] extern crate failure_derive; extern crate image; extern crate rusttype; extern crate specs; extern crate rayon; #[macro_use] extern cra...
} // Update & paint the world { dispatcher.dispatch_seq(&mut world.res); // Get the player position let player_pos = world.read_storage::<Pos>().get(player).unwrap().clone(); let player_pos = [player_pos.pos.x, player_pos.z, player_pos.pos.y]; ...
{ println!("Resizing window viewport"); renderer.update_window_size(&window); }
conditional_block
main.rs
#![feature(test)] #[macro_use] extern crate gfx; extern crate gfx_window_glutin; extern crate gfx_device_gl; extern crate glutin; extern crate rand; extern crate failure; #[macro_use] extern crate failure_derive; extern crate image; extern crate rusttype; extern crate specs; extern crate rayon; #[macro_use] extern cra...
.with(PlayerControlled::new()) .with(FollowCamera) .with(Health::new(8, Hitmask(HITMASK_PLAYER))) .with(Collector { magnet_radius: 64.0 }) .with(Equipment { .. Default::default() }) .with(CollCircle { r: 8.0, off: Vec32::zero(), ...
.with(Vel { vel: Vec32::zero() }) .with(Alliance::good())
random_line_split
main.rs
#![feature(test)] #[macro_use] extern crate gfx; extern crate gfx_window_glutin; extern crate gfx_device_gl; extern crate glutin; extern crate rand; extern crate failure; #[macro_use] extern crate failure_derive; extern crate image; extern crate rusttype; extern crate specs; extern crate rayon; #[macro_use] extern cra...
(renderer::VertexBuffer); /// Entities that have been 'killed' and need to produce on-death effects. This /// doesn't mean all deleted entities - it means alive characters have been /// killed by combat or other effects. pub struct KilledEntities(Vec<Entity>); /// Empty specs::System to use in the dispatcher as a com...
UIVertexBuffer
identifier_name
main.rs
#![feature(test)] #[macro_use] extern crate gfx; extern crate gfx_window_glutin; extern crate gfx_device_gl; extern crate glutin; extern crate rand; extern crate failure; #[macro_use] extern crate failure_derive; extern crate image; extern crate rusttype; extern crate specs; extern crate rayon; #[macro_use] extern cra...
} /// Create the world and register all the components fn create_world() -> specs::World { let mut world = specs::World::new(); world.register::<Pos>(); world.register::<Vel>(); world.register::<PlayerControlled>(); world.register::<Tilemap>(); world.register::<AnimSprite>(); world.registe...
{}
identifier_body
mod.rs
use crate::cipher::Cipher; use crate::error::*; use crate::format::ossh_privkey::*; use crate::format::ossh_pubkey::*; use crate::format::parse_keystr; use crate::format::pem::*; use crate::format::pkcs8::*; use digest::{Digest, FixedOutputReset}; use md5::Md5; use openssl::pkey::{Id, PKey, PKeyRef, Private, Public}; u...
/// Serialize the keypair to the OpenSSL PKCS#8 PEM format /// /// If the passphrase is given (set to `Some(...)`), then the generated PKCS#8 key will be encrypted. pub fn serialize_pkcs8(&self, passphrase: Option<&str>) -> OsshResult<String> { serialize_pkcs8_privkey(self, passphrase) } ...
{ stringify_pem_privkey(self, passphrase) }
identifier_body
mod.rs
use crate::cipher::Cipher; use crate::error::*; use crate::format::ossh_privkey::*; use crate::format::ossh_pubkey::*; use crate::format::parse_keystr; use crate::format::pem::*; use crate::format::pkcs8::*; use digest::{Digest, FixedOutputReset}; use md5::Md5; use openssl::pkey::{Id, PKey, PKeyRef, Private, Public}; u...
SHA512, } impl FingerprintHash { fn hash(self, data: &[u8]) -> Vec<u8> { fn digest_hash<D>(hasher: &mut D, data: &[u8]) -> Vec<u8> where D: Digest + FixedOutputReset, { // Fix error[E0034]: multiple applicable items in scope Digest::update(hasher, dat...
SHA256,
random_line_split
mod.rs
use crate::cipher::Cipher; use crate::error::*; use crate::format::ossh_privkey::*; use crate::format::ossh_pubkey::*; use crate::format::parse_keystr; use crate::format::pem::*; use crate::format::pkcs8::*; use digest::{Digest, FixedOutputReset}; use md5::Md5; use openssl::pkey::{Id, PKey, PKeyRef, Private, Public}; u...
(inner: rsa::RsaPublicKey) -> PublicKey { PublicKey { key: PublicKeyType::RSA(inner), comment: String::new(), } } } impl From<dsa::DsaPublicKey> for PublicKey { fn from(inner: dsa::DsaPublicKey) -> PublicKey { PublicKey { key: PublicKeyType::DSA(inner...
from
identifier_name
mod.rs
//! Text handling. mod deco; mod misc; mod quotes; mod raw; mod shaping; mod shift; pub use self::deco::*; pub use self::misc::*; pub use self::quotes::*; pub use self::raw::*; pub use self::shaping::*; pub use self::shift::*; use rustybuzz::Tag; use ttf_parser::Rect; use typst::font::{Font, FontStretch, FontStyle, ...
ngth) => length.resolve(styles), } } } cast! { TopEdge, self => match self { Self::Metric(metric) => metric.into_value(), Self::Length(length) => length.into_value(), }, v: TopEdgeMetric => Self::Metric(v), v: Length => Self::Length(v), } /// Metrics that describe the t...
ric) = metric.try_into() { font.metrics().vertical(metric).resolve(styles) } else { bbox.map(|bbox| (font.to_em(bbox.y_max)).resolve(styles)) .unwrap_or_default() } } TopEdge::Length(le
conditional_block
mod.rs
//! Text handling. mod deco; mod misc; mod quotes; mod raw; mod shaping; mod shift; pub use self::deco::*; pub use self::misc::*; pub use self::quotes::*; pub use self::raw::*; pub use self::shaping::*; pub use self::shift::*; use rustybuzz::Tag; use ttf_parser::Rect; use typst::font::{Font, FontStretch, FontStyle, ...
self => match self { Self::Metric(metric) => metric.into_value(), Self::Length(length) => length.into_value(), }, v: BottomEdgeMetric => Self::Metric(v), v: Length => Self::Length(v), } /// Metrics that describe the bottom edge of text. #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, ...
} } cast! { BottomEdge,
random_line_split
mod.rs
//! Text handling. mod deco; mod misc; mod quotes; mod raw; mod shaping; mod shift; pub use self::deco::*; pub use self::misc::*; pub use self::quotes::*; pub use self::raw::*; pub use self::shaping::*; pub use self::shift::*; use rustybuzz::Tag; use ttf_parser::Rect; use typst::font::{Font, FontStretch, FontStyle, ...
(global: &mut Scope) { global.define("text", TextElem::func()); global.define("linebreak", LinebreakElem::func()); global.define("smartquote", SmartQuoteElem::func()); global.define("strong", StrongElem::func()); global.define("emph", EmphElem::func()); global.define("lower", lower_func()); ...
define
identifier_name
tetris.py
"""This is the main file for the Pytris project. The three concrete classes defined herein are Board: generally controls the flow of the game, e.g. interacting with the classes defined in tetris_pieces.py to determine whether and how pieces get moved around the board. Also responsible for displaying the state ...
(self): """Clear any full rows, modifying the variables locked_squares, level, lines, and score as appropriate.""" ### Previous version had a bug, in that it assumed the set of ### ### indices of full rows had to be a contiguous sequence! ### full_rows = [j for j in range(ROWS) i...
clear_rows
identifier_name
tetris.py
"""This is the main file for the Pytris project. The three concrete classes defined herein are Board: generally controls the flow of the game, e.g. interacting with the classes defined in tetris_pieces.py to determine whether and how pieces get moved around the board. Also responsible for displaying the state ...
self.increment_score(delta[1]) self.move_curr_piece(delta) self.lock_curr_piece() self.queue_draw() def rotate_curr_piece(self): """Check the validity of a rotation, and conditionally perform it.""" if self.over: return hypothetical = self.curr_piece.test_ro...
break
conditional_block
tetris.py
"""This is the main file for the Pytris project. The three concrete classes defined herein are Board: generally controls the flow of the game, e.g. interacting with the classes defined in tetris_pieces.py to determine whether and how pieces get moved around the board. Also responsible for displaying the state ...
self.game_over() def game_over(self): """End the game. (Doesn't currently have to do much, because the actual painting is done conditionally in expose.)""" self.over = True def clear_rows(self): """Clear any full rows, modifying the variables locked_squares, ...
self.clear_rows() self.curr_piece = self.next_piece_display.get_piece() if any(pos in self.locked_squares for pos in self.curr_piece.occupying()):
random_line_split
tetris.py
"""This is the main file for the Pytris project. The three concrete classes defined herein are Board: generally controls the flow of the game, e.g. interacting with the classes defined in tetris_pieces.py to determine whether and how pieces get moved around the board. Also responsible for displaying the state ...
def on_key_down(self, widget, event): key = event.keyval if key == gtk.keysyms.Left: self.board.move_curr_piece((-1, 0)) elif key == gtk.keysyms.Up: self.board.rotate_curr_piece() elif key == gtk.keysyms.Right: self.board.move_curr_piece((1, 0)) ...
super(Main, self).__init__() self.set_title("Tetris") self.set_resizable(False) self.set_position(gtk.WIN_POS_CENTER) self.connect("destroy", gtk.main_quit) self.connect("key-press-event", self.on_key_down) ### Create and reformat labels ### self.next_piece_word...
identifier_body
SPACE-BLASTER-FINAL.py
# PREET PANCHAL & TIRTH PATEL # ICS3U1-01 # MRS. RUBINI-LAFOREST # WOBURN COLLEGIATE INSTITUTE # JUNE 9th, 2017 """ WORKS CITED: - ALL screens(Start, instructions, credits, & game over screens) are designed and created on https://www.canva.com/ - Star Background animation help: http: // prog...
# For-loop appending coordinates for the meteors # on blue spaceship side x_meteor_blue = random.randrange(15, 550) meteor_list_blue.append([x_meteor_blue, 0]) # Blue meteor width & height values blue_meteorw = 30 blue_meteorh = 30 # Function for displaying blue spaceship def BLUE(x_change_blue, y_chang...
random_line_split
SPACE-BLASTER-FINAL.py
# PREET PANCHAL & TIRTH PATEL # ICS3U1-01 # MRS. RUBINI-LAFOREST # WOBURN COLLEGIATE INSTITUTE # JUNE 9th, 2017 """ WORKS CITED: - ALL screens(Start, instructions, credits, & game over screens) are designed and created on https://www.canva.com/ - Star Background animation help: http: // prog...
if startX_red >= 1157: startX_red -= 3 startX_red -= 3 startX_red -= 3 # Synchronizes Red spaceship with bullets x_coord_red += Xchange_bullet_red RED(x_coord_red, y_coord_red) # Controls movement of bullets on red side startX_red += Xchange_bullet_red ...
startX_red += 3 startX_red += 3 startX_red += 3
conditional_block
SPACE-BLASTER-FINAL.py
# PREET PANCHAL & TIRTH PATEL # ICS3U1-01 # MRS. RUBINI-LAFOREST # WOBURN COLLEGIATE INSTITUTE # JUNE 9th, 2017 """ WORKS CITED: - ALL screens(Start, instructions, credits, & game over screens) are designed and created on https://www.canva.com/ - Star Background animation help: http: // prog...
# Importing & loading music file background_music = pygame.mixer.music.load("Instrumental Music.mp3") # Music timer set at zero before loop music_timer = 0 # Initializing game timer (set to zero) game_timer = 90 # --- Main Game Title Screen --- start = False done = False while not start and not done:...
font_red_score = pygame.font.SysFont('monospace', 25, True, False) score_red_text = font_red_score.render("SCORE :" + str(int(score_red)), True, RED_FADE) screen.blit(score_red_text, [865, 10]) return score_red
identifier_body
SPACE-BLASTER-FINAL.py
# PREET PANCHAL & TIRTH PATEL # ICS3U1-01 # MRS. RUBINI-LAFOREST # WOBURN COLLEGIATE INSTITUTE # JUNE 9th, 2017 """ WORKS CITED: - ALL screens(Start, instructions, credits, & game over screens) are designed and created on https://www.canva.com/ - Star Background animation help: http: // prog...
(obj1x, obj1y, obj1w, obj1h, obj2x, obj2y, obj2w, obj2h): # check bounding box if obj1x + obj1w >= obj2x and obj1x <= obj2x + obj2w: if obj1y + obj1h >= obj2y and obj1y <= obj2y + obj2h: return True return False # Blue Player scoring function score_blue = 0 def blue_pla...
checkCollision
identifier_name
rust_gtest_interop.rs
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::pin::Pin; /// Use `prelude:::*` to get access to all macros defined in this crate. pub mod prelude { // The #[extern_test_suite("cplusplus::Type") macro. pub ...
pub use crate::expect_ge; pub use crate::expect_gt; pub use crate::expect_le; pub use crate::expect_lt; pub use crate::expect_ne; pub use crate::expect_true; } // The gtest_attribute proc-macro crate makes use of small_ctor, with a path // through this crate here to ensure it's available. #[doc...
random_line_split
rust_gtest_interop.rs
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::pin::Pin; /// Use `prelude:::*` to get access to all macros defined in this crate. pub mod prelude { // The #[extern_test_suite("cplusplus::Type") macro. pub ...
{ data: [u8; 0], marker: std::marker::PhantomData<(*mut u8, std::marker::PhantomPinned)>, } #[doc(hidden)] pub trait TestResult { fn into_error_message(self) -> Option<String>; } impl TestResult for () { fn into_error_message(self) -> Option<String> { None } } // This impl requires an `Err...
OpaqueTestingTest
identifier_name
rust_gtest_interop.rs
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::pin::Pin; /// Use `prelude:::*` to get access to all macros defined in this crate. pub mod prelude { // The #[extern_test_suite("cplusplus::Type") macro. pub ...
} // Internals used by code generated from the gtest-attriute proc-macro. Should // not be used by human-written code. #[doc(hidden)] pub mod __private { use super::{GtestFactoryFunction, OpaqueTestingTest, Pin}; /// Rust wrapper around the same C++ method. /// /// We have a wrapper to convert the fi...
{ match self { Ok(_) => None, Err(e) => Some(format!("Test returned error: {}", e.into())), } }
identifier_body
main.rs
//This project was inspired by https://github.com/jkusner/CACBarcode/blob/master/cacbarcode.py extern crate base_custom; use base_custom::BaseCustom; extern crate chrono; use chrono::prelude::*; extern crate time; use time::Duration; fn main() { if std::env::args().count() > 1 { println!("For security, the bar...
//Electronic Data Interchange Person Identifier (base 32) let edipi = data_chars.by_ref().take(7).collect::<String>(); out.push(("Electronic Data Interchange Person Identifier", base32.decimal(edipi).to_string())); //Personnel Category Code out.push(("Personnel Category Code", lookup_ppc(data_chars.next().un...
random_line_split
main.rs
//This project was inspired by https://github.com/jkusner/CACBarcode/blob/master/cacbarcode.py extern crate base_custom; use base_custom::BaseCustom; extern crate chrono; use chrono::prelude::*; extern crate time; use time::Duration; fn main() { if std::env::args().count() > 1 { println!("For security, the bar...
(data: String) -> String { let mut data_chars = data.chars(); let base32 = BaseCustom::<String>::new("0123456789ABCDEFGHIJKLMNOPQRSTUV", None); let mut out = Vec::new(); //(Key, Value) out.push(("Barcode type", "Code39".to_string())); //Version let version = data_chars.next().unwrap(); match version {...
decode_code39
identifier_name
main.rs
//This project was inspired by https://github.com/jkusner/CACBarcode/blob/master/cacbarcode.py extern crate base_custom; use base_custom::BaseCustom; extern crate chrono; use chrono::prelude::*; extern crate time; use time::Duration; fn main() { if std::env::args().count() > 1 { println!("For security, the bar...
fn decode_pdf217(data: String) -> String { let base32 = BaseCustom::<String>::new("0123456789ABCDEFGHIJKLMNOPQRSTUV", None); let base_time = Utc.ymd(1000, 1, 1); let mut data_chars = data.chars(); let mut out = Vec::new(); //(Key, Value) out.push(("Barcode type", "PDF217".to_string())); //Version l...
{ match data.len() { 18 => return decode_code39(data), 88 | 89 => return decode_pdf217(data), _ => return format!("Incorrect barcode length: {}. Make sure to include all spaces.", data.len()), } }
identifier_body
source_manager.go
package gps import ( "fmt" "os" "path/filepath" "strings" "sync" "github.com/Masterminds/semver" ) // Used to compute a friendly filepath from a URL-shaped input // // TODO(sdboyer) this is awful. Right? var sanitizer = strings.NewReplacer(":", "-", "/", "-", "+", "-") // A SourceManager is responsible for re...
// gps's SourceManager is intended to be threadsafe (if it's not, please file a // bug!). It should be safe to reuse across concurrent solving runs, even on // unrelated projects. func NewSourceManager(an ProjectAnalyzer, cachedir string) (*SourceMgr, error) { if an == nil { return nil, fmt.Errorf("a ProjectAnalyzer...
random_line_split
source_manager.go
package gps import ( "fmt" "os" "path/filepath" "strings" "sync" "github.com/Masterminds/semver" ) // Used to compute a friendly filepath from a URL-shaped input // // TODO(sdboyer) this is awful. Right? var sanitizer = strings.NewReplacer(":", "-", "/", "-", "+", "-") // A SourceManager is responsible for re...
(id ProjectIdentifier) ([]Version, error) { src, err := sm.getSourceFor(id) if err != nil { // TODO(sdboyer) More-er proper-er errors return nil, err } return src.listVersions() } // RevisionPresentIn indicates whether the provided Revision is present in the given // repository. func (sm *SourceMgr) RevisionP...
ListVersions
identifier_name
source_manager.go
package gps import ( "fmt" "os" "path/filepath" "strings" "sync" "github.com/Masterminds/semver" ) // Used to compute a friendly filepath from a URL-shaped input // // TODO(sdboyer) this is awful. Right? var sanitizer = strings.NewReplacer(":", "-", "/", "-", "+", "-") // A SourceManager is responsible for re...
return src.listVersions() } // RevisionPresentIn indicates whether the provided Revision is present in the given // repository. func (sm *SourceMgr) RevisionPresentIn(id ProjectIdentifier, r Revision) (bool, error) { src, err := sm.getSourceFor(id) if err != nil { // TODO(sdboyer) More-er proper-er errors ret...
{ // TODO(sdboyer) More-er proper-er errors return nil, err }
conditional_block
source_manager.go
package gps import ( "fmt" "os" "path/filepath" "strings" "sync" "github.com/Masterminds/semver" ) // Used to compute a friendly filepath from a URL-shaped input // // TODO(sdboyer) this is awful. Right? var sanitizer = strings.NewReplacer(":", "-", "/", "-", "+", "-") // A SourceManager is responsible for re...
// ListVersions retrieves a list of the available versions for a given // repository name. // // The list is not sorted; while it may be returned in the order that the // underlying VCS reports version information, no guarantee is made. It is // expected that the caller either not care about order, or sort the result...
{ src, err := sm.getSourceFor(id) if err != nil { return PackageTree{}, err } return src.listPackages(id.ProjectRoot, v) }
identifier_body
detailed-titanic-analysis-and-solution.py
#!/usr/bin/env python # coding: utf-8 # Titanic is one of the classical problems in machine learning. There are many solutions with different approaches out there, so here is my take on this problem. I tried to explain every step as detailed as I could, too, so if you're new to ML, this notebook may be helpful for you...
# In[ ]: train['Title'] = train['Name'].apply(get_title) test['Title'] = test['Name'].apply(get_title) # In[ ]: plt.figure(figsize=(16, 10)) sns.boxplot('Title', 'Age', data=train) # Now that we have all the titles, we can find out a mean value for each of them and use it to fill the gaps in the data. # In[...
index_1 = pasngr_name.find(', ') + 2 index_2 = pasngr_name.find('. ') + 1 return pasngr_name[index_1:index_2]
identifier_body
detailed-titanic-analysis-and-solution.py
#!/usr/bin/env python # coding: utf-8 # Titanic is one of the classical problems in machine learning. There are many solutions with different approaches out there, so here is my take on this problem. I tried to explain every step as detailed as I could, too, so if you're new to ML, this notebook may be helpful for you...
class_mean_scores = [] for score in class_scores: class_mean_scores.append(score.mean()) # Now that we have the mean accuracy scores, we need to compare them somehow. But since it's just a list of numbers, we can easily plot them. First, let's create a data frame of classifiers names and their scores, and t...
class_scores.append(cross_val_score(classifier, X_train, y_train, scoring='accuracy', cv=cv_kfold))
conditional_block
detailed-titanic-analysis-and-solution.py
#!/usr/bin/env python # coding: utf-8 # Titanic is one of the classical problems in machine learning. There are many solutions with different approaches out there, so here is my take on this problem. I tried to explain every step as detailed as I could, too, so if you're new to ML, this notebook may be helpful for you...
(cols): age = cols[0] titles = cols[1] if pd.isnull(age): return age_by_title[titles] else: return age # In[ ]: train['Age'] = train[['Age', 'Title']].apply(fill_missing_ages, axis=1) test['Age'] = test[['Age', 'Title']].apply(fill_missing_ages, axis=1) #and one Fare value in t...
fill_missing_ages
identifier_name
detailed-titanic-analysis-and-solution.py
#!/usr/bin/env python # coding: utf-8 # Titanic is one of the classical problems in machine learning. There are many solutions with different approaches out there, so here is my take on this problem. I tried to explain every step as detailed as I could, too, so if you're new to ML, this notebook may be helpful for you...
# ### Prediction on the testing set and output # Now our model is ready, and we can make a prediction on the testing set and create a .csv output for submission. # In[ ]: prediction = g_boost.predict(X_final) # In[ ]: submission = pd.DataFrame({ 'PassengerId': test['PassengerId'], 'Survived': prediction ...
random_line_split
getdata.py
""" These are data input download and prep scripts. They download and massage the data for the UBM calculations (calc.py) """ from __future__ import absolute_import, division, print_function, unicode_literals import time import urllib try: # For Python 3.0 and later import urllib.request except ImportError: ...
arcpy.env.mask = area arcpy.CheckOutExtension("spatial") for rast in arcpy.ListRasters(): calc = SetNull(arcpy.Raster(rast) > 32700, arcpy.Raster(rast)) calc.save(outpath + data_type + rast[1:5] + rast[6:8] + 'h' + rast[10:11] + 'v' + rast[13:14]) print(outpath + data_type + rast[1...
area = 'H:/GIS/Calc.gdb/WBD_UT'
conditional_block
getdata.py
""" These are data input download and prep scripts. They download and massage the data for the UBM calculations (calc.py) """ from __future__ import absolute_import, division, print_function, unicode_literals import time import urllib try: # For Python 3.0 and later import urllib.request except ImportError: ...
(save_path, wld='*.105*.hdf'): """ Args: save_path: path to folder where raw MODIS files are wld: common wildcard in all of the raw MODIS files Returns: list of files to analyze in the raw folder """ return glob.glob(os.path.join(save_path, wld)) def reproject_modis(file...
get_file_list
identifier_name
getdata.py
""" These are data input download and prep scripts. They download and massage the data for the UBM calculations (calc.py) """ from __future__ import absolute_import, division, print_function, unicode_literals import time import urllib try: # For Python 3.0 and later import urllib.request except ImportError: ...
prodcode = {'us_ssmv11038wS__A': 'SPAT', 'us_ssmv11044bS__T': 'SNML', 'us_ssmv11050lL00T': 'SPSB', 'us_ssmv11034tS__T': 'SWEQ', 'us_ssmv01025SlL00': 'RAIN', 'us_ssmv01025SlL01': 'SNOW', 'us_ssmv11036tS__T': 'SNOD', 'us_ssmv11039lL00T': 'BSSB'} for filename in os.listdir(path): ...
def rename_polaris_snodas(path):
random_line_split
getdata.py
""" These are data input download and prep scripts. They download and massage the data for the UBM calculations (calc.py) """ from __future__ import absolute_import, division, print_function, unicode_literals import time import urllib try: # For Python 3.0 and later import urllib.request except ImportError: ...
def merge_rasts(path, data_type='ET', monthRange='', yearRange='', outpath=''): """Mosaics (merges) different MODIS cells into one layer. """ if monthRange == '': monthRange = [1, 12] if yearRange == '': yearRange = [2000, 2015] if outpath == '': outpath = path arcp...
"""Clips raster to Utah's Watersheds and makes exception values null. Args: path: folder of the reprojected MODIS files outpath: ESRI gdb to store the clipped files data_type: type of MODIS16 data being reprojected; options are 'ET','PET','LE', and 'PLE' area: path to polygon used t...
identifier_body
nfa2regex.py
from util import AutomataError from automata import NFA from base import Node from copy import copy, deepcopy from os.path import commonprefix DEBUG = False LAMBDA = u'\u03bb' PHI = u'\u00d8' def copyDeltas(src): out = dict() for k in src: out[k] = dict() for k2 in src[k]: out[k]...
# Sort pliable nodes by distance from terminal pliableNodes.sort(key=lambda x: nodeFinalDist[x], reverse=True) if DEBUG: print('Pliables: ', pliableNodes) for node in pliableNodes: # Remove Node network.remNode(node) # Save delta delta = copy(network.getDelta(...
for node in toProcess: dests = network.getDelta(node).values() if len(dests) == 0: dests = set([]) else: dests = reduce(set.union, network.getDelta(node).values()) if len(dests) == 0: toProcess.remove(node) else...
conditional_block
nfa2regex.py
from util import AutomataError from automata import NFA from base import Node from copy import copy, deepcopy from os.path import commonprefix DEBUG = False LAMBDA = u'\u03bb' PHI = u'\u00d8' def copyDeltas(src): out = dict() for k in src: out[k] = dict() for k2 in src[k]: out[k]...
seq = [reverse(i) for i in seq] return reverse(commonprefix(seq)) class NetworkNFA(NFA): def __init__(self, nfa): if type(nfa) is not NFA: raise AutomataError('Can create a NetworkNFA only from an NFA.') if all([len(i) == 1 for i in nfa.charset]): self._charset =...
out = '' for c in reversed(s): out += c return out
identifier_body
nfa2regex.py
from util import AutomataError from automata import NFA from base import Node from copy import copy, deepcopy from os.path import commonprefix DEBUG = False LAMBDA = u'\u03bb' PHI = u'\u00d8' def
(src): out = dict() for k in src: out[k] = dict() for k2 in src[k]: out[k][k2] = copy(src[k][k2]) return out def replaceNode(nfa, old, new): if DEBUG: print('R_Start(%s, %s) ---' % (old, new), nfa) if old in nfa._deltas: for input in nfa._deltas[old]: ...
copyDeltas
identifier_name
nfa2regex.py
from util import AutomataError from automata import NFA from base import Node from copy import copy, deepcopy from os.path import commonprefix DEBUG = False LAMBDA = u'\u03bb' PHI = u'\u00d8' def copyDeltas(src): out = dict() for k in src: out[k] = dict() for k2 in src[k]: out[k]...
if type(dest) is set and all([type(i) is Node for i in dest]): if len(dest): if node in self._deltas: if input in self._deltas[node]: self._deltas[node][input] = self._deltas[node][input].union( ...
raise AutomataError('%s contains symbols not in charset.' % input) if type(node) is Node:
random_line_split
metrics.py
import math import sys import os import numpy as np import requests import zipfile from collections import Counter from clint.textui import progress from metrics.bleu_metrics import BleuMetrics from metrics.distinct_metrics import DistinctMetrics from metrics.entropy_metrics import EntropyMetrics from metrics.embeddin...
total_length = int(data_stream.headers.get('content-length')) for chunk in progress.bar(data_stream.iter_content(chunk_size=1024), expected_size=total_length / 1024 + 1): if chunk: file.write(chunk) file.flush() # Extract file. zip_file = ...
'vectors-english/wiki-news-300d-1M.vec.zip', stream=True) zipped_path = os.path.join(self.input_dir, 'fasttext.zip') with open(zipped_path, 'wb') as file:
random_line_split
metrics.py
import math import sys import os import numpy as np import requests import zipfile from collections import Counter from clint.textui import progress from metrics.bleu_metrics import BleuMetrics from metrics.distinct_metrics import DistinctMetrics from metrics.entropy_metrics import EntropyMetrics from metrics.embeddin...
if not os.path.exists(self.vector_vocab): print('File containing word vectors not found in ' + self.vector_vocab) print('If you would like to use FastText embeddings press \'y\'') if input() == 'y': self.get_fast_text_embeddings() else: print('Embedding metrics and \'coheren...
print('Can\' find test targets at ' + self.test_target + ', embedding, kl divergence, and bleu metrics won\'t be computed.') self.delete_from_metrics(['kl-div', 'embedding', 'bleu'])
conditional_block
metrics.py
import math import sys import os import numpy as np import requests import zipfile from collections import Counter from clint.textui import progress from metrics.bleu_metrics import BleuMetrics from metrics.distinct_metrics import DistinctMetrics from metrics.entropy_metrics import EntropyMetrics from metrics.embeddin...
self): for filename in self.metrics: responses = open(filename, encoding='utf-8') # If we don't need these just open a dummy file. sources = open(self.test_source, encoding='utf-8') \ if os.path.exists(self.test_source) else open(filename, encoding='utf-8') gt_responses = open(self.t...
un(
identifier_name
metrics.py
import math import sys import os import numpy as np import requests import zipfile from collections import Counter from clint.textui import progress from metrics.bleu_metrics import BleuMetrics from metrics.distinct_metrics import DistinctMetrics from metrics.entropy_metrics import EntropyMetrics from metrics.embeddin...
ith open(self.output_path, 'w') as output: output.write('filename ') output.write(' '.join([k for k, v in self.which_metrics.items() if v])) output.write('\n') ''' The first row contains the names of the metrics, then each row contains the name of the file and its metrics separated by spa...
identifier_body
cmh_test.py
""" Perform Cochran-Mantel-Haenszel chi-squared tests on stratified contingency tables. Each stratum is a population's contingency table; each population has a case and a control. Each contingency table is 2x2 - case and control x REF and ALT allele counts. ALT and REF allele counts are calculated by multiplying the...
if len(badcols) > 0: print(ColorText('FAIL: The following case populations to not have a valid control column in dataframe.').fail()) for cs,ct in badcols: print(ColorText(f'FAIL: no match for {cs} named {ct} in dataframe').fail()) print(ColorText('FAIL: These case columns have...
controlcol = casecol.replace(case, control) if not controlcol in controlcols: badcols.append((casecol, controlcol)) continue pairs[casecol] = controlcol
conditional_block
cmh_test.py
""" Perform Cochran-Mantel-Haenszel chi-squared tests on stratified contingency tables. Each stratum is a population's contingency table; each population has a case and a control. Each contingency table is 2x2 - case and control x REF and ALT allele counts. ALT and REF allele counts are calculated by multiplying the...
def __str__(self): return self.text def bold(self): self.text = '\033[1m' + self.text + self.ending return self def underline(self): self.text = '\033[4m' + self.text + self.ending return self def green(self): self.text = '\033[92m' + self.text + self...
self.text = text self.ending = '\033[0m' self.colors = []
identifier_body
cmh_test.py
""" Perform Cochran-Mantel-Haenszel chi-squared tests on stratified contingency tables. Each stratum is a population's contingency table; each population has a case and a control. Each contingency table is 2x2 - case and control x REF and ALT allele counts. ALT and REF allele counts are calculated by multiplying the...
(engines:int, profile:str): """Reload engines until number matches input engines arg.""" lview = [] dview = [] count = 1 while any([len(lview) != engines, len(dview) != engines]): if count % 30 == 0: # if waiting too long.. # TODO: if found engines = 0, no reason to a...
wait_for_engines
identifier_name
cmh_test.py
""" Perform Cochran-Mantel-Haenszel chi-squared tests on stratified contingency tables. Each stratum is a population's contingency table; each population has a case and a control. Each contingency table is 2x2 - case and control x REF and ALT allele counts. ALT and REF allele counts are calculated by multiplying the...
# write to outfile outfile = op.join(args.outdir, op.basename(args.input).split(".")[0] + '_CMH-test-results.txt') print(ColorText(f'\nWriting all results to: ').bold().__str__()+ f'{outfile} ...') output.to_csv(outfile, sep='\t', index=False) # write logs logfile = outfile.re...
# run cmh tests in parallel output,logs = parallelize_cmh(casedata, controldata, lview)
random_line_split
regexp.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // The testing package implements a simple regular expression library. // It is a reduced version of the regular expression package suitable // for use in tests...
return } switch p.c() { case '*': // (start,end)*: alt := new(_Alt); p.re.add(alt); end.setNext(alt); // after end, do alt alt.left = start; // alternate brach: return to start start = alt; // alt becomes new (start, end) end = alt; case '+': // (start,end)+: alt := new(_Alt); p.re.add(alt); ...
start, end = p.term(); if start == nil || p.error != "" {
random_line_split
regexp.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // The testing package implements a simple regular expression library. // It is a reduced version of the regular expression package suitable // for use in tests...
return; } // MatchSlices matches the Regexp against the byte slice b. // The return value is an array of subslices matched by the expression. // a[0] is the subslice matched by the entire expression. // a[i] for i > 0 is the subslice matched by the ith parenthesized subexpression. // An empty array means ``no ...
{ if r[i] != -1 { // -1 means no match for this subexpression a[i/2] = s[r[i]:r[i+1]] } }
conditional_block