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
main.rs
c| match c { Self::And(es) => es, x => vec![x], }) .collect(), ) } /// convert the expression into disjunctive normal form /// /// careful, for some expressions this can have exponential runtime. E.g. the disjunctive normal...
Ok(serde_cbor::from_slice(&decompressed)?) } fn borrow_inner(elements: &[BTreeSet<String>]) -> Vec<BTreeSet<&str>> { elements.iter().map(|x| x.iter().map(|e| e.as_ref()).collect()).collect()
random_line_split
main.rs
<_>>(); // not a single query can possibly match, no need to iterate. if query.is_empty() { return Vec::new(); } // check the remaining queries self.elements .iter() .enumerate() .filter_map(|(i, e)| { if query.iter(...
fn and(e: Vec<Expression>) -> Self { Self::And( e.into_iter() .flat_map(|c| match c { Self::And(es) => es, x => vec![x], }) .collect(), ) } /// convert the expression into disjunctive norma...
{ Self::Or( e.into_iter() .flat_map(|c| match c { Self::Or(es) => es, x => vec![x], }) .collect(), ) }
identifier_body
main.rs
<_>>(); // not a single query can possibly match, no need to iterate. if query.is_empty() { return Vec::new(); } // check the remaining queries self.elements .iter() .enumerate() .filter_map(|(i, e)| { if query.iter(...
(e: Vec<Expression>) -> Self { Self::Or( e.into_iter() .flat_map(|c| match c { Self::Or(es) => es, x => vec![x], }) .collect(), ) } fn and(e: Vec<Expression>) -> Self { Self::And( ...
or
identifier_name
main.rs
} } Ok(Index { strings: strings.into_iter().collect(), elements, }) } } impl Index { /// given a query expression in Dnf form, returns all matching indices pub fn matching(&self, query: Dnf) -> Vec<usize> { // lookup all strings and trans...
{ return Err(serde::de::Error::custom("invalid string index")); }
conditional_block
xterm.rs
fn from(color: XtermColors) -> Self { match color { $( XtermColors::$name => $xterm_num, )* } } } } $( #[allow(missing_docs)] ...
impl From<XtermColors> for u8 {
random_line_split
gtmaps.py
_z = min(reach_z) nav_grid = np.zeros((c_x,c_z)) for i in range(nav_grid.shape[0]): for j in range(nav_grid.shape[1]): if [m_x + i*0.25, m_z + j*0.25] in coords: nav_grid[i,j] = 1 else: nav_grid[i,j] = 0 #print("nav_grid after disabling...
d = '>' #"\u2192" #right arrow if locator[2]==270: d = '^' #"\u2191" #up arrow if locator[2]==90: d = 'v' #"\u2193" #down arrow if locator[2]==180: d = '<' #"...
for j in range(mat.shape[1]): d = repr(j) if j<10: d = '0'+d print(d,end = '') print(" ",end = '') print(" ") print(" ") for i in range(mat.shape[0]): for j in range(mat.shape[1]): d = 0 if argmax: d...
identifier_body
gtmaps.py
m_z = min(reach_z) nav_grid = np.zeros((c_x,c_z)) for i in range(nav_grid.shape[0]): for j in range(nav_grid.shape[1]): if [m_x + i*0.25, m_z + j*0.25] in coords: nav_grid[i,j] = 1 else: nav_grid[i,j] = 0 #print("nav_grid after disabli...
print(" ",end = '') print(" --",repr(i)) #print(" ") def surrounding_patch(agentloc, labeled_grid, R = 16, unreach_value = -1): #returns a visibility patch centered around the agent with radius R #unreach_value = -1 mat = labeled_grid position = agentloc r=copy...
if locator[2]==180: d = '<' #"\u2190" #left arrow print(d,end = '')
random_line_split
gtmaps.py
append black columns to the left of agent position #print("Increasing columns to left ") mat = np.insert(mat,0, unreach_value,axis=1) r-=1 p[0]+=1 r=copy.copy(R) while position[0]+r>init_shape[1]-1: #append blank columns to the right of the agent position #print("I...
prettyprint(o_grids[obj])
conditional_block
gtmaps.py
(env,event): #sometimes in a room there are fixed objects which cannot be removed from scene using disable command #so need to go near them to check distance and then map them return def gtmap(env,event): objs = event.metadata['objects'] print("There are a total of ",len(objs)," objects ...
touchmap
identifier_name
corpus_wikipedia.py
', #'/home/arne/devel/ML/data/corpora/WIKIPEDIA/wikipedia-23886057.csv',#'/home/arne/devel/ML/data/corpora/WIKIPEDIA/documents_utf8_filtered_20pageviews.csv', # '/home/arne/devel/ML/data/corpora/SICK/sick_train/SICK_train.txt', 'The path to the SICK train data file.') #tf.flags.DEFINE_string( # 'corpus_data_inpu...
tree_mode=tree_mode, child_idx_offset=child_idx_offset) print('dump data, parents, depths and child indices for offset=' + str(offset) + ' ...') current_seq_data.dump(out_path + '.data.batch' + str(offset)) current_seq_parents.dump(out_path + '.parent.batch' + str(offset)...
out_fn = ntpath.basename(out_path) print('parse articles ...') child_idx_offset = 0 for offset in range(0, max_articles, batch_size): # all or none: otherwise the mapping lacks entries! #if not careful or not os.path.isfile(out_path + '.data.batch' + str(offset)) \ # or not o...
identifier_body
corpus_wikipedia.py
', #'/home/arne/devel/ML/data/corpora/WIKIPEDIA/wikipedia-23886057.csv',#'/home/arne/devel/ML/data/corpora/WIKIPEDIA/documents_utf8_filtered_20pageviews.csv', # '/home/arne/devel/ML/data/corpora/SICK/sick_train/SICK_train.txt', 'The path to the SICK train data file.') #tf.flags.DEFINE_string( # 'corpus_data_inpu...
return parser def parse_articles(out_path, parent_dir, in_filename, parser, mapping, sentence_processor, max_depth, max_articles, batch_size, tree_mode): out_fn = ntpath.basename(out_path) print('parse articles ...') child_idx_offset = 0 for offset in range(0, max_articles, batch_size): ...
if not os.path.isfile(out_filename + '.children.depth' + str(current_depth)): preprocessing.merge_numpy_batch_files(out_base_name + '.children.depth' + str(current_depth), parent_dir)
conditional_block
corpus_wikipedia.py
', #'/home/arne/devel/ML/data/corpora/WIKIPEDIA/wikipedia-23886057.csv',#'/home/arne/devel/ML/data/corpora/WIKIPEDIA/documents_utf8_filtered_20pageviews.csv', # '/home/arne/devel/ML/data/corpora/SICK/sick_train/SICK_train.txt', 'The path to the SICK train data file.') #tf.flags.DEFINE_string( # 'corpus_data_inpu...
articles_from_csv_reader, sentence_processor, parser, mapping, args={ 'filename': in_filename, 'max_articles': min(batch_size, max_articles), 'skip': offset }, max_depth=max_depth, batch_size=batch_si...
#if not careful or not os.path.isfile(out_path + '.data.batch' + str(offset)) \ # or not os.path.isfile(out_path + '.parent.batch' + str(offset)) \ # or not os.path.isfile(out_path + '.depth.batch' + str(offset)) \ # or not os.path.isfile(out_path + '.children.batch'...
random_line_split
corpus_wikipedia.py
', #'/home/arne/devel/ML/data/corpora/WIKIPEDIA/wikipedia-23886057.csv',#'/home/arne/devel/ML/data/corpora/WIKIPEDIA/documents_utf8_filtered_20pageviews.csv', # '/home/arne/devel/ML/data/corpora/SICK/sick_train/SICK_train.txt', 'The path to the SICK train data file.') #tf.flags.DEFINE_string( # 'corpus_data_inpu...
(out_path, parent_dir, in_filename, parser, mapping, sentence_processor, max_depth, max_articles, batch_size, tree_mode): out_fn = ntpath.basename(out_path) print('parse articles ...') child_idx_offset = 0 for offset in range(0, max_articles, batch_size): # all or none: otherwise the mapping la...
parse_articles
identifier_name
sync.go
() error { if w.holeSize > 0 { err := w.writer.PunchHole(w.offset, w.holeSize) if err == nil { w.offset += w.holeSize w.holeSize = 0 } return err } if len(w.buf) == 0 { return nil } n, err := w.writer.WriteAt(w.buf, w.offset) if err != nil { return err } w.buf = w.buf[:0] w.offset += int64(n)...
Flush
identifier_name
sync.go
} written += n2 if err != nil { return written, err } } else { written += n } p = p[n:] } } return written, nil } func (w *batchingWriter) ReadFrom(src io.Reader) (int64, error) { if err := w.prepareWrite(); err != nil { return 0, err } var read int64 for { n, err := src...
n2 = 0
random_line_split
sync.go
, error)
err := w.Flush() w.offset = offset if err != nil { return offset, err } } return offset, nil } type counting struct { count int64 } type CountingReader struct { io.Reader counting } type CountingWriteCloser struct { io.WriteCloser counting } func (p *hashPool) get() (h hash.Hash) { l := len(*p) ...
{ var o int64 if w.holeSize > 0 { o = w.offset + w.holeSize } else { o = w.offset + int64(len(w.buf)) } switch whence { case io.SeekStart: // no-op case io.SeekCurrent: offset = o + offset case io.SeekEnd: var err error offset, err = w.writer.Seek(offset, whence) if err != nil { return offset, ...
identifier_body
sync.go
} } } func (w *batchingWriter) WriteHole(size int64) error { if w.holeSize == 0 { err := w.Flush() if err != nil { return err } } w.holeSize += size return nil } func (w *batchingWriter) Seek(offset int64, whence int) (int64, error) { var o int64 if w.holeSize > 0 { o = w.offset + w.holeSize } e...
{ return read, err }
conditional_block
event.py
_* methods depend on this attribute. Can be: 'QUIT', 'KEYDOWN', 'KEYUP', 'MOUSEDOWN', 'MOUSEUP', or 'MOUSEMOTION.' """ def __repr__(self): """List an events public attributes when printed. """ attrdict = {} for varname in dir(self): if '_' == varname[0]: ...
return '%s(%s)' % (self.__class__.__name__, ', '.join(parameters)) class KeyDown(KeyEvent): """Fired when the user presses a key on the keyboard or a key repeats. """ type = 'KEYDOWN' class KeyUp(KeyEvent): """Fired when the user releases a key on the keyboard. """ type = 'KEYUP' _mo...
parameters.append('%s=%r' % (attr, value))
conditional_block
event.py
'QUIT', 'KEYDOWN', 'KEYUP', 'MOUSEDOWN', 'MOUSEUP', or 'MOUSEMOTION.' - L{MouseButtonEvent.button} (found in L{MouseDown} and L{MouseUp} events) 'LEFT', 'MIDDLE', 'RIGHT', 'SCROLLUP', 'SCROLLDOWN' - L{KeyEvent.key} (found in L{KeyDown} and L{KeyUp} events) 'NONE', 'ESCAPE', 'BACKSPAC...
random_line_split
event.py
_* methods depend on this attribute. Can be: 'QUIT', 'KEYDOWN', 'KEYUP', 'MOUSEDOWN', 'MOUSEUP', or 'MOUSEMOTION.' """ def __repr__(self): """List an events public attributes when printed. """ attrdict = {} for varname in dir(self): if '_' == varname[0]: ...
class MouseDown(MouseButtonEvent): """Fired when a mouse button is pressed.""" __slots__ = () type = 'MOUSEDOWN' class MouseUp(MouseButtonEvent): """Fired when a mouse button is released.""" __slots__ = () type = 'MOUSEUP' class MouseMotion(Event): """Fired when the mouse is moved.""" ...
def __init__(self, button, pos, cell): self.button = _mouseNames[button] """Can be one of 'LEFT', 'MIDDLE', 'RIGHT', 'SCROLLUP', 'SCROLLDOWN' @type: string""" self.pos = pos """(x, y) position of the mouse on the screen @type: (int, int)""" self.cell = cel...
identifier_body
event.py
on the screen @type: (int, int)""" self.cell = cell """(x, y) position of the mouse snapped to a cell on the root console @type: (int, int)""" class MouseDown(MouseButtonEvent): """Fired when a mouse button is pressed.""" __slots__ = () type = 'MOUSEDOWN' class MouseUp(Mou...
wait
identifier_name
dealerDispatcherList.js
*) pageList: [10, 25, 50, 100], //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据 url: "${ctx}/process/shopmsg/shopMsg/dataDispatcher", //默认值为 'limit',传给服务端的参数为:limit, offset, search, sort, order Else //queryParamsType:'', ...
conditional_block
dealerDispatcherList.js
true, //显示 内容列下拉框 showColumns: true, //显示到处按钮 showExport: true, //显示切换分页按钮 showPaginationSwitch: true, //最低显示2行 minimumCountColumns: 2, //是否显示行间隔色 striped: true, //是否使用缓存,默认为t...
} ,{ field: 'legalPersonName', title: '法人姓名', sortable: true } ,{ field: 'legalPersonIdCard', title: '法人身份号', sort...
sortable: true
random_line_split
entities.py
return cast(Iterator[T], super().__iter__()) ENTITY_WIDTH = 10 ENTITY_HEIGHT = 10 class Entity(pygame.sprite.Sprite): @classmethod def create_group(cls: Type[T], size: int, point_getter: PointProducer) -> EntityGroup[T]: all_group = EntityGroup[T](cls) ...
(self): super().__init__(HUMAN_COLOR) self.lifetime: Generator[float, None, None] = self.new_lifetime() def eat_food(self, food: Food) -> None: if self.is_hungry(): food.consume() self.lifetime = self.new_lifetime() self.change_dir() def is_hungry(se...
__init__
identifier_name
entities.py
(self, pos: Point) -> None: groups = self.groups() self._mouse_groups = [] for group in groups: group.remove(self) self._mouse_groups.append(group) self._mouse_offset = self.position - pos def update_pick_up(self, pos: Point) -> None: new_point = pos ...
span = zutil.span(field.bounds) span_mid = span / 2.0 food, _ = self.closest_to(field.food, field.bounds) if food is not None: direc = Direction.from_points(self.position, food.position) dist = self.position.distance(food.position) if d...
conditional_block
entities.py
return cast(Iterator[T], super().__iter__()) ENTITY_WIDTH = 10 ENTITY_HEIGHT = 10 class Entity(pygame.sprite.Sprite): @classmethod def create_group(cls: Type[T], size: int, point_getter: PointProducer) -> EntityGroup[T]: all_group = EntityGroup[T](cls) ...
def put_down(self, pos: Point): self.update_pick_up(pos) for group in self._mouse_groups: group.add(self) del self._mouse_groups del self._mouse_offset def update(self, *args, **kwargs) -> None: """ Let's be honest - this is to make the typing system happy"...
new_point = pos + self._mouse_offset self.rect.center = int(new_point.x), int(new_point.y) self.reset_pos()
identifier_body
entities.py
return cast(Iterator[T], super().__iter__()) ENTITY_WIDTH = 10 ENTITY_HEIGHT = 10 class Entity(pygame.sprite.Sprite): @classmethod def create_group(cls: Type[T], size: int, point_getter: PointProducer) -> EntityGroup[T]: all_group = EntityGroup[T](cls) ...
continue dist = pos.distance(each.position) if dist > span_mid: dist = span - dist if dist < curmin: curmin = dist curactor = each return (curactor, curmin) def update_state(self, field: World) -> None: ...
curactor: Optional[C] = None pos = self.position for each in other: if not to_include(each):
random_line_split
parser.py
.split(':')[1]) if mode != 0: raise ModeError(mode) elif 'Title' in line and 'Unicode' not in line: beatmap['title'] = line.split(':')[1].strip() beatmap['title_lower'] = beatmap['title'].lower() elif 'Version' in line: beatmap['version'] =...
def circle_radius(cs, hd, ez): mod_cs = cs if hd: mod_cs *= 1.3 elif ez: mod_cs /= 2 return (104.0 - mod_cs * 8.0) / 2.0 def dist(p_input, obj): return math.sqrt(math.pow(p_input['x'] - obj.x, 2) + \ math.pow(p_input['y'] - obj.y, 2)) def score_hit(time, obj, window): ...
buttons = [] for k in ['K1', 'K2', 'M1', 'M2']: if cur_input['keys'][k] and not prev_input['keys'][k]: buttons.append(k) return buttons
identifier_body
parser.py
# get the rotation matrix a = math.cos(theta) b = math.sin(theta) R = np.matrix([[a, -b], [b, a]]) # apply the rotation matrix to the coordinates coords = np.ravel(R * np.matrix([[dx], [dy]])) # remap to hitmap pixel coordinates coords += HITMAP_SIZE / 2 # one last remapping to hitm...
print(json.dumps({'error': 'Unsupported game mode.'})) sys.exit(0)
conditional_block
parser.py
def __init__(self, time, mpb): self.time = time self.mpb = mpb def parse_object(line): params = line.split(',') x = float(params[0]) y = float(params[1]) time = int(params[2]) objtype = int(params[3]) # hit circle if (objtype & 1) != 0: return HitObject(x, y, t...
class TimingPoint: time = -1 mpb = -1
random_line_split
parser.py
(self): return repr(self.mode) class HitObject: x = -1 y = -1 time = -1 lenient = False def __init__(self, x, y, time, lenient): self.x = x self.y = y self.time = time self.lenient = lenient self.tags = [] def add_tag(self, tag): if tag ...
__str__
identifier_name
changeLanguage.js
ansowania" document.querySelector('.advanced3').textContent = "Poziom zaawansowania" document.querySelector('.advanced4').textContent = "Poziom zaawansowania" document.querySelector('.advanced5').textContent = "Poziom zaawansowania" document.querySelector('.advanced6').textContent = "Poziom zaawansowani...
document.querySelector('.pro1').textContent = "Zaawansowany" document.querySelector('.pro6').textContent = "Zaawansowany" document.querySelector('.headerAbout').textContent = "TROSZKĘ O MOJEJ PRACY..." //EDIT document.querySelector('.pAbout').textContent = "Jako programista przemysłowy, zajmuję się...
random_line_split
base.rs
t: PhantomData<T> } impl<T: ReteIntrospection> KnowledgeBase<T> { pub fn compile(builder: KnowledgeBuilder<T>) -> KnowledgeBase<T> { let (string_repo, rules, condition_map) = builder.explode(); let (hash_eq_nodes, alpha_network, statement_memories) = Self::compile_alpha_network(condition_map...
} } pub struct KnowledgeBase<T: ReteIntrospection> {
random_line_split
base.rs
: KnowledgeBuilder<T>) -> KnowledgeBase<T> { let (string_repo, rules, condition_map) = builder.explode(); let (hash_eq_nodes, alpha_network, statement_memories) = Self::compile_alpha_network(condition_map); let mut statement_rule_map = HashMap::new(); for (rule_id, rule) in rules { ...
else { unreachable!("Unexpected comparison. HashEq must be set"); } }); let mut node_id_gen = LayoutIdGenerator::new(); let mut hash_eq_nodes = HashMap::new(); let mut statement_memories: HashMap<StatementId, MemoryId> = HashMap::new(); let mut al...
{ hash1.dependents.len().cmp(&hash2.dependents.len()).then(tests1.len().cmp(&tests2.len())) }
conditional_block
base.rs
::HashEq).unwrap(); let hash_eq_id = node_id_gen.next_hash_eq_id(); let mut hash_eq_destinations: Vec<DestinationNode> = Vec::new(); // Lay down the node for the most shared nodes before the others while let Some((max_info, max_intersection)) = test_map.iter() ...
insert
identifier_name
base.rs
_eq_destinations.push(destination_id.into()); } // Add the HashEq node to the map && store any remaining statements for the beta network hash_eq_nodes.insert(hash_eq_id, (hash_val, HashEqNode{id: hash_eq_id, store: !hash_eq_info.dependents.is_empty(), destinations: hash_eq_destinati...
{ let rc = Rc::new(val); if !self.store.insert(rc.clone()) { self.store.get(&rc).unwrap().clone() } else { rc } }
identifier_body
lib.rs
raw: RawBlock<'a>, hl: Hashlife<'a>, lg_size: usize, } #[derive(Clone, Copy, Debug)] pub struct Node<'a> { raw: RawNode<'a>, hl: Hashlife<'a>, lg_size: usize, } impl<'a> Drop for HashlifeCache<'a> { fn drop(&mut self) { self.blank_cache.get_mut().clear(); } } impl<'a> Hashlife<'a...
{ self.node_block(make_2x2(|_,_| self.random_block(rng, lg_size-1))) }
conditional_block
lib.rs
> { raw: RawBlock<'a>, hl: Hashlife<'a>, lg_size: usize, } #[derive(Clone, Copy, Debug)] pub struct Node<'a> { raw: RawNode<'a>, hl: Hashlife<'a>, lg_size: usize, } impl<'a> Drop for HashlifeCache<'a> { fn drop(&mut self) { self.blank_cache.get_mut().clear(); } } impl<'a> Hash...
/// Hashlife algorithm. /// /// This is the raw version of big stepping. pub fn raw_evolve(&self, node: RawNode<'a>) -> RawBlock<'a> { evolve::evolve(self, node, node.lg_size() - LG_LEAF_SIZE - 1) } /// Given 2^(n+1)x2^(n+1) node `node`, progress it 2^(n-1) generations and /// retur...
/// Given 2^(n+1)x2^(n+1) node `node`, progress it 2^(n-1) generations and /// return 2^nx2^n block in the center. This is the main component of the
random_line_split
lib.rs
(), elem_lg_size, "Sizes don't match in new node")); let raw_elems = make_2x2(|i, j| elems[i][j].to_raw()); Node { raw: self.raw_node(raw_elems), hl: *self, lg_size: elem_lg_size + 1, } } /// Create a new block with `elems` as corners ...
{ self.destruct().unwrap_err() }
identifier_body
lib.rs
} #[derive(Clone, Copy, Debug)] pub struct Node<'a> { raw: RawNode<'a>, hl: Hashlife<'a>, lg_size: usize, } impl<'a> Drop for HashlifeCache<'a> { fn drop(&mut self) { self.blank_cache.get_mut().clear(); } } impl<'a> Hashlife<'a> { /// Create a new Hashlife and pass it to a function. F...
fmt
identifier_name
server_cgi.go
//doRelay relays url to websocket. //e.g. accept http://relay.com:8000/server.cgi/relay/client.com:8000/server.cgi/join/other.com:8000+server.cgi func doRelay(w http.ResponseWriter, r *http.Request) { reg := regexp.MustCompile("^" + ServerURL + `/relay/(([^/]+)/[^/]*.*)`) m := reg.FindStringSubmatch(r.URL.Path) if...
{ s.RegistCompressHandler(ServerURL+"/ping", doPing) s.RegistCompressHandler(ServerURL+"/node", doNode) s.RegistCompressHandler(ServerURL+"/join/", doJoin) s.RegistCompressHandler(ServerURL+"/bye/", doBye) s.RegistCompressHandler(ServerURL+"/have/", doHave) s.RegistCompressHandler(ServerURL+"/removed/", doGetHead...
identifier_body
server_cgi.go
.ResponseWriter, r *http.Request) { s, err := newServerCGI(w, r) if err != nil { log.Println(err) return } host, path, port := s.extractHost("bye") host = s.checkRemote(host) if host == "" { return } n, err := node.MakeNode(host, path, port) if err == nil { s.NodeManager.RemoveFromList(n) } fmt.Fprin...
parseStamp
identifier_name
server_cgi.go
.Handle(ServerURL+"/request_relay/", websocket.Handler(websocketRelay(relaynum))) } } //doRelay relays url to websocket. //e.g. accept http://relay.com:8000/server.cgi/relay/client.com:8000/server.cgi/join/other.com:8000+server.cgi func doRelay(w http.ResponseWriter, r *http.Request) { reg := regexp.MustCompile("^" ...
host, port, err := net.SplitHostPort(ws.Request().RemoteAddr) if err != nil { log.Println(err) return } p, err := strconv.Atoi(port) if err != nil { log.Println(err) return } log.Println("websocket client:", host, port) n, err := node.MakeNode(host, "/server.cgi", p) if err != nil { lo...
{ log.Println("num of relays", n, "is over", relaynum) return }
conditional_block
server_cgi.go
* POSSIBILITY OF SUCH DAMAGE. */ package cgi import ( "math" "errors" "fmt" "io/ioutil" "log" "net" "net/http" "net/http/httputil" "net/url" "regexp" "strconv" "strings" "time" "golang.org/x/net/websocket" "github.com/shingetsu-gou/go-nat" "github.com/shingetsu-gou/http-relay" "github.com/shinget...
random_line_split
image_convolution.py
0, convMask): for y in range(0, convMask): convMatrix[x][y] = 0 # cnt = cnt+1 convMatrix[1][1] = 1 # ----------------------------------------------Load Images----------------------------------------------# image = PIL.Image.open("bumbleKoda.png") # Open default image to memory thumbnailImage = PIL...
else: imageStart = 2 imageStopWidth = imageWidth-2 imageStopHeight = imageHeight-2 start = time.clock() # timer (debug message) for x in range(imageStart, imageStopWidth): # Image Rows, ignore outside pixels print x,"/",(imageStopWidth) for y in range(imageStart, ...
imageStart = 2 imageStopWidth = 128 imageStopHeight = 128
conditional_block
image_convolution.py
0, convMask): for y in range(0, convMask): convMatrix[x][y] = 0 # cnt = cnt+1 convMatrix[1][1] = 1 # ----------------------------------------------Load Images----------------------------------------------# image = PIL.Image.open("bumbleKoda.png") # Open default image to memory thumbnailImage = PIL...
(): # updates the normalizer and each value of the convolution matrix to what was entered by user global normalizer global convMatrix convMatrix[0][0] = int(matrix_1_1.get()) convMatrix[0][1] = int(matrix_1_2.get()) convMatrix[0][2] = int(matrix_1_3.get()) convMatrix[1][0] = int(matrix_2_1.get(...
update_matrix
identifier_name
image_convolution.py
0, convMask): for y in range(0, convMask): convMatrix[x][y] = 0 # cnt = cnt+1 convMatrix[1][1] = 1 # ----------------------------------------------Load Images----------------------------------------------# image = PIL.Image.open("bumbleKoda.png") # Open default image to memory thumbnailImage = PIL...
apply_filter.pack(side=TOP, fill=X) preview_checkbox = Checkbutton(frame, text="Small Section Preview", command=swap_checkbox_value) preview_checkbox.pack(side=TOP, fill=X) load_image = Button(frame, text="Load Image", command=image_load) load_image.pack(side=TOP, fill=X) path = Entry(frame) # text entry field, for...
quit_button = Button(frame, text="QUIT", command=frame.quit) quit_button.pack(side=BOTTOM, fill=X) apply_filter = Button(frame, text="Apply Matrix Filter", command=apply_matrix)
random_line_split
image_convolution.py
0, convMask): for y in range(0, convMask): convMatrix[x][y] = 0 # cnt = cnt+1 convMatrix[1][1] = 1 # ----------------------------------------------Load Images----------------------------------------------# image = PIL.Image.open("bumbleKoda.png") # Open default image to memory thumbnailImage = PIL...
def update_matrix(): # updates the normalizer and each value of the convolution matrix to what was entered by user global normalizer global convMatrix convMatrix[0][0] = int(matrix_1_1.get()) convMatrix[0][1] = int(matrix_1_2.get()) convMatrix[0][2] = int(matrix_1_3.get()) convMatrix[1][0] =...
photo = PhotoImage(file="processedImageThumbnail.gif") display_image.configure(image=photo) display_image.photo = photo
identifier_body
models.ts
, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Ajax, Filter, Utils } from '@labkey/api'; import { List, Map, Record } from 'immutable'; import { Option } from 'react-select'; import { getEditorModel } from '../../global...
} throw new Error('SampleIdCreationModel.models.revertParentInputSchema -- invalid inputColumn fieldKey length.'); } throw new Error('SampleIdCreationModel.models.revertParentInputSchema -- invalid inputColumn.'); } getGridValues(queryInfo: QueryInfo): Map<any, any> { ...
} return SchemaQuery.create(schemaName, fieldKey[1]);
random_line_split
models.ts
, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Ajax, Filter, Utils } from '@labkey/api'; import { List, Map, Record } from 'immutable'; import { Option } from 'react-select'; import { getEditorModel } from '../../global...
else { console.warn('SampleSet/actions/getSampleInputs -- Unable to parse rowId from "' + option.value + '" for ' + role + '.'); } }); } } }); return { dataInputs, ...
{ const input = {role, rowId}; if (isData) { dataInputs.push(input); } else { materialInputs.push(input); } ...
conditional_block
models.ts
, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Ajax, Filter, Utils } from '@labkey/api'; import { List, Map, Record } from 'immutable'; import { Option } from 'react-select'; import { getEditorModel } from '../../global...
() : string { return this.hasTargetSampleSet() ? this.targetSampleSet.value : undefined; } getSampleInputs(): { dataInputs: Array<SampleInputProps>, materialInputs: Array<SampleInputProps> } { let dataInputs: Array<SampleInputProps> = [], materialInputs: Array<Sa...
getTargetSampleSetName
identifier_name
models.ts
, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Ajax, Filter, Utils } from '@labkey/api'; import { List, Map, Record } from 'immutable'; import { Option } from 'react-select'; import { getEditorModel } from '../../global...
throw new Error('SampleIdCreationModel.models.revertParentInputSchema -- invalid inputColumn.'); } getGridValues(queryInfo: QueryInfo): Map<any, any> { let data = List<Map<string, any>>();
{ if (inputColumn.isExpInput()) { const fieldKey = inputColumn.fieldKey.toLowerCase().split('/'); if (fieldKey.length === 2) { let schemaName: string; if (fieldKey[0] === QueryColumn.DATA_INPUTS.toLowerCase()) { schemaName = SCHEMAS.DAT...
identifier_body
easy.rs
.find(|format| format.base_format().1 == ChannelType::Srgb) .unwrap_or(default_format) }; let (device, queue_group) = { let queue_family = adapter .queue_families .iter() .find(|family| { surface.supports_queue_family(family) &...
{ let instance = B::Instance::create(name, version).map_err(|_| "unsupported backend")?; let surface = unsafe { instance .create_surface(window) .map_err(|_| "create_surface failed")? }; let adapter = instance.enumerate_adapters().remove(0); let surface_color_format ...
identifier_body
easy.rs
== ubos && set.1.len() == images && set.2.len() == samplers), "All desc_sets must have the same layout of values" ); let mut binding_number = 0; let mut bindings = vec![]; let mut ranges = vec![]; for _ in 0..ubos { bindings.push(DescriptorSetLayoutBinding { binding: bi...
}, ); pipeline_desc.blender.targets.push(ColorBlendDesc {
random_line_split
easy.rs
unsafe { use gfx_hal::pool::CommandPoolCreateFlags; device .create_command_pool(queue_group.family, CommandPoolCreateFlags::empty()) .expect("out of memory") }; Ok(( instance, surface, surface_color_format, adapter, device, ...
; let pipeline_layout = unsafe { device .create_pipeline_layout(desc_layout.into_iter(), push.into_iter()) .expect("out of memory") }; let shader_modules = [(vs_bytes, false), (fs_bytes, true)] .iter() .map(|&(bytes, is_frag)| unsafe { B::make_shader_module(...
{ vec![] }
conditional_block
easy.rs
<B: Backend>( window: &crate::windowing::window::Window, name: &str, version: u32, ) -> Result< ( B::Instance, B::Surface, Format, Adapter<B>, B::Device, QueueGroup<B>, B::CommandPool, ), &'static str, > { let instance = B::Instance::cr...
init
identifier_name
sql.go
{ return nil, errors.New("specified both a deprecated `dsn` as well as a `data_source_name`") } dsn = conf.SQL.DSN deprecated = true } if len(conf.SQL.Args) > 0 && conf.SQL.ArgsMapping != "" { return nil, errors.New("cannot specify both `args` and an `args_mapping` in the same processor") } var argsMa...
{ s.mErr.Incr(1) s.log.Errorf("SQL error: %v\n", err) FlagErr(newMsg.Get(i), err) }
conditional_block
sql.go
bool `json:"unsafe_dynamic_query" yaml:"unsafe_dynamic_query"` Args []string `json:"args" yaml:"args"` ArgsMapping string `json:"args_mapping" yaml:"args_mapping"` ResultCodec string `json:"result_codec" yaml:"result_codec"` } // NewSQLConfig returns a SQLConfig with default val...
getArgs
identifier_name
sql.go
columns of footable that share a ` + "`user_id`" + ` with the message ` + "`user.id`" + `. The ` + "`result_codec`" + ` is set to ` + "`json_array`" + ` and a ` + "[`branch` processor](/docs/components/processors/branch)" + ` is used in order to insert the resulting array into the original message at the path ` + "`fo...
//------------------------------------------------------------------------------ // SQL is a processor that executes an SQL query for each message. type SQL struct { log log.Modular stats metrics.Type conf SQLConfig db *sql.DB dbMux sync.RWMutex args []*field.Expression argsMap...
{ _, exists := map[string]struct{}{ "clickhouse": {}, }[driver] return exists }
identifier_body
sql.go
for columns of footable that share a ` + "`user_id`" + ` with the message ` + "`user.id`" + `. The ` + "`result_codec`" + ` is set to ` + "`json_array`" + ` and a ` + "[`branch` processor](/docs/components/processors/branch)" + ` is used in order to insert the resulting array into the original message at the path ` + ...
} //------------------------------------------------------------------------------ // SQLConfig contains configuration fields for the SQL processor. type SQLConfig struct { Driver string `json:"driver" yaml:"driver"` DataSourceName string `json:"data_source_name" yaml:"data_source_name"` DSN ...
columns value in the row.`, }
random_line_split
test_transformer.py
self.make_std_mask(self.trg, pad) self.ntokens = (self.trg_y != pad).data.sum() @staticmethod def make_std_mask(tgt, pad): "Create a mask to hide padding and future words." tgt_mask = (tgt != pad).unsqueeze(-2) tgt_mask = tgt_mask & Variable( ...
def greedy_decode(model, src, src_mask, max_len, start_symbol): memory = model.encode(src, src_mask) ys = torch.ones(1, 1).fill_(start_symbol).type_as(src.data) for i in range(max_len-1): out = model.decode(memory, src_mask, Variable(ys), Vari...
"Mask out subsequent positions." attn_shape = (1, size, size) subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8') return torch.from_numpy(subsequent_mask) == 0
identifier_body
test_transformer.py
self.make_std_mask(self.trg, pad) self.ntokens = (self.trg_y != pad).data.sum() @staticmethod def make_std_mask(tgt, pad): "Create a mask to hide padding and future words." tgt_mask = (tgt != pad).unsqueeze(-2) tgt_mask = tgt_mask & Variable( ...
return ys def visualise_attention(tgt_sent, sent): def draw(data, x, y, ax): seaborn.heatmap(data, xticklabels=x, square=True, yticklabels=y, vmin=0.0, vmax=1.0, cbar=False, ax=ax) # bottom, top = ax.get_ylim() # ax.set_ylim(bottom + 0.5, top - ...
out = model.decode(memory, src_mask, Variable(ys), Variable(subsequent_mask(ys.size(1)) .type_as(src.data))) prob = model.generator(out[:, -1]) # vals, idxs = torch.topk(torch.softmax(prob, dim=1).flatten(), 10, ...
conditional_block
test_transformer.py
(self, src, trg=None, pad=0): self.src = src self.src_mask = (src != pad).unsqueeze(-2) if trg is not None: self.trg = trg[:, :-1] self.trg_y = trg[:, 1:] self.trg_mask = \ self.make_std_mask(self.trg, pad) self.ntokens = (self.trg_...
__init__
identifier_name
test_transformer.py
self.make_std_mask(self.trg, pad) self.ntokens = (self.trg_y != pad).data.sum() @staticmethod def make_std_mask(tgt, pad): "Create a mask to hide padding and future words." tgt_mask = (tgt != pad).unsqueeze(-2) tgt_mask = tgt_mask & Variable( ...
"Fix order in torchtext to match ours" src, trg = batch.src.transpose(0, 1), batch.trg.transpose(0, 1) return Batch(src, trg, pad_idx) def evaluate(data_iter, model, criterion): model.eval() with torch.no_grad(): eval_loss = run_epoch((rebatch(pad_idx, b) for b in data_iter), model, ...
random_line_split
RBF_full_NEW.py
(NUM_POINTS): csv_data = read_csv_fast(os.path.dirname(os.path.realpath(__file__))+'/trajectories/right_100.csv') timestamps = csv_data[:,0] duration = timestamps[-1] - timestamps[0] interpolated_duration_list = [0] for i in range(NUM_POINTS-2): interpolated_duration_list.append(np.nan) ...
interpolate_timestamps
identifier_name
RBF_full_NEW.py
def learn_weights(norm_data, PSIs_matrix, LAMBDA_COEFF=1e-12): """ :param norm_data: predifined trajectories -> data to learn weights :param PSIs_matrix: matrix of basis kernel functions (taken from compute_feature_matrix) :return: learned weights """ # Find out the number of basis functions ...
""" Computes phase from given timestamps. Phase is normalized time from 0 to 1. """ phases = (half_timestamp - full_timestamps[0]) / (full_timestamps[-1] - full_timestamps[0]) return phases
identifier_body
RBF_full_NEW.py
interpolated_duration_list.append(duration) series = pd.Series(interpolated_duration_list) result = series.interpolate() return np.array(result) def normalize_time(full_timestamps, half_timestamp): """ Computes phase from given timestamps. Phase is normalized time from 0 to 1. """ pha...
interpolated_duration_list.append(np.nan)
conditional_block
RBF_full_NEW.py
(norm_data, PSIs_matrix, LAMBDA_COEFF=1e-12): """ :param norm_data: predifined trajectories -> data to learn weights :param PSIs_matrix: matrix of basis kernel functions (taken from compute_feature_matrix) :return: learned weights """ # Find out the number of basis functions N = PSIs_matrix....
combined_cov_right_xy = [weights_cov_right_x, weights_cov_right_y] ###### bound calculation for mean ###### traj_cov_x_diag = np.sum(psi.dot(weights_cov_right_x) * psi, axis=1) std_x = np.sqrt(traj_cov_x_diag) bound_upp_x = reconstr_traj_mean_right_x + 2 * std_x bound_bottom_x = reconstr_traj_mean_right_x - 2 * std_x...
reconstr_traj_mean_right_x, reconstr_traj_mean_right_y = np.dot(psi, x_weights_right[:,None]).reshape([time_steps]), np.dot(psi, y_weights_right[:,None]).reshape([time_steps]) ###### Calculate COVARIANCE of weights ###### weights_cov_right_x = np.cov(weights_right[:,0].T) # shape (6, 6) weights_cov_right_y = np.cov(w...
random_line_split
validation.go
:generate mockgen -destination=mocks/mockValidation.go -package=mocks github.com/openshift/managed-upgrade-operator/pkg/validation Validator type Validator interface { IsValidUpgradeConfig(uC *upgradev1alpha1.UpgradeConfig, cV *configv1.ClusterVersion, logger logr.Logger) (ValidatorResult, error) } type validator str...
if !found { logger.Info(fmt.Sprintf("Failed to find the desired version %s in channel %s", desiredVersion, desiredChannel)) return ValidatorResult{ IsValid: false, IsAvailableUpdate: false, Message: fmt.Sprintf("cannot find version %s in available updates", desiredVersion), ...
{ if v.Version == dv && !v.Force { found = true } }
conditional_block
validation.go
go:generate mockgen -destination=mocks/mockValidation.go -package=mocks github.com/openshift/managed-upgrade-operator/pkg/validation Validator type Validator interface { IsValidUpgradeConfig(uC *upgradev1alpha1.UpgradeConfig, cV *configv1.ClusterVersion, logger logr.Logger) (ValidatorResult, error) } type validator s...
Message: "Failed to validate .spec.desired in UpgradeConfig: Either (image and version) or (version and channel) should be specified", }, nil } // Validate image spec reference // Sample image spec: "quay.io/openshift-release-dev/ocp-release@sha256:8c3f5392ac933cd520b4dce560e007f2472d2d943de14c29cbbb...
{ // Validate upgradeAt as RFC3339 upgradeAt := uC.Spec.UpgradeAt _, err := time.Parse(time.RFC3339, upgradeAt) if err != nil { return ValidatorResult{ IsValid: false, IsAvailableUpdate: false, Message: fmt.Sprintf("Failed to parse upgradeAt:%s during validation", upgradeAt), }, ni...
identifier_body
validation.go
", upgradeAt), }, nil } // Initial validation considering the usage for three optional fields for image, version and channel. // If the UpgradeConfig doesn't support image or version based upgrade then fail validation. // TODO: Remove (image and version) message once OSD-7609 is done. if !supportsImageUpgrade(u...
supportsVersionUpgrade
identifier_name
validation.go
go:generate mockgen -destination=mocks/mockValidation.go -package=mocks github.com/openshift/managed-upgrade-operator/pkg/validation Validator type Validator interface { IsValidUpgradeConfig(uC *upgradev1alpha1.UpgradeConfig, cV *configv1.ClusterVersion, logger logr.Logger) (ValidatorResult, error) } type validator s...
if len(ref.ID) == 0 { return ValidatorResult{ IsValid: false, IsAvailableUpdate: false, Message: fmt.Sprintf("Failed to parse image:%s must be a valid image pull spec: no image digest specified", image), }, nil } } // Validate desired version. dv := uC.Spec.Desired.Version ...
random_line_split
ecc.py
odd s (i.e. # reduce all the powers of 2 from p-1) # s = p - 1 e = 0 while s % 2 == 0: s //= 2 e += 1 # Find some 'n' with a legendre symbol n|p = -1. # Shouldn't take long. # n = 2 while legendre_symbol(n, p) != -1: n += 1 # Here be dragons! # ...
(a, p): """ Compute the Legendre symbol a|p using Euler's criterion. p is a prime, a is relatively prime to p (if p divides a, then a|p = 0) Returns 1 if a has a square root modulo p, -1 otherwise. """ ls = pow(a, (p - 1) // 2, p) return -1 if ls == p - 1 else ls class MySigningKe...
legendre_symbol
identifier_name
ecc.py
odd s (i.e. # reduce all the powers of 2 from p-1) # s = p - 1 e = 0 while s % 2 == 0: s //= 2 e += 1 # Find some 'n' with a legendre symbol n|p = -1. # Shouldn't take long. # n = 2 while legendre_symbol(n, p) != -1: n += 1 # Here be dragons! # ...
def append_PKCS7_padding(data: bytes) -> bytes: padlen = 16 - (len(data) % 16) return data + bytes([padlen]) * padlen def strip_PKCS7_padding(data: bytes) -> bytes: if len(data) % 16 != 0 or len(data) == 0: raise InvalidPadding("invalid length") padlen = data[-1] if padlen > 16: ...
return "Incorrect password"
identifier_body
ecc.py
odd s (i.e. # reduce all the powers of 2 from p-1) # s = p - 1 e = 0 while s % 2 == 0: s //= 2 e += 1 # Find some 'n' with a legendre symbol n|p = -1. # Shouldn't take long. # n = 2 while legendre_symbol(n, p) != -1: n += 1 # Here be dragons! # ...
ecdsa.ecdsa.generator_secp256k1 * secret) self.privkey = ecdsa.ecdsa.Private_key(self.pubkey, secret) self.secret = secret def get_public_key(self, compressed: bool) -> bytes: if compressed: if self.pubkey.point.y() & 1: key = '03' + '%064x' % self.pu...
self.pubkey = ecdsa.ecdsa.Public_key( ecdsa.ecdsa.generator_secp256k1,
random_line_split
ecc.py
odd s (i.e. # reduce all the powers of 2 from p-1) # s = p - 1 e = 0 while s % 2 == 0: s //= 2 e += 1 # Find some 'n' with a legendre symbol n|p = -1. # Shouldn't take long. # n = 2 while legendre_symbol(n, p) != -1: n += 1 # Here be dragons! # ...
else: raise Exception("error: cannot sign message") def verify_message(self, sig, message: bytes): h = sha256d(msg_magic(message)) public_key, compressed = pubkey_from_signature(sig, h) # check public key if point_to_ser(public_key.pubkey.point, compressed) != p...
sig = bytes([27 + i + (4 if is_compressed else 0)]) + signature try: self.verify_message(sig, message) return sig except Exception as e: continue
conditional_block
model_param_old.py
ripl.assume('total_birds', self.total_birds) ripl.assume('cells', self.cells) #ripl.assume('num_features', num_features) # we want to infer the hyperparameters of a log-linear model if not self.learnHypers: for k, b in enumerate(self.hypers): ripl.assume('hypers%d' % k, b) else: ...
for j in range(self.cells)[:cell_limit]: ground = self.ground[(0,d,i,j)] current = self.ripl.sample('(get_birds_moving 0 %d %d %d)'%(d,i,j))
random_line_split
model_param_old.py
ripl.assume('phi', """ (mem (lambda (y d i j) (let ((fs (lookup features (array y d i j)))) (exp %s))))""" % fold('+', '(* hypers_k_ (lookup fs _k_))', '_k_', num_features)) ripl.assume('get_bird_move_dist', '(mem (lambda (y d i) ' + fold('simplex', '(phi y d i j)', 'j...
else: for k, prior in enumerate(self.hypers): ripl.assume('hypers%d' % k,'(scope_include (quote hypers) 0 %s )'%prior) #ripl.assume('hypers%d' % k,'(scope_include (quote hypers) %d %s )'%(k,prior) ) # the features will all be observed #ripl.assume('features', '(mem (lambda (y d i j ...
for k, b in enumerate(self.hypers): ripl.assume('hypers%d' % k, b)
conditional_block
model_param_old.py
ripl.assume('phi', """ (mem (lambda (y d i j) (let ((fs (lookup features (array y d i j)))) (exp %s))))""" % fold('+', '(* hypers_k_ (lookup fs _k_))', '_k_', num_features)) ripl.assume('get_bird_move_dist', '(mem (lambda (y d i) ' + fold('simplex', '(phi y d i j)', 'j...
(self, ripl = None): if ripl is None: ripl = self.ripl observations_file = "data/input/dataset%d/%s-observations.csv" % (1, self.name) observations = readObservations(observations_file) self.unconstrained = [] for y in self.years: for (d, ns) in observations[y]: if d not in ...
loadObserves
identifier_name
model_param_old.py
ripl.assume('cell2P', '(lambda (cell) (make_pair (cell2X cell) (cell2Y cell)))') ripl.assume('XY2cell', '(lambda (x y) (+ (* height x) y))') ripl.assume('square', '(lambda (x) (* x x))') ripl.assume('dist2', """ (lambda (x1 y1 x2 y2) (+ (square (- x1 x2)) (square (- y1 y2))))""") ripl.a...
infer_bird_moves = self.getBirdMoves() score = 0 for key in infer_bird_moves: score += (infer_bird_moves[key] - self.ground[key]) ** 2 return score
identifier_body
score_codons.py
) # if float(weight) > self.max: # self.max = float(weight) # self.optimal = codon self.codons.append(codon) self.weight_list.append(weight) def
(self): """ """ num_codons = len(self.codons) r = float(random.randrange(0,10000, 1)) # r = float(random.randrange(0,num_codons*100, 1)) # print (self.aa) # print(r) r = np.divide(r, 10000) # r = np.divide(r, 100) # print(" of max ".join([str(r), s...
random_codon
identifier_name
score_codons.py
(weight) # if float(weight) > self.max: # self.max = float(weight) # self.optimal = codon self.codons.append(codon) self.weight_list.append(weight) def random_codon(self): """ """ num_codons = len(self.codons) r = float(random.randrange(0,10000...
'CAU':'H','CAC':'H', 'CAA':'Q','CAG':'Q', 'AAU':'N','AAC':'N', 'AAA':'K','AAG':'K', 'GAU':'D','GAC':'D', 'GAA':'E','GAG':'E', 'UGU':'C','UGC':'C', 'UGA':'X', 'UGG':'W', 'CGU':'R','CGC':'R','CGA':'R','CGG':'R', 'AGU':'S','AGC':'S', ...
""" """ def __init__(self): """Return a Expression_obj whose name is *gene_id*""" # self.organism = [] self.weighting_dict = defaultdict(list) # self.codon_obj_dict = {} self.codon_dict = { 'UUU':'F','UUC':'F', 'UUA':'L','UUG':'L','CUU':'L','CUC':'L','CUA...
identifier_body
score_codons.py
(weight) # if float(weight) > self.max: # self.max = float(weight) # self.optimal = codon self.codons.append(codon) self.weight_list.append(weight) def random_codon(self): """ """ num_codons = len(self.codons) r = float(random.randrange(0,10000...
total_score = float(0) total_max = float(0) for codon in codons: aa = table_obj.codon_dict[codon] score = table_obj.weighting_dict[aa][0].weightings_adj[codon] # score = score - table_obj.weighting_dict[aa][0].weight_list_adj[0] max = table_obj.weighting_dict[aa][0].max ...
return(new_seq) def score_seq(seq, table_obj): codons = [seq[i:i+3] for i in range(0, len(seq), 3)]
random_line_split
score_codons.py
S','UCA':'S','UCG':'S', 'CCU':'P','CCC':'P','CCA':'P','CCG':'P', 'ACU':'T','ACC':'T','ACA':'T','ACG':'T', 'GCU':'A','GCC':'A','GCA':'A','GCG':'A', 'UAU':'Y','UAC':'Y', 'UAA':'X','UAG':'X', 'CAU':'H','CAC':'H', 'CAA':'Q','CAG':'Q', 'AAU':'N','AAC':'N', ...
new_cds = optimise_rand(prot) seq_score, max = score_seq(new_cds, vd_table_obj) # print seq_score cds_list.append(new_cds) score_list.append(str(round(seq_score, 2))) f.write(">cds_" + str(i) + "_" + str(seq_score)) f.write(new_cds)
conditional_block
easyPresentation.py
os import sys import getopt import codecs import shutil import markdown import tempfile from subprocess import Popen, PIPE def main(argv): template_id = 1 custom_markdown_args = "" path = "output" + os.path.sep input_file_name = "" input_textfile_path = "" out_file_name = "easyPresentation.ht...
elif opt in ('-t',"--template"): template_id = arg elif opt in ('-f',"--filename"): out_file_name = arg else: print ('unhandled option %s',opt) # checking if non optional arguments are passed. if input_file_name == "": print ('No input text f...
path = arg # reqChangePath(arg)
conditional_block
easyPresentation.py
-t',"--template"): template_id = arg elif opt in ('-f',"--filename"): out_file_name = arg else: print ('unhandled option %s',opt) # checking if non optional arguments are passed. if input_file_name == "": print ('No input text file given in arguments,...
preDefCSS = {} preDefCSS["bgimage"] = "background-image" preDefCSS["bgcolor"] = "background-color" preDefCSS["bgimage-repeat"] = "background-repeat" preDefCSS["text-color"] = "color" preDefCSS["font"] = "font" preDefCSS["font-size"] = "font-size" preDefCSS["bgimage-size"] = "backgroun...
identifier_body
easyPresentation.py
perticular string should be present in template and this is where all the generated div blocks need to be placed htmlDataPart1, htmlDataPart2 = htmlContent.split('--slide content--', 1) index = htmlDataPart1.find("</head>") if index == -1: index = htmlDataPart1.find("<body") htmlDataPart1 = ht...
print(" Error while running markdown script : ") print(err) sys.exit(1)
random_line_split
easyPresentation.py
os import sys import getopt import codecs import shutil import markdown import tempfile from subprocess import Popen, PIPE def main(argv): template_id = 1 custom_markdown_args = "" path = "output" + os.path.sep input_file_name = "" input_textfile_path = "" out_file_name = "easyPresentation.ht...
(path): # (kp) this check is wrong. hidden files on unix filesystems start with '.' so startswith('.') is not a good check for current directory # (kp) this is actually the same bug that Ken Thompson had in the original unix impl of the filesystem which lead to dotfiles being hidden in the first place if pa...
reqChangePath
identifier_name
osutil.py
class SSLError(SocketError): """ SSL error """ def raise_socket_error(timeout=None): """ Convert a socket error into an appropriate module exception This function needs an already raised ``socket.error``. ``raise_socket_error.EAIS`` is a mapping from GAI error numbers to their names (``{in...
""" Timeout error """
identifier_body
osutil.py
socket.timeout`` - `AddressError`: address/host resolution error (``socket.gaierror/herror``) - `SSLError`: ``socket.sslerror`` - `SocketError`: other socket errors, ``IOError`` - `Exception`: unrecognized exceptions """ try: raise except _socket.timeout: if timeo...
_lock.acquire() try: if spec not in _cache: _cache[spec] = ( adi, _datetime.datetime.utcnow() + _datetime.timedelta(seconds=cache), ) ...
conditional_block
osutil.py
:Parameters: - `timeout`: applied timeout in seconds, used for the TimeoutError description :Types: - `timeout`: ``float`` :Exceptions: - `TimeoutError`: ``socket.timeout`` - `AddressError`: address/host resolution error (``socket.gaierror/herror``) - `SSLError`: ``s...
finally: for dfd in toclose: try: _os.close(dfd) except OSError: pass return fd def close_descriptors(*keep): """ Close all file descriptors >= 3 """ keep = set(keep) try: flag = _resource.RLIMIT_NOFILE except AttributeErr...
try: while fd < 3: toclose.append(fd) fd = _os.dup(fd)
random_line_split
osutil.py
(Error): """ The attempt to change identity caused a hard error """ class SocketError(Error): """ Socket error """ class AddressError(SocketError): """ Address resolution error """ class TimeoutError(SocketError): """ Timeout error """ class SSLError(SocketError): """ SSL error """ def raise_...
IdentityError
identifier_name
sshCopy.py
if('non-zero' in str(e)): pass # print ('timedout') else: print (e) # print ("offline / didnt work") return False def workon(host,localDir, indexStart): if ping(host): # print (host) ssh = paramiko.SSHClient() # print ('client created' + str(host)) ssh.set_missing_host_key_policy(parami...
self.collectedDataType = "ref" return True #indentations elif 'i' == checkData or 'in' == checkData or 'ind' in checkData: self.collectedDataType = "indentation" if(0 < len(splitInput)): if splitInput[0].isdigit(): self.collectedDataType += '-' + splitInput[0] return True elif 'test' == ...
elif 'r' == checkData or 're' in checkData:
random_line_split
sshCopy.py
if('non-zero' in str(e)): pass # print ('timedout') else: print (e) # print ("offline / didnt work") return False def workon(host,localDir, indexStart): if ping(host): # print (host) ssh = paramiko.SSHClient() # print ('client created' + str(host)) ssh.set_missing_host_key_policy(paramik...
(self): folder = list(os.scandir(self.homeDir)) # check for most recent folder name # if the most recent folder is a calibration folder then ignore it. if( 0 < len(folder)): sortedFolders = sorted(folder, key = lambda x: x.stat().st_mtime, reverse = True) #sort the folders by time they were modified ...
getLastFolder
identifier_name
sshCopy.py
if('non-zero' in str(e)): pass # print ('timedout') else: print (e) # print ("offline / didnt work") return False def workon(host,localDir, indexStart): if ping(host): # print (host) ssh = paramiko.SSHClient() # print ('client created' + str(host)) ssh.set_missing_host_key_policy(paramik...
def getDate(self): date = str(datetime.date.today()) # date = date.replace("-", "_") return date #check scanfolder directory for the most recent folder def getLastFolder(self): folder = list(os.scandir(self.homeDir)) # check for most recent folder name # if the most recent folder is a calibratio...
def __init__(self): self.subjectIdentifier = None self.increment = None self.homeDir = self.getDirectory() self.lastFolder = self.getLastFolder() self.date = self.getDate() self.newFolderName = "" self.useOldFolder = False # check the home directory # setup scanFolder in the documents folder if it do...
identifier_body
sshCopy.py
if('non-zero' in str(e)): pass # print ('timedout') else: print (e) # print ("offline / didnt work") return False def workon(host,localDir, indexStart): if ping(host): # print (host) ssh = paramiko.SSHClient() # print ('client created' + str(host)) ssh.set_missing_host_key_policy(paramik...
#swelling: cast or socket or just swelling elif 's' == checkData or'sw' in checkData: self.collectedDataType = "swelling" if(0 < len(splitInput)): if 'c' == splitInput[0] or 'cast' == splitInput[0]: self.collectedDataType +="Cast" elif 's' == splitInput[0] or 'so' in splitInput[0]: self...
self.collectedDataType = "muscleContractions" return True
conditional_block
DynamicInput.js
'& span': { fontSize: 13, }, }, '&[data-focus=false]:hover': { border: `1px solid`, }, '&[data-focus=true]': { border: `1px solid ${theme.palette.primary.main}`, boxShadow: `inset 0px 0px 0px 1px ${theme.palette.primary.main}`, }, '&[data-blur=true]': { ...
} } if (uiEnable && uiEnable.length && javaScriptUiEnable) { if (javaScriptUiEnable.indexOf('return') !== -1) { if (field.uiEnable[0][1] !== '' && relatedDropDownValue) { try { const execute = new Function('relatedDropDownValue', `${javaScriptUiEnable}`); ...
{ try { const execute = new Function('formData', `${javaScriptUiVisible}`); setUiVisibled(execute(clone(formData))); } catch (error) { console.log('javaScriptUiVisible error on %s', field.name, error); } }
conditional_block
DynamicInput.js
s', field.name, error); } } } } if (uiEnable && uiEnable.length && javaScriptUiEnable) { if (javaScriptUiEnable.indexOf('return') !== -1) { if (field.uiEnable[0][1] !== '' && relatedDropDownValue) { try { const execute = new Function('relatedDropDownV...
extraProps.dropdownState = getDropDownListFromState(field, 'uiEnable', state, metaData); } return extraProps; };
random_line_split
client.rs
AsyncContext, Context, Handler, StreamHandler, }; use actix_codec::{AsyncRead, AsyncWrite, Framed}; use futures::{ lazy, /* future::ok, */ stream::{SplitSink, Stream}, Future,
// str::FromStr, // time::Duration, sync::Arc, thread, // net, process, thread, }; // use tokio_io::{AsyncRead, io::WriteHalf}; // use tokio_tcp::TcpStream; use awc::{ error::WsProtocolError, http::StatusCode, ws::{Codec, Frame, Message}, Client, Connector, }; use rustls::ClientConfi...
}; use std::{ io,
random_line_split
client.rs
AsyncContext, Context, Handler, StreamHandler, }; use actix_codec::{AsyncRead, AsyncWrite, Framed}; use futures::{ lazy, /* future::ok, */ stream::{SplitSink, Stream}, Future, }; use std::{ io, // str::FromStr, // time::Duration, sync::Arc, thread, // net, process, thre...
<T>(SinkWrite<SplitSink<Framed<T, Codec>>>) where T: AsyncRead + AsyncWrite; #[derive(Message)] struct ClientCommand(String); impl<T: 'static> Actor for WsClient<T> where T: AsyncRead + AsyncWrite, { type Context = Context<Self>; fn started(&mut self, ctx: &mut Context<Self>) { // start heart...
WsClient
identifier_name