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.rs
use maplit::btreeset; use reduce::Reduce; use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwned}; use std::{ collections::{BTreeMap, BTreeSet}, ops::{BitAnd, BitOr}, }; /// a compact index #[derive(Debug, Clone, PartialEq, Eq)] pub struct Index { /// the strings table strin...
} fn main() { let strings = (0..5000).map(|i| { let fizz = i % 3 == 0; let buzz = i % 5 == 0; if fizz && buzz { btreeset!{"fizzbuzz".to_owned(), "com.somecompany.somenamespace.someapp.sometype".to_owned()} } else if fizz { btreeset!{"fizz".to_owned(), "org.sc...
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
use maplit::btreeset; use reduce::Reduce; use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwned}; use std::{ collections::{BTreeMap, BTreeSet}, ops::{BitAnd, BitOr}, }; /// a compact index #[derive(Debug, Clone, PartialEq, Eq)] pub struct Index { /// the strings table strin...
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
use maplit::btreeset; use reduce::Reduce; use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwned}; use std::{ collections::{BTreeMap, BTreeSet}, ops::{BitAnd, BitOr}, }; /// a compact index #[derive(Debug, Clone, PartialEq, Eq)] pub struct Index { /// the strings table strin...
(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
use maplit::btreeset; use reduce::Reduce; use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwned}; use std::{ collections::{BTreeMap, BTreeSet}, ops::{BitAnd, BitOr}, }; /// a compact index #[derive(Debug, Clone, PartialEq, Eq)] pub struct Index { /// the strings table strin...
} } 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
macro_rules! xterm_colors { ($( $xterm_num:literal $name:ident ($r:literal, $g:literal, $b:literal) )*) => { pub(crate) mod dynamic { use core::fmt; #[allow(unused_imports)] use crate::OwoColorize; /// Available Xterm colors for use with [`OwoCo...
fn from(color: XtermColors) -> Self { match color { $( XtermColors::$name => $xterm_num, )* } } } } $( #[allow(missing_docs)] ...
impl From<XtermColors> for u8 {
random_line_split
gtmaps.py
import numpy as np import math import sys import glob import os import json import random import copy from skimage.measure import regionprops, label def get_file(rn = 302, task_index = 1, trial_num = 0): folders = sorted(glob.glob('/home/hom/alfred/data/json_2.1.0/train/*'+repr(rn))) #for home com...
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.copy(R) init_shape = copy.copy(mat.shape) p = copy.copy(position) ...
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
import numpy as np import math import sys import glob import os import json import random import copy from skimage.measure import regionprops, label def get_file(rn = 302, task_index = 1, trial_num = 0): folders = sorted(glob.glob('/home/hom/alfred/data/json_2.1.0/train/*'+repr(rn))) #for home com...
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
import numpy as np import math import sys import glob import os import json import random import copy from skimage.measure import regionprops, label def get_file(rn = 302, task_index = 1, trial_num = 0): folders = sorted(glob.glob('/home/hom/alfred/data/json_2.1.0/train/*'+repr(rn))) #for home com...
else: prettyprint(o_grids[obj+'|']) save = input("Save data ? (y/n)") if save=='y': np.save(fname,o_grids) #overwrites the existing one
prettyprint(o_grids[obj])
conditional_block
gtmaps.py
import numpy as np import math import sys import glob import os import json import random import copy from skimage.measure import regionprops, label def get_file(rn = 302, task_index = 1, trial_num = 0): folders = sorted(glob.glob('/home/hom/alfred/data/json_2.1.0/train/*'+repr(rn))) #for home com...
(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
from __future__ import print_function import csv import os from sys import maxsize import pickle import tensorflow as tf import numpy as np import spacy import constants import corpus import preprocessing import sequence_node_sequence_pb2 import tools import random from multiprocessing import Pool import fnmatch imp...
if __name__ == '__main__': sentence_processor = getattr(preprocessing, FLAGS.sentence_processor) out_dir = os.path.abspath(os.path.join(FLAGS.corpus_data_output_dir, sentence_processor.func_name)) if not os.path.isdir(out_dir): os.makedirs(out_dir) out_path = os.path.join(out_dir, FLAGS.corp...
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
from __future__ import print_function import csv import os from sys import maxsize import pickle import tensorflow as tf import numpy as np import spacy import constants import corpus import preprocessing import sequence_node_sequence_pb2 import tools import random from multiprocessing import Pool import fnmatch imp...
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
from __future__ import print_function import csv import os from sys import maxsize import pickle import tensorflow as tf import numpy as np import spacy import constants import corpus import preprocessing import sequence_node_sequence_pb2 import tools import random from multiprocessing import Pool import fnmatch imp...
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
from __future__ import print_function import csv import os from sys import maxsize import pickle import tensorflow as tf import numpy as np import spacy import constants import corpus import preprocessing import sequence_node_sequence_pb2 import tools import random from multiprocessing import Pool import fnmatch imp...
(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
package diskrsync import ( "bufio" "bytes" "encoding/binary" "errors" "fmt" "hash" "io" "log" "math" "github.com/dop251/spgz" "golang.org/x/crypto/blake2b" ) const ( hdrMagic = "BSNC0002" ) const ( hashSize = 64 DefTargetBlockSize = 128 * 1024 ) const ( cmdHole byte = iota cmdBlock cmdEqual cmdN...
() 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
package diskrsync import ( "bufio" "bytes" "encoding/binary" "errors" "fmt" "hash" "io" "log" "math" "github.com/dop251/spgz" "golang.org/x/crypto/blake2b" ) const ( hdrMagic = "BSNC0002" ) const ( hashSize = 64 DefTargetBlockSize = 128 * 1024 ) const ( cmdHole byte = iota cmdBlock cmdEqual cmdN...
} 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
package diskrsync import ( "bufio" "bytes" "encoding/binary" "errors" "fmt" "hash" "io" "log" "math" "github.com/dop251/spgz" "golang.org/x/crypto/blake2b" ) const ( hdrMagic = "BSNC0002" ) const ( hashSize = 64 DefTargetBlockSize = 128 * 1024 ) const ( cmdHole byte = iota cmdBlock cmdEqual cmdN...
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) if l > 0 { l-- h = (*p)[l] (*p)[l] = nil *p = (*p)[:l] h.Reset() } else { h, _ = blake2b.New51...
{ 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
package diskrsync import ( "bufio" "bytes" "encoding/binary" "errors" "fmt" "hash" "io" "log" "math" "github.com/dop251/spgz" "golang.org/x/crypto/blake2b" ) const ( hdrMagic = "BSNC0002" ) const ( hashSize = 64 DefTargetBlockSize = 128 * 1024 ) const ( cmdHole byte = iota cmdBlock cmdEqual cmdN...
} } } 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
""" This module handles user input. To handle user input you will likely want to use the L{event.get} function or create a subclass of L{event.App}. - L{event.get} iterates over recent events. - L{event.App} passes events to the overridable methods: ev_* and key_*. But there are other option...
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
""" This module handles user input. To handle user input you will likely want to use the L{event.get} function or create a subclass of L{event.App}. - L{event.get} iterates over recent events. - L{event.App} passes events to the overridable methods: ev_* and key_*. But there are other option...
'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
""" This module handles user input. To handle user input you will likely want to use the L{event.get} function or create a subclass of L{event.App}. - L{event.get} iterates over recent events. - L{event.App} passes events to the overridable methods: ev_* and key_*. But there are other option...
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
""" This module handles user input. To handle user input you will likely want to use the L{event.get} function or create a subclass of L{event.App}. - L{event.get} iterates over recent events. - L{event.App} passes events to the overridable methods: ev_* and key_*. But there are other option...
(timeout=None, flush=True): """Wait for an event. @type timeout: int or None @param timeout: The time in seconds that this function will wait before giving up and returning None. With the default value of None, this will block forever. @type flush: boolean @...
wait
identifier_name
dealerDispatcherList.js
<%@ page contentType="text/html;charset=UTF-8" %> <script> $(document).ready(function() { $('#dealerTable').bootstrapTable({ //请求方法 method: 'get', //类型json dataType: "json", //显示刷新按钮 showRefresh: true, //显示切换手机试图按钮 ...
conditional_block
dealerDispatcherList.js
<%@ page contentType="text/html;charset=UTF-8" %> <script> $(document).ready(function() { $('#dealerTable').bootstrapTable({ //请求方法 method: 'get', //类型json dataType: "json", //显示刷新按钮 showRefresh: true, //显示切换手机试图按钮 ...
} ,{ field: 'legalPersonName', title: '法人姓名', sortable: true } ,{ field: 'legalPersonIdCard', title: '法人身份号', sort...
sortable: true
random_line_split
entities.py
""" Created on Dec 7, 2014 @author: bbuxton """ import random import sys import pygame import math from collections.abc import Callable, Iterator from typing import Generator, Iterable, Optional, Generic, Tuple, TypeVar, Type, cast import zombiesim.util as zutil from zombiesim.type_def import Bounds, Direction, Food,...
(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
""" Created on Dec 7, 2014 @author: bbuxton """ import random import sys import pygame import math from collections.abc import Callable, Iterator from typing import Generator, Iterable, Optional, Generic, Tuple, TypeVar, Type, cast import zombiesim.util as zutil from zombiesim.type_def import Bounds, Direction, Food,...
return goto class Consumable(Entity): def __init__(self, color: pygame.Color, amount: int = 5): super().__init__(color) self.amount: int = amount def draw_image(self, color: pygame.Color) -> None: pygame.draw.rect(self.image, color, self.image.get_rect()) def consume(sel...
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
""" Created on Dec 7, 2014 @author: bbuxton """ import random import sys import pygame import math from collections.abc import Callable, Iterator from typing import Generator, Iterable, Optional, Generic, Tuple, TypeVar, Type, cast import zombiesim.util as zutil from zombiesim.type_def import Bounds, Direction, Food,...
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
""" Created on Dec 7, 2014 @author: bbuxton """ import random import sys import pygame import math from collections.abc import Callable, Iterator from typing import Generator, Iterable, Optional, Generic, Tuple, TypeVar, Type, cast import zombiesim.util as zutil from zombiesim.type_def import Bounds, Direction, Food,...
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
from struct import unpack_from from dbparse import parseReplay from collections import Counter, deque import numpy as np import math import json import urllib.request import sys import os from copy import deepcopy # constants HITMAP_RESOLUTION = 64 HITMAP_SIZE = 128 TIMING_RESOLUTION = 64 class ModeError(Exception)...
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
from struct import unpack_from from dbparse import parseReplay from collections import Counter, deque import numpy as np import math import json import urllib.request import sys import os from copy import deepcopy # constants HITMAP_RESOLUTION = 64 HITMAP_SIZE = 128 TIMING_RESOLUTION = 64 class ModeError(Exception)...
# attempt to locate beatmap file in /data bm_hash = replay['beatmap_md5'] bm_path = 'data/' + bm_hash + '.osu' bm_file = None bm_tuple = get_beatmap_id(bm_hash) if bm_tuple == None: print(json.dumps({'error': 'Could not access the osu! api at this time. Please try again in a bit.'})) ...
print(json.dumps({'error': 'Unsupported game mode.'})) sys.exit(0)
conditional_block
parser.py
from struct import unpack_from from dbparse import parseReplay from collections import Counter, deque import numpy as np import math import json import urllib.request import sys import os from copy import deepcopy # constants HITMAP_RESOLUTION = 64 HITMAP_SIZE = 128 TIMING_RESOLUTION = 64 class ModeError(Exception)...
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
from struct import unpack_from from dbparse import parseReplay from collections import Counter, deque import numpy as np import math import json import urllib.request import sys import os from copy import deepcopy # constants HITMAP_RESOLUTION = 64 HITMAP_SIZE = 128 TIMING_RESOLUTION = 64 class ModeError(Exception)...
(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
const english = document.querySelector('.eng') const polish = document.querySelector('.pl') polish.addEventListener('click', function () { document.querySelector('.hey').textContent = "Witaj! Nazywam się Piotr Ludew" document.querySelector('.front').textContent = "i chcę pracować jako Front-End Developer" ...
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
use std::marker::PhantomData; use std::rc::Rc; use itertools::Itertools; use std::collections::{HashMap, HashSet}; use ::serial::SerialGen; use ::traits::ReteIntrospection; use ::builder::{AlphaTest, ConditionInfo, KnowledgeBuilder}; use ::network::ids::*; use ::builders::ids::{StatementId, RuleId}; use runtime::memory...
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
use std::marker::PhantomData; use std::rc::Rc; use itertools::Itertools; use std::collections::{HashMap, HashSet}; use ::serial::SerialGen; use ::traits::ReteIntrospection; use ::builder::{AlphaTest, ConditionInfo, KnowledgeBuilder}; use ::network::ids::*; use ::builders::ids::{StatementId, RuleId}; use runtime::memory...
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
use std::marker::PhantomData; use std::rc::Rc; use itertools::Itertools; use std::collections::{HashMap, HashSet}; use ::serial::SerialGen; use ::traits::ReteIntrospection; use ::builder::{AlphaTest, ConditionInfo, KnowledgeBuilder}; use ::network::ids::*; use ::builders::ids::{StatementId, RuleId}; use runtime::memory...
<I: Into<MemoryId> + AlphaMemoryId>(&mut self, id: I, val: Rc<T>) { let mem_id = id.into(); self.mem.entry(mem_id) .or_insert_with(Default::default) .insert(val); } } pub struct AlphaNetwork<T: ReteIntrospection> { hash_eq_node: HashMap<T::HashEq, HashEqNode>, alpha_...
insert
identifier_name
base.rs
use std::marker::PhantomData; use std::rc::Rc; use itertools::Itertools; use std::collections::{HashMap, HashSet}; use ::serial::SerialGen; use ::traits::ReteIntrospection; use ::builder::{AlphaTest, ConditionInfo, KnowledgeBuilder}; use ::network::ids::*; use ::builders::ids::{StatementId, RuleId}; use runtime::memory...
} pub enum BetaNodeType { And(MemoryId, MemoryId) } pub struct BetaNode { id: BetaId, b_type: BetaNodeType, destinations: Vec<DestinationNode> } pub struct BetaNetwork { b_network: Vec<BetaNode> } pub struct BetaMemory { tripwire: Vec<bool>, }
{ let rc = Rc::new(val); if !self.store.insert(rc.clone()) { self.store.get(&rc).unwrap().clone() } else { rc } }
identifier_body
lib.rs
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![cfg_attr(feature="clippy_pedantic", warn(clippy_pedantic))] // Clippy doesn't like this pattern, but I do. I may consider changing my mind // on this in the future, just to make clippy happy. #![cfg_attr(all(feature="cli...
} } impl<'a> fmt::Debug for HashlifeCache<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<Hashlife instance>") } } impl<'a> Node<'a> { pub fn to_raw(&self) -> RawNode<'a> { self.raw } pub fn hashlife_instance(&self) -> Hashlife<'a> { self.hl ...
{ self.node_block(make_2x2(|_,_| self.random_block(rng, lg_size-1))) }
conditional_block
lib.rs
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![cfg_attr(feature="clippy_pedantic", warn(clippy_pedantic))] // Clippy doesn't like this pattern, but I do. I may consider changing my mind // on this in the future, just to make clippy happy. #![cfg_attr(all(feature="cli...
/// 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
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![cfg_attr(feature="clippy_pedantic", warn(clippy_pedantic))] // Clippy doesn't like this pattern, but I do. I may consider changing my mind // on this in the future, just to make clippy happy. #![cfg_attr(all(feature="cli...
pub fn unwrap_node(self) -> Node<'a> { self.destruct().unwrap() } pub fn lg_size(&self) -> usize { self.lg_size } pub fn lg_size_verified(&self) -> Result<usize, ()> { Ok(self.lg_size()) } pub fn is_blank(&self) -> bool { self.raw.is_blank() } } impl...
{ self.destruct().unwrap_err() }
identifier_body
lib.rs
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![cfg_attr(feature="clippy_pedantic", warn(clippy_pedantic))] // Clippy doesn't like this pattern, but I do. I may consider changing my mind // on this in the future, just to make clippy happy. #![cfg_attr(all(feature="cli...
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<Hashlife instance>") } } impl<'a> Node<'a> { pub fn to_raw(&self) -> RawNode<'a> { self.raw } pub fn hashlife_instance(&self) -> Hashlife<'a> { self.hl } pub fn evolve(&self) -> Block<'a> { self.hl.bl...
fmt
identifier_name
server_cgi.go
/* * Copyright (c) 2015, Shinya Yagyu * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of condition...
//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
/* * Copyright (c) 2015, Shinya Yagyu * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of condition...
(stamp string, last int64) (int64, int64, string) { buf := strings.Split(stamp, "/") var id string if len(buf) > 1 { id = buf[1] stamp = buf[0] } buf = strings.Split(stamp, "-") nstamps := make([]int64, len(buf)) var err error for i, nstamp := range buf { if nstamp == "" { continue } nstamps[i], er...
parseStamp
identifier_name
server_cgi.go
/* * Copyright (c) 2015, Shinya Yagyu * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of condition...
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
/* * Copyright (c) 2015, Shinya Yagyu * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of condition...
* 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
import os import PIL.Image import time from Tkinter import * # =============================================Initialize Variables=============================================# size = 256, 256 # Size of thumbnail image displayed newValue = list((0, 0, 0)) convMask = 3 normalizer = 1 errorMessage = "" previewBox = 0 c...
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
import os import PIL.Image import time from Tkinter import * # =============================================Initialize Variables=============================================# size = 256, 256 # Size of thumbnail image displayed newValue = list((0, 0, 0)) convMask = 3 normalizer = 1 errorMessage = "" previewBox = 0 c...
(): # 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
import os import PIL.Image import time from Tkinter import * # =============================================Initialize Variables=============================================# size = 256, 256 # Size of thumbnail image displayed newValue = list((0, 0, 0)) convMask = 3 normalizer = 1 errorMessage = "" previewBox = 0 c...
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
import os import PIL.Image import time from Tkinter import * # =============================================Initialize Variables=============================================# size = 256, 256 # Size of thumbnail image displayed newValue = list((0, 0, 0)) convMask = 3 normalizer = 1 errorMessage = "" previewBox = 0 c...
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
/* * Copyright (c) 2019 LabKey Corporation * * 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...
} 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
/* * Copyright (c) 2019 LabKey Corporation * * 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...
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
/* * Copyright (c) 2019 LabKey Corporation * * 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...
() : 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
/* * Copyright (c) 2019 LabKey Corporation * * 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...
getGridValues(queryInfo: QueryInfo): Map<any, any> { let data = List<Map<string, any>>(); for (let i = 0; i < this.sampleCount; i++) { let values = Map<string, any>(); queryInfo .getInsertColumns() .forEach((col) => { co...
{ 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
use super::*; use crate::utils::over; pub fn init<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, ), &...
pub fn desc_sets<B: Backend>( device: &B::Device, values: Vec<(Vec<&B::Buffer>, Vec<&B::ImageView>, Vec<&B::Sampler>)>, ) -> ( B::DescriptorSetLayout, B::DescriptorPool, Vec<B::DescriptorSet>, ) { use gfx_hal::pso::*; let sets = values.len(); let ubos = values.get(0).map(|set| set.0.l...
{ 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
use super::*; use crate::utils::over; pub fn init<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, ), &...
mask: ColorMask::ALL, blend: Some(BlendState::ALPHA), }); if depth_format.is_some() { pipeline_desc.depth_stencil = DepthStencilDesc { depth: Some(DepthTest { fun: Comparison::LessEqual, write: true, }), depth_bounds: f...
}, ); pipeline_desc.blender.targets.push(ColorBlendDesc {
random_line_split
easy.rs
use super::*; use crate::utils::over; pub fn init<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, ), &...
; 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
use super::*; use crate::utils::over; pub fn
<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
package processor import ( "database/sql" "errors" "fmt" "strings" "sync" "time" "github.com/Jeffail/benthos/v3/internal/bloblang/field" "github.com/Jeffail/benthos/v3/internal/bloblang/mapping" "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/internal/interop" "github.com/Jeffa...
} } else { IteratePartsWithSpanV2(TypeSQL, nil, newMsg, func(index int, span *tracing.Span, part types.Part) error { args, err := s.getArgs(index, msg) if err != nil { s.mErr.Incr(1) s.log.Errorf("Args mapping error: %v\n", err) return err } if s.resCodec == nil { if s.dynQuery != nil...
{ s.mErr.Incr(1) s.log.Errorf("SQL error: %v\n", err) FlagErr(newMsg.Get(i), err) }
conditional_block
sql.go
package processor import ( "database/sql" "errors" "fmt" "strings" "sync" "time" "github.com/Jeffail/benthos/v3/internal/bloblang/field" "github.com/Jeffail/benthos/v3/internal/bloblang/mapping" "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/internal/interop" "github.com/Jeffa...
(index int, msg types.Message) ([]interface{}, error) { if len(s.args) > 0 { args := make([]interface{}, len(s.args)) for i, v := range s.args { args[i] = v.String(index, msg) } return args, nil } if s.argsMapping == nil { return nil, nil } pargs, err := s.argsMapping.MapPart(index, msg) if err != ...
getArgs
identifier_name
sql.go
package processor import ( "database/sql" "errors" "fmt" "strings" "sync" "time" "github.com/Jeffail/benthos/v3/internal/bloblang/field" "github.com/Jeffail/benthos/v3/internal/bloblang/mapping" "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/internal/interop" "github.com/Jeffa...
//------------------------------------------------------------------------------ // 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
package processor import ( "database/sql" "errors" "fmt" "strings" "sync" "time" "github.com/Jeffail/benthos/v3/internal/bloblang/field" "github.com/Jeffail/benthos/v3/internal/bloblang/mapping" "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/internal/interop" "github.com/Jeffa...
} //------------------------------------------------------------------------------ // 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
import sys sys.path.append("./") from torchtext.datasets import Multi30k from torchtext.data import Field from torchtext import data import pickle import models.transformer as h import torch from datasets import load_dataset from torch.utils.data import DataLoader from metrics.metrics import bleu import numpy as np fro...
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
import sys sys.path.append("./") from torchtext.datasets import Multi30k from torchtext.data import Field from torchtext import data import pickle import models.transformer as h import torch from datasets import load_dataset from torch.utils.data import DataLoader from metrics.metrics import bleu import numpy as np fro...
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
import sys sys.path.append("./") from torchtext.datasets import Multi30k from torchtext.data import Field from torchtext import data import pickle import models.transformer as h import torch from datasets import load_dataset from torch.utils.data import DataLoader from metrics.metrics import bleu import numpy as np fro...
(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
import sys sys.path.append("./") from torchtext.datasets import Multi30k from torchtext.data import Field from torchtext import data import pickle import models.transformer as h import torch from datasets import load_dataset from torch.utils.data import DataLoader from metrics.metrics import bleu import numpy as np fro...
"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
import numpy as np import matplotlib.pyplot as plt from functions import comb_dataset, read_csv_fast import os import pandas as pd def
(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
import numpy as np import matplotlib.pyplot as plt from functions import comb_dataset, read_csv_fast import os import pandas as pd def interpolate_timestamps(NUM_POINTS): csv_data = read_csv_fast(os.path.dirname(os.path.realpath(__file__))+'/trajectories/right_100.csv') timestamps = csv_data[:,0] duration ...
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
import numpy as np import matplotlib.pyplot as plt from functions import comb_dataset, read_csv_fast import os import pandas as pd def interpolate_timestamps(NUM_POINTS): csv_data = read_csv_fast(os.path.dirname(os.path.realpath(__file__))+'/trajectories/right_100.csv') timestamps = csv_data[:,0] duration ...
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
import numpy as np import matplotlib.pyplot as plt from functions import comb_dataset, read_csv_fast import os import pandas as pd def interpolate_timestamps(NUM_POINTS): csv_data = read_csv_fast(os.path.dirname(os.path.realpath(__file__))+'/trajectories/right_100.csv') timestamps = csv_data[:,0] duration ...
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
// Package validation provides UpgradeConfig CR validation tools. package validation import ( "fmt" "net/url" "strings" "time" "github.com/blang/semver" "github.com/go-logr/logr" "github.com/google/uuid" configv1 "github.com/openshift/api/config/v1" "github.com/openshift/cluster-version-operator/pkg/cincinna...
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
// Package validation provides UpgradeConfig CR validation tools. package validation import ( "fmt" "net/url" "strings" "time" "github.com/blang/semver" "github.com/go-logr/logr" "github.com/google/uuid" configv1 "github.com/openshift/api/config/v1" "github.com/openshift/cluster-version-operator/pkg/cincinna...
// compareVersions accepts desiredVersion and currentVersion strings as versions, converts // them to semver and then compares them. Returns an indication of whether the desired // version constitutes a downgrade, no-op or upgrade, or an error if no valid comparison can occur func compareVersions(dV semver.Version, c...
{ // 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
// Package validation provides UpgradeConfig CR validation tools. package validation import ( "fmt" "net/url" "strings" "time" "github.com/blang/semver" "github.com/go-logr/logr" "github.com/google/uuid" configv1 "github.com/openshift/api/config/v1" "github.com/openshift/cluster-version-operator/pkg/cincinna...
(uc *upgradev1alpha1.UpgradeConfig) bool { return empty(uc.Spec.Desired.Image) && !empty(uc.Spec.Desired.Version) && !empty(uc.Spec.Desired.Channel) } // empty function checks if a given string is empty or not. func empty(s string) bool { return strings.TrimSpace(s) == "" }
supportsVersionUpgrade
identifier_name
validation.go
// Package validation provides UpgradeConfig CR validation tools. package validation import ( "fmt" "net/url" "strings" "time" "github.com/blang/semver" "github.com/go-logr/logr" "github.com/google/uuid" configv1 "github.com/openshift/api/config/v1" "github.com/openshift/cluster-version-operator/pkg/cincinna...
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
"""This module deals with Eliptical Curve Operations: keys, signing """ import base64 import binascii import ecdsa import hashlib import hmac import pyaes from .hash import sha256d from .serialize import write_compact_size def msg_magic(message): return b"\x18Bitcoin Signed Message:\n" + write_compact_size(len(m...
(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
"""This module deals with Eliptical Curve Operations: keys, signing """ import base64 import binascii import ecdsa import hashlib import hmac import pyaes from .hash import sha256d from .serialize import write_compact_size def msg_magic(message): return b"\x18Bitcoin Signed Message:\n" + write_compact_size(len(m...
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
"""This module deals with Eliptical Curve Operations: keys, signing """ import base64 import binascii import ecdsa import hashlib import hmac import pyaes from .hash import sha256d from .serialize import write_compact_size def msg_magic(message): return b"\x18Bitcoin Signed Message:\n" + write_compact_size(len(m...
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
"""This module deals with Eliptical Curve Operations: keys, signing """ import base64 import binascii import ecdsa import hashlib import hmac import pyaes from .hash import sha256d from .serialize import write_compact_size def msg_magic(message): return b"\x18Bitcoin Signed Message:\n" + write_compact_size(len(m...
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
import venture.shortcuts as s from utils import * from venture.unit import VentureUnit from venture.ripl.ripl import _strip_types num_features = 4 def loadFeatures(dataset, name, years, days,maxDay=None): features_file = "data/input/dataset%d/%s-features.csv" % (dataset, name) print "Loading features from %s" ...
if ground>0 and current>0: self.ripl.force('(get_birds_moving 0 %d %d %d)'%(d,i,j),ground) print 'force: moving(0 %d %d %d) from %f to %f'%(d,i,j,current,ground) # try: # self.ripl.force('(get_birds_moving 0 %d %d %d)'%(d,i,j), # ...
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
import venture.shortcuts as s from utils import * from venture.unit import VentureUnit from venture.ripl.ripl import _strip_types num_features = 4 def loadFeatures(dataset, name, years, days,maxDay=None): features_file = "data/input/dataset%d/%s-features.csv" % (dataset, name) print "Loading features from %s" ...
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
import venture.shortcuts as s from utils import * from venture.unit import VentureUnit from venture.ripl.ripl import _strip_types num_features = 4 def loadFeatures(dataset, name, years, days,maxDay=None): features_file = "data/input/dataset%d/%s-features.csv" % (dataset, name) print "Loading features from %s" ...
(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
import venture.shortcuts as s from utils import * from venture.unit import VentureUnit from venture.ripl.ripl import _strip_types num_features = 4 def loadFeatures(dataset, name, years, days,maxDay=None): features_file = "data/input/dataset%d/%s-features.csv" % (dataset, name) print "Loading features from %s" ...
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
#!/usr/bin/python ''' This script generates a codon optimised protein based upon a fasta protein sequence and a table of relative codon usage. ''' from sets import Set import sys,argparse from collections import defaultdict import re import numpy as np import csv import random from Bio import SeqIO #----------------...
(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
#!/usr/bin/python ''' This script generates a codon optimised protein based upon a fasta protein sequence and a table of relative codon usage. ''' from sets import Set import sys,argparse from collections import defaultdict import re import numpy as np import csv import random from Bio import SeqIO #----------------...
def optimise_rand(prot): new_seq = '' for aa in prot: new_aa = vd_table_obj.weighting_dict[aa][0].random_codon() new_seq = new_seq + new_aa return(new_seq) def optimise_best(prot): new_seq = '' for aa in prot: # print aa # new_aa = vd_table_obj.weighting_dict[aa...
""" """ 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
#!/usr/bin/python ''' This script generates a codon optimised protein based upon a fasta protein sequence and a table of relative codon usage. ''' from sets import Set import sys,argparse from collections import defaultdict import re import numpy as np import csv import random from Bio import SeqIO #----------------...
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
#!/usr/bin/python ''' This script generates a codon optimised protein based upon a fasta protein sequence and a table of relative codon usage. ''' from sets import Set import sys,argparse from collections import defaultdict import re import numpy as np import csv import random from Bio import SeqIO #----------------...
f.close() f = open("_".join([prefix, "1000_scores.tsv"]), "w+") f.write("\n".join(score_list)) f.close() midpoint_score = sorted(score_list)[500] sorted_cds = [x for _,x in sorted(zip(score_list,cds_list))] midpoint_cds = sorted_cds[500] print("midpoint sequence:") print midpoint_score print midpoint_cds #--------...
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
# !/usr/bin/python # This tool converts text file to a html looks like a presenation. # -*- coding: utf-8 -*- # Version 1.0 05/01/2015 # *************************************************************************** # * Copyright (C) 2015, Varun Srinivas Chakravarthi Nalluri * # * ...
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
# !/usr/bin/python # This tool converts text file to a html looks like a presenation. # -*- coding: utf-8 -*- # Version 1.0 05/01/2015 # *************************************************************************** # * Copyright (C) 2015, Varun Srinivas Chakravarthi Nalluri * # * ...
# Converts markdown text to html text def convertTextToHtml(data, custom_markdown_args): output = "" if custom_markdown_args == "": output = markdown.markdown(data) # Using imported python markdown else: if ' ' in custom_markdown_args: markdown_cmd = custom_markd...
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
# !/usr/bin/python # This tool converts text file to a html looks like a presenation. # -*- coding: utf-8 -*- # Version 1.0 05/01/2015 # *************************************************************************** # * Copyright (C) 2015, Varun Srinivas Chakravarthi Nalluri * # * ...
else: output = output.decode('utf-8') return output # begin main() if __name__ == "__main__": main(sys.argv[1:])
print(" Error while running markdown script : ") print(err) sys.exit(1)
random_line_split
easyPresentation.py
# !/usr/bin/python # This tool converts text file to a html looks like a presenation. # -*- coding: utf-8 -*- # Version 1.0 05/01/2015 # *************************************************************************** # * Copyright (C) 2015, Varun Srinivas Chakravarthi Nalluri * # * ...
(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
# -*- coding: ascii -*- # # Copyright 2006-2012 # Andr\xe9 Malo or his licensors, as applicable # # 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-...
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
# -*- coding: ascii -*- # # Copyright 2006-2012 # Andr\xe9 Malo or his licensors, as applicable # # 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-...
AF_INET6 = getattr(_socket, 'AF_INET6', None) for family, stype, proto, _, addr in adi: if not _socket.has_ipv6 and family == AF_INET6: continue # skip silenty if python was built without it. sock = _socket.socket(family, stype, proto) sock.settimeo...
_lock.acquire() try: if spec not in _cache: _cache[spec] = ( adi, _datetime.datetime.utcnow() + _datetime.timedelta(seconds=cache), ) ...
conditional_block
osutil.py
# -*- coding: ascii -*- # # Copyright 2006-2012 # Andr\xe9 Malo or his licensors, as applicable # # 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-...
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
# -*- coding: ascii -*- # # Copyright 2006-2012 # Andr\xe9 Malo or his licensors, as applicable # # 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-...
(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
#!/usr/bin/python import paramiko import sys import os import string import threading import subprocess import time import select import datetime from os.path import expanduser import qs global threads threads = [] global upload upload = False class FileCopy: def __init__(self): self.numCams = 21 self...
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
#!/usr/bin/python import paramiko import sys import os import string import threading import subprocess import time import select import datetime from os.path import expanduser import qs global threads threads = [] global upload upload = False class FileCopy: def __init__(self): self.numCams = 21 self...
(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
#!/usr/bin/python import paramiko import sys import os import string import threading import subprocess import time import select import datetime from os.path import expanduser import qs global threads threads = [] global upload upload = False class FileCopy: def __init__(self): self.numCams = 21 self...
# This is the string the user sees when starting the program. # It provides instructions of the legal inputs introString = """ File copying instructions: If this is the first file for this subject enter the subject identifier eg. 's1' followed by the following folder type. The subject identifier can be left out...
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
#!/usr/bin/python import paramiko import sys import os import string import threading import subprocess import time import select import datetime from os.path import expanduser import qs global threads threads = [] global upload upload = False class FileCopy: def __init__(self): self.numCams = 21 self...
#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
/* eslint-disable @typescript-eslint/no-empty-function */ import React, { useState, useEffect, useCallback } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import lodashGet from 'lodash/get'; import lodashFind from 'lodash/find'; import lodashIsEqual from 'lodash/isEqual'; impo...
} } 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
/* eslint-disable @typescript-eslint/no-empty-function */ import React, { useState, useEffect, useCallback } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import lodashGet from 'lodash/get'; import lodashFind from 'lodash/find'; import lodashIsEqual from 'lodash/isEqual'; impo...
const mapDispatchToProps = {}; export default connect(mapStateToProps, mapDispatchToProps)(DynamicInput);
extraProps.dropdownState = getDropDownListFromState(field, 'uiEnable', state, metaData); } return extraProps; };
random_line_split
client.rs
// #[macro_use] extern crate actix; // extern crate byteorder; // extern crate bytes; extern crate futures; extern crate serde; extern crate serde_json; // extern crate tokio_io; // extern crate tokio_tcp; extern crate awc; extern crate rustls; extern crate structopt; #[macro_use] extern crate log; extern crate env_log...
// 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
// #[macro_use] extern crate actix; // extern crate byteorder; // extern crate bytes; extern crate futures; extern crate serde; extern crate serde_json; // extern crate tokio_io; // extern crate tokio_tcp; extern crate awc; extern crate rustls; extern crate structopt; #[macro_use] extern crate log; extern crate env_log...
<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