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
term_gui.rs
rustbox.print_char(col, row, style, Color::Default, Color::Default, c); } row += 1; if row > rustbox.height() { break; } } } } struct BufferViewWidget { view_id: String, client: client::ThinClient, cursor_id: String, } impl Buff...
{ let options = parse_options(); let mut gui = TerminalGui::new(&options).unwrap(); while gui.handle_events().unwrap() { gui.draw(); } }
identifier_body
term_gui.rs
of the server, since the server // might run on a different machine than the client - and certainly in a different // directory. let current_dir = env::current_dir().unwrap(); let rpc = try!(client.call("list_files", &swiboe::plugin::list_files::ListFilesRequest { directory...
(&mut self, key: rustbox::Key) -> CompleterState { match key { rustbox::Key::Char(c) => { self.query.push(c); self.results.clear(); CompleterState::Running }, rustbox::Key::Backspace => { self.query.pop(); ...
on_key
identifier_name
wechat_task.py
.join(self.out_path,"qrcode") if not os.path.exists(self.out_qrcode_path): os.makedirs(self.out_qrcode_path) self.wx_cookie_path = os.path.join(self.out_path,"wx.info") def __start_threads__(self): for thread_id in range(1,self.threads): thread_name = "Thread - " +...
os.makedirs(image_path) if not os.path.exists(pdf_path): os.makedirs(pdf_path) html_file = os.path.join(html_path,str(no)+ "-" +title+".html") pdf_file = os.path.join(pdf_path,str(no)+ "-" +title+".pdf") if os.path.exists(pdf_file): # PDF文件存在则不生成对应的PDF文件,否则继续 ...
s(image_path):
conditional_block
wechat_task.py
请使用微信扫描弹出的二维码图片用于登录微信公众号!") try: image = Image.open(qrcode_path) image.show() except Exception as e: log.error(e) raise Exception("获取二维码失败,请重试!") self.getqrcodeStatus(session) def getqrcodeStatus(self,session,t=6): while Tr...
s_code == 200: with open(path, 'wb+') as f: for chunk in resp.iter_content(chunk_size=1024): if chunk: f.write(chunk) f.flush() f.close() return session,True time.sleep(1) ...
identifier_body
wechat_task.py
.referer } if self.cookie: head["Cookie"] = self.cookie if heads: for key,value in heads.items(): head[key] = value return head def __start_login__(self): data = {"sessionid":str(time.time()).replace(".","")} session,result =...
def __http_io_request__(self,method='get',url=None,data=None,headers=None,session=requests.session(),stream=True,path=None):
random_line_split
wechat_task.py
.join(self.out_path,"qrcode") if not os.path.exists(self.out_qrcode_path): os.makedirs(self.out_qrcode_path) self.wx_cookie_path = os.path.join(self.out_path,"wx.info") def __start_threads__(self): for thread_id in range(1,self.threads): thread_name = "Thread - " +...
html_path = os.path.join(out_dir,"html") pdf_path = os.path.join(out_dir,"pdf") image_path = os.path.join(html_path,"image") if not os.path.exists(image_path): os.makedirs(image_path) if not os.path.exists(pdf_path): os.makedirs(pdf_path) h...
.replace(filter,"")
identifier_name
write.rs
} /// Creates a new builder instance for a binary STL file. pub fn
() -> Self { Self::new(Encoding::Binary) } /// Creates a new builder instance for an ASCII STL file. /// /// **Note**: please don't use this. STL ASCII files are even more space /// inefficient than binary STL files. If you can avoid it, never use ASCII /// STL. In fact, consider not us...
binary
identifier_name
write.rs
/// Creates a new builder instance for a binary STL file. pub fn binary() -> Self { Self::new(Encoding::Binary) } /// Creates a new builder instance for an ASCII STL file. /// /// **Note**: please don't use this. STL ASCII files are even more space /// inefficient than binary STL fi...
#[inline(never)] pub fn write_raw_binary( self, num_triangles: u32, triangles: impl IntoIterator<Item = Result<RawTriangle, Error>>, ) -> Result<(), Error> { let config = self.config; let mut w = self.writer; // First, a 80 bytes useless header that must no...
{ if self.config.encoding == Encoding::Ascii { self.write_raw_ascii(triangles) } else { self.write_raw_binary(num_triangles, triangles) } }
identifier_body
write.rs
use cgmath::prelude::*; use crate::{ prelude::*, io::{PropKind, Error, ErrorKind}, }; use super::{Encoding, RawTriangle}; // ---------------------------------------------------------------------------- /// The solid name used when the user didn't specify one. const DEFAULT_SOLID_NAME: &str = "mesh"; // ==...
use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};
random_line_split
write.rs
/// Creates a new builder instance for a binary STL file. pub fn binary() -> Self { Self::new(Encoding::Binary) } /// Creates a new builder instance for an ASCII STL file. /// /// **Note**: please don't use this. STL ASCII files are even more space /// inefficient than binary STL fi...
let mesh = src.core_mesh(); let has_normals = src.face_normal_type().is_some(); // The triangle iterator let triangles = mesh.face_handles().map(|fh| { let mut it = mesh.vertices_around_face(fh); let va = it.next().expect("bug: less than 3 vertices around face"...
{ return Err(Error::new(|| ErrorKind::DataIncomplete { prop: PropKind::VertexPosition, msg: "source does not provide vertex positions, but STL requires them".into(), })); }
conditional_block
jh.py
3, 0x0758df38, 0x65655e4e, 0x897cfcf2, 0x8e5086fc, 0x442e7031, 0x86ca0bd0, 0xa20940f0, 0x4e477830, 0x39eea065, 0x8338f7d1, 0x37e95ef7, 0xbd3a2ce4, 0x26b29721, 0x6ff81301, 0xd1ed44a3, 0xe7de9fef, 0x15dfa08b, 0xd9922576, 0xf6f7853c, 0xbe42dc12, 0x7ceca7d8, 0x7eb027ab, 0xda7d8d53, 0xdea83eaa, 0x93ce25aa, 0...
SL
identifier_name
jh.py
] x[0] ^= x[5] x[1] ^= x[6] x[2] ^= x[7] ^ x[4] x[3] ^= x[4] return x def Ceven(n, r): return C[((r) << 3) + 3 - n] def Codd(n, r): return C[((r) << 3) + 7 - n] def S(x0, x1, x2, x3, cb, r): x = Sb([x0[3], x1[3], x2[3], x3[3]], cb(3, r)) x0[3] = x[0] x1[3] = x[1] x2[3] ...
state[5] = h[1][2] state[6] = h[1][1] state[7] = h[1][0] state[8] = h[2][3]
random_line_split
jh.py
] = x[5] x6[1] = x[6] x7[1] = x[7] x = Lb([x0[0], x1[0], x2[0], x3[0], x4[0], x5[0], x6[0], x7[0]]) x0[0] = x[0] x1[0] = x[1] x2[0] = x[2] x3[0] = x[3] x4[0] = x[4] x5[0] = x[5] x6[0] = x[6] x7[0] = x[7] def Wz(x, c, n): t = (x[3] & (c)) << (n) x[3] = ((x[3] >> (n))...
buf32 = op.swap32_list(op.bytes_to_i32_list(buf)) bufferXORInsertBackwards(V, buf32, 4, 4) E8(V) bufferXORInsertBackwards(V, buf32, 4, 4, 4, 0) blockCountLow = ctx['blockCountLow'] blockCountLow = op.t32(blockCountLow + 1) ctx['blockCountLow'] = bl...
conditional_block
jh.py
f2c9d2, 0x0cd29b00, 0x30ceaa5f, 0x300cd4b7, 0x16512a74, 0x9832e0f2, 0xd830eb0d, 0x9af8cee3, 0x7b9ec54b, 0x9279f1b5, 0x6ee651ff, 0xd3688604, 0x574d239b, 0x316796e6, 0xf3a6e6cc, 0x05750a17, 0xd98176b1, 0xce6c3213, 0x8452173c, 0x62a205f8, 0xb3cb2bf4, 0x47154778, 0x825446ff, 0x486a9323, 0x0758df38, 0x65655e...
t = (x[3] & (c)) << (n) x[3] = ((x[3] >> (n)) & (c)) | t t = (x[2] & (c)) << (n) x[2] = ((x[2] >> (n)) & (c)) | t t = (x[1] & (c)) << (n) x[1] = ((x[1] >> (n)) & (c)) | t t = (x[0] & (c)) << (n) x[0] = ((x[0] >> (n)) & (c)) | t
identifier_body
parse.rs
']'", 0), '{' => { match split_in_parens(s.clone(), CURLY_BRACKETS) { Some((rep, newst)) => { if let Some(p) = stack.pop() { let rep = parse_specific_repetition(rep, p)?; stack.push(rep); ...
{ let case1 = ( "a(b)c", Pattern::Concat(vec![ Pattern::Char('a'), Pattern::Submatch(Box::new(Pattern::Char('b'))), Pattern::Char('c'), ]), ); let case2 = ("(b)", Pattern::Submatch(Box::new(Pattern::Char('b'))));...
identifier_body
parse.rs
(from, self.len()) } /// pos returns the overall position within the input regex. fn pos(&self) -> usize { self.pos } /// sub returns a sub-ParseState containing [from..to] of the current one. fn sub(&self, from: usize, to: usize) -> ParseState<'a> { ParseState { src:...
} else { return s.err("repetition {} without pattern to repeat", 0); } } None => return s.err("unmatched {", s.len()), }; } c => { stack.push(Patter...
if let Some(p) = stack.pop() { let rep = parse_specific_repetition(rep, p)?; stack.push(rep); s = newst;
random_line_split
parse.rs
<'a> { /// The string to parse. This may be a substring of the "overall" matched string. src: &'a [char], /// The position within the overall string (for error reporting). pos: usize, } impl<'a> ParseState<'a> { /// new returns a new ParseState operating on the specified input string. fn new(s:...
ParseState
identifier_name
regression.py
____', 'try dropping "type" _____,' 'try adding "type" _____, to improve score by ____'], [[str(round(pred_val,5)), rank, top_5_games, str(round(accuracy,2)), decrease_gain_tup, increase_gain_tup, lang_dep_gain_tup, game_type_tup]]) e...
''' Make recommendations based on what paramters can the user potentially increase, decrease, switch categories of to increase their predicted value of BGG rating and number of ratings and also informs of the corresponding change in the predicted value Inputs: coef (pandas DataFrame): be...
identifier_body
regression.py
for predicted BGG rating If False, run the regression for predicted number of ratings input_dict (dict): Dictionary produced by Django UI, containing required fields for the prediction using regres...
#Source: /home/syedajaisha/capp30121-aut-20-syedajaisha/pa5/util.py col_names = list(X.columns) col_names[0] = 'intercept' coef = pd.DataFrame({'beta': beta}, index=col_names) return coef def calculate_R2(X, y, beta): ''' Calculate R_sqauared for a regression model Inputs: X (...
''' beta = np.linalg.lstsq(X, y, rcond=None)[0]
random_line_split
regression.py
in input_dict.keys(): if field == 'Language dependency': for dummy, complexity in django_to_local_cols[field].items(): x_dict[dummy] = 0 if input_dict[field] == complexity: x_dict[dummy] = 1 elif field in ['Type 1', 'Type 2', 'Type 3']: ...
if beta[current_lang_dep] < 0: lang_dep_gain_tup.append((1, -beta[current_lang_dep])) for lang_dep_dummy in django_to_local_cols['Language dependency'].keys(): if beta[lang_dep_dummy] > beta[current_lang_dep]: gain = -beta[current_lang_dep]...
conditional_block
regression.py
for predicted BGG rating If False, run the regression for predicted number of ratings input_dict (dict): Dictionary produced by Django UI, containing required fields for the prediction using regres...
(X, y, beta): ''' Calculate R_sqauared for a regression model Inputs: X (pandas DataFrame):
calculate_R2
identifier_name
iggo.go
int `json:"follower_count"` Byline string `json:"byline"` } } Tags []struct { Tag struct { Name string `json:"name"` MediaCount int `json:"media_count"` } `json:"hashtag"` } `json:"hashtags"` } type Tag struct { Name string Posts []*Post } func GetPost(r *http.Request) (*Post, e...
return nil } func sharedData(r io.Reader) []byte { re := regexp.MustCompile(`window._sharedData\s?=\s?(.*);</script>`) b, err := ioutil.ReadAll(r) if err != nil { return nil } matches := re.FindSubmatch(b) if len(matches) < 2 { return nil } return matches[1] } func getSearchResult(q string) (*SearchR...
{ return &appError{"Template error", 500, err} }
conditional_block
iggo.go
: n.Get("shortcode").GetString(), URL: n.Get("display_url").GetString(), Timestamp: timestamp, Time: humanize.Time(time.Unix(timestamp, 0)), Likes: n.GetPath("edge_liked_by", "count").GetInt(), Sizes: sizes, Text: getText(n), Height: n.GetPath("dimensions", "height").GetI...
{ return GetPost(r) }
identifier_body
iggo.go
:= range base.GetPath("edge_media_preview_like", "edges").GetArray() { n := edge.Get("node") likers = append(likers, &PostLiker{ ProfilePic: n.Get("profile_pic_url").GetString(), Username: n.Get("username").GetString(), }) } data := &Post{ Shortcode: base.Get("shortcode").GetString(), ID: b...
makeIndex
identifier_name
iggo.go
:= range n.Get("thumbnail_resources").GetArray() { sizes = append(sizes, Size{ URL: s.Get("src").GetString(), Width: s.Get("config_width").GetInt(), Height: s.Get("config_width").GetInt(), }) } timestamp := n.Get("taken_at_timestamp").GetInt64() posts = append(posts, &Post{ ID: n...
return renderTemplate(w, templateKey, data) } }
random_line_split
fib.rs
{ assert!(self.is_some()); let _self_idx = idx!(self); /* validate right sibling */ let rh = right!(self); if rh.is_some() { let _rh_idx = idx!(rh); let rhlf = left!(rh).upgrade(); assert!(rhlf.rc_eq(self)); assert!(rhlf.is_s...
(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { writeln!(f, "R({:?}) ", self)?; let mut curq = vec![(self.clone(), self.children())]; loop { let mut nxtq = vec![]; for (p, children) in curq { if children.is_empty() { bre...
fmt
identifier_name
fib.rs
/// replace with new val, return old val fn replace_key(&self, val: T) -> T where I: Debug, T: Debug { replace(val_mut!(self), val) } fn replace(&mut self, x: Self) -> Self { let old = Self(self.0.clone()); self.0 = x.0; old } #[cfg(tes...
{ if !left!(x).is_none() { right!(left!(x).upgrade(), right!(x)); } else { debug_assert!(child!(self).rc_eq(&x)); child!(self, right!(x)); } if !right!(x).is_none() { left!(right!(x), left!(x)); } rank!(self, rank!(self) -...
identifier_body
fib.rs
: T) -> Option<T> where I: Eq + Hash + Clone, T: Debug { let x; match self.nodes.entry(i.clone()) { Occupied(ent) => { x = ent.get().clone(); let oldv = x.replace_key(v); self.decrease_key_(x); Some(oldv...
(sib.is_some()); sib = right!(sib);
conditional_block
fib.rs
where I: Borrow<Q>, Q: Ord + Hash + ?Sized, { self.nodes.get(i).map(|node| val!(node)) } pub fn indexes(&self) -> impl Iterator<Item = &I> { self.nodes.keys() } //////////////////////////////////////////////////////////////////////////// //// Assistant met...
min = Node::none(); }
random_line_split
main.rs
if let Some(spare) = spare_chemicals.get_mut(&req_chem) { if *spare >= req_amount { // We have enough spare to completely fulfill this // requirement, no need to go further. *spare -= req_amount; continue; }...
let used_ore = calc_ore_for_fuel(current, reactions); if used_ore < ore { lower = current; } else { upper = current; } if upper - 1 == lower { return lower; } } } fn parse_chemical(chemical: &str) -> (String, u64) { let mut ...
{ let mut lower = 1; let mut current; let mut upper = 1; // Find an upper bound to use for binary search. loop { let used_ore = calc_ore_for_fuel(upper, reactions); if used_ore < ore { upper *= 2; } else { break; } } // Binary search ...
identifier_body
main.rs
if let Some(spare) = spare_chemicals.get_mut(&req_chem) { if *spare >= req_amount { // We have enough spare to completely fulfill this // requirement, no need to go further. *spare -= req_amount; continue; }...
() { let input = vec![String::from("7 A, 1 E => 1 FUEL")]; let reactions = parse_reactions(input.as_slice()); let result = reactions.get(&String::from("FUEL")); assert!(result.is_some()); let reaction = result.unwrap(); assert_eq!( *reaction, Rea...
test_parse
identifier_name
main.rs
if let Some(spare) = spare_chemicals.get_mut(&req_chem) { if *spare >= req_amount { // We have enough spare to completely fulfill this // requirement, no need to go further. *spare -= req_amount; continue; }...
} fn parse_input(filename: &str) -> ReactionMap { let file = File::open(filename).expect("Failed to open file"); let reader = BufReader::new(file); let reactions: Vec<String> = reader .lines() .map(|l| l.expect("Failed to read line")) .map(|l| String::from(l.trim())) .colle...
} reactions
random_line_split
main.rs
let Some(spare) = spare_chemicals.get_mut(&req_chem) { if *spare >= req_amount { // We have enough spare to completely fulfill this // requirement, no need to go further. *spare -= req_amount; continue; } el...
} // Binary search to find the highest amount of fuel we can // produce without using all the ore. loop { current = (upper - lower) / 2 + lower; let used_ore = calc_ore_for_fuel(current, reactions); if used_ore < ore { lower = current; } else { ...
{ break; }
conditional_block
$time.js
single-digit hours (12-hour clock). H Hours; no leading zero for single-digit hours (24-hour clock). HH Hours; leading zero for single-digit hours (24-hour clock). M Minutes; no leading zero for single-digit minutes. MM Minutes; leading zero for single-digit minutes. s Seconds; no leading zero...
return $secondsToTime(parseInt(ms, 10)/1000); } l
identifier_body
$time.js
X Years * * Single units are +10%. 1 Year shows first at 1 Year + 10% */ function
(val, single) { if(val >= single && val <= single * (1+margin)) { return single; } return val; } function normalizeDateInput(date) { switch (typeof date) { case "string": date = new Date(('' + date).replace(minusRe, "/").replace(tzRe, " ")); break; case "number": date = new...
normalize
identifier_name
$time.js
lang.ago; } for(var i = 0, format = formats[0]; formats[i]; format = formats[++i]) { if(seconds < format[0]) { if(i === 0) { // Now return format[1]; } var val = Math.ceil(normalize(seconds, format[3]) / (format[3])); return val + ' ' + (val != 1 ? format[2] : for...
M: M, MM: pad(M), s: s, ss: pad(s),
random_line_split
$time.js
X Years * * Single units are +10%. 1 Year shows first at 1 Year + 10% */ function normalize(val, single) { if(val >= single && val <= single * (1+margin)) { return single; } return val; } function normalizeDateInput(date) { switch (typeof date) { case "string": dat...
var val = Math.ceil(normalize(seconds, format[3]) / (format[3])); return val + ' ' + (val != 1 ? format[2] : format[1]) + (i > 0 ? token : ''); } } }; timeAgo.lang = {}; timeAgo.formats = {}; timeAgo.setLang = function(code, newLang) { this.defaultLang = code; this.la...
{ // Now return format[1]; }
conditional_block
ecvrf.rs
traits::Uniform, vrf::ecvrf::*}; //! # use rand::{rngs::StdRng, SeedableRng}; //! # let message = b"Test message"; //! # let mut rng: StdRng = SeedableRng::from_seed([0; 32]); //! # let private_key = VRFPrivateKey::generate_for_testing(&mut rng); //! # let public_key: VRFPublicKey = (&private_key).into(); //! let proof...
} impl TryFrom<&[u8]> for VRFPrivateKey { type Error = CryptoMaterialError; fn try_from(bytes: &[u8]) -> std::result::Result<VRFPrivateKey, CryptoMaterialError> { Ok(VRFPrivateKey( ed25519_PrivateKey::from_bytes(bytes).unwrap(), )) } } impl TryFrom<&[u8]> for VRFPublicKey { ...
{ VRFPrivateKey(ed25519_PrivateKey::generate(rng)) }
identifier_body
ecvrf.rs
ECVRF private key #[derive(Serialize, Deserialize, Deref, Debug)] pub struct VRFPrivateKey(ed25519_PrivateKey); /// An ECVRF public key #[derive(Serialize, Deserialize, Deref, Debug, PartialEq, Eq)] pub struct VRFPublicKey(ed25519_PublicKey); /// A longer private key which is slightly optimized for proof generation....
random_line_split
ecvrf.rs
traits::Uniform, vrf::ecvrf::*}; //! # use rand::{rngs::StdRng, SeedableRng}; //! # let message = b"Test message"; //! # let mut rng: StdRng = SeedableRng::from_seed([0; 32]); //! # let private_key = VRFPrivateKey::generate_for_testing(&mut rng); //! # let public_key: VRFPublicKey = (&private_key).into(); //! let proof...
else { bail!("The proof failed to verify for this public key") } } pub(super) fn hash_to_curve(&self, alpha: &[u8]) -> EdwardsPoint { let mut result = [0u8; 32]; let mut counter = 0; let mut wrapped_point: Option<EdwardsPoint> = None; while wrapped_point.is...
{ Ok(()) }
conditional_block
ecvrf.rs
traits::Uniform, vrf::ecvrf::*}; //! # use rand::{rngs::StdRng, SeedableRng}; //! # let message = b"Test message"; //! # let mut rng: StdRng = SeedableRng::from_seed([0; 32]); //! # let private_key = VRFPrivateKey::generate_for_testing(&mut rng); //! # let public_key: VRFPublicKey = (&private_key).into(); //! let proof...
(bytes: &[u8]) -> std::result::Result<VRFPublicKey, CryptoMaterialError> { if bytes.len() != ed25519_dalek::PUBLIC_KEY_LENGTH { return Err(CryptoMaterialError::WrongLengthError); } let mut bits: [u8; 32] = [0u8; 32]; bits.copy_from_slice(&bytes[..32]); let compresse...
try_from
identifier_name
interactor.go
} // For sparse checkouts, we have to do some additional housekeeping after // the clone is completed. We use Git's global "-C <directory>" flag to // switch to that directory before running the "sparse-checkout" command, // because otherwise the command will fail (because it will try to run the // command in th...
{ return err }
conditional_block
interactor.go
q: %w %v", commitlike, err, string(out)) } return nil } // RevParse runs git rev-parse. func (i *interactor) RevParse(commitlike string) (string, error) { i.logger.Infof("Parsing revision %q", commitlike) out, err := i.executor.Run("rev-parse", commitlike) if err != nil { return "", fmt.Errorf("error parsing %q...
{ fetchArgs := []string{"--no-write-fetch-head"} if noFetchTags { fetchArgs = append(fetchArgs, "--no-tags") } // For each commit SHA, check if it already exists. If so, don't bother // fetching it. var missingCommits bool for _, commitSHA := range commitSHAs { if exists, _ := i.ObjectExists(commitSHA); ex...
identifier_body
interactor.go
nil { i.logger.WithError(err).Warnf("Error staging merge for %q: %s", commitlike, string(out)) if out, err := i.executor.Run("reset", "--hard", "HEAD"); err != nil { return false, fmt.Errorf("error aborting merge of %q: %w %v", commitlike, err, string(out)) } return false, nil } out, err = i.executor.Run(...
ShowRef
identifier_name
interactor.go
the clone is completed. We use Git's global "-C <directory>" flag to // switch to that directory before running the "sparse-checkout" command, // because otherwise the command will fail (because it will try to run the // command in the $PWD, which is not the same as the just-created clone // directory (i.dir)). i...
return fmt.Errorf("failed to merge %q", headSHA) }
random_line_split
eulerlib.py
) tn = i = 1 while tn < n: triangle_numbers[triangle_number(i)] = True i += 1 tn = triangle_number(i) return triangle_numbers def hexagonal_number(n): """ Calculate the nth hexagonal number. :param n: Hn :return: Hexagonal number """ return n * (2 * n - 1) ...
numbers): """ Returns the product of a list of numbers. :param numbers: :return: """ p = 1 for x in numbers: p *= x return p def factorial(n): """ Returns the factorial n! of a number. :param n: :return: """ return product(range(1, n + 1)) def is_even(...
roduct(
identifier_name
eulerlib.py
:param b: :return: """ return a * b // gcd(a, b) def lcm3(a, b, c): """ Calculating the LCM for multiple digits is done with LCM(a,b,c) = LCM(LCM(a,b),c) :param a: :param b: :param c: :return: """ return lcm(lcm(a, b), c) def primitive_pythagorean_triplet_generato...
-= 1
conditional_block
eulerlib.py
): yield list(hp) def shift(a, n=1): """ Shift all the elements in the list by n. :param a: :param n: :return: """ return a[n:] + a[:n] def is_palindrome(x): """ Returns true if a number or a string is a palindrome. :param x: :return: """ strx = str(x)...
def union_sets(S): """
random_line_split
eulerlib.py
1) tn = i = 1 while tn < n: triangle_numbers[triangle_number(i)] = True i += 1 tn = triangle_number(i) return triangle_numbers def hexagonal_number(n):
def is_hexagonal_number(n): """ Determines if n is a hexagonal number. :param n: Hn :return: Hexagonal number """ _, x = quadratic.solve(2, -1, -n) return is_number(x) and x.is_integer() def pentagonal_number(n): return n * (3 * n - 1) / 2 def is_pentagonal_number(n): """ ...
""" Calculate the nth hexagonal number. :param n: Hn :return: Hexagonal number """ return n * (2 * n - 1)
identifier_body
constant_folding.py
(other_et)) value = lst.value + list(other.value) elements = lst.elements + other_elts stack.push(_Constant(typ, value, elements, op)) elif isinstance(op, opcodes.MAP_ADD): elements = stack.fold_args(3, op) if elements: map_, key, val = element...
elts = tuple(typeconst(t) for t in params) else:
random_line_split
constant_folding.py
elements: Tuple[Any, ...] @attrs.define class _Map: """A dictionary.""" key_types: FrozenSet[Any] keys: Tuple[Any, ...] value_types: FrozenSet[Any] values: Tuple[Any, ...] elements: Dict[Any, Any] class _CollectionBuilder: """Build up a collection of constants.""" def __init__(self): self.typ...
def _preserve_constant(self, c): if c and ( not isinstance(c.op, opcodes.LOAD_CONST) or isinstance(c.op, opcodes.BUILD_STRING)): self.consts[id(c.op)] = c def clear(self): # Preserve any constants in the stack before clearing it. for c in self.stack: self._preserve_constan...
return self.stack.pop()
identifier_body
constant_folding.py
"""Collect the arguments to a build call.""" ret = _CollectionBuilder() args = self._pop_args(n) if args is None: self.push(None) return None for elt in args: ret.add(elt) elt.op.folded = op return ret.build() def fold_map_args(self, n, op): """Collect the arguments ...
params = tuple(expand(vals)) return (tag, params)
conditional_block
constant_folding.py
elements: Tuple[Any, ...] @attrs.define class _Map: """A dictionary.""" key_types: FrozenSet[Any] keys: Tuple[Any, ...] value_types: FrozenSet[Any] values: Tuple[Any, ...] elements: Dict[Any, Any] class _CollectionBuilder: """Build up a collection of constants.""" def __init__(self): self.typ...
(self, python_type, op): """Build a folded type.""" collection = self.fold_args(op.arg, op) if collection: typename = python_type.__name__ typ = (typename, collection.types) try: value = python_type(collection.values) except TypeError as e: raise ConstantError(f'TypeE...
build
identifier_name
parser.rs
whitespace and comments fn space<'a>() -> Parser<'a, u8, ()> { (ws() | comment()).repeat(0..).discard() } fn semi<'a>() -> Parser<'a, u8, ()> { keyword(b";").name("semi") } fn to_eol<'a>() -> Parser<'a, u8, String> { fn anything_else(term: u8) -> bool { !is_cr(term) && !is_lf(term) } is_...
<'a>() -> Parser<'a, u8, Vec<State>> { fn tag_starting_state(idx: usize, state: State) -> State { State { is_starting_state: idx == 0, ..state } }; state().repeat(0..).map(|states| states.into_iter().enumerate().map(|(idx, state)| tag_starting_state(idx, state)).colle...
state_list
identifier_name
parser.rs
fn to_eol<'a>() -> Parser<'a, u8, String> { fn anything_else(term: u8) -> bool { !is_cr(term) && !is_lf(term) } is_a(anything_else) .repeat(0..) .map(|u8s| String::from_utf8(u8s).expect("can only parse utf")) } fn line_comment<'a>() -> Parser<'a, u8, ()> { (seq(b"//") * to_eol(...
{ let line_parser = (to_eol() - eol()).repeat(0..); let parse_result = line_parser.parse(byte_slice).unwrap(); parse_result.len() }
identifier_body
parser.rs
(is_underscore)).repeat(0..)) .map(|(first, rest)| format!("{}{}", first as char, String::from_utf8(rest).unwrap())); spaced(it).name("name") } fn string<'a>() -> Parser<'a, u8, String> { let special_char = sym(b'\\') | sym(b'/') | sym(b'"') | sym(b'b').map(|_| b'\x08') ...
{ let start_str = &byte_vec[0..position]; let line = count_lines(start_str) + 1; let end = min(position + 50, file_content.len() - 1); let extract = &file_content[position..end]; let extract = extract .to_string() ...
conditional_block
parser.rs
/// whitespace and comments fn space<'a>() -> Parser<'a, u8, ()> { (ws() | comment()).repeat(0..).discard() } fn semi<'a>() -> Parser<'a, u8, ()> { keyword(b";").name("semi") } fn to_eol<'a>() -> Parser<'a, u8, String> { fn anything_else(term: u8) -> bool { !is_cr(term) && !is_lf(term) } ...
fn accept_states_list<'a>() -> Parser<'a, u8, Vec<AcceptState>> { accept_states_chain() .repeat(0..) .map(|chains| chains.into_iter().flatten().collect()) } fn accept_states_chain<'a>() -> Parser<'a, u8, Vec<AcceptState>> { let raw = spaced(list(spaced(state_id()), keyword(b"->"))) - semi(); ...
} }; state().repeat(0..).map(|states| states.into_iter().enumerate().map(|(idx, state)| tag_starting_state(idx, state)).collect()) }
random_line_split
lib.rs
null? args) // (if (tail? next) // c // (list ’frame next c)) // (loop (cdr args) // (compile (car args) // (list ’argument c)))))])] // [else // (list ’constant x next)]))) pub ...
let ix_opt = self.vars.iter().position(|v| { v == var }); match ix_opt { Some(ix) => { *self.vals.get_mut(ix) = val }, None => self.vals.push(val) }; } fn extend(&self, vars: Vec<String>, vals: Vec<Obj>) -> Scope { Scope{ parent: Some(box self.clone...
identifier_name
lib.rs
(*test, box TEST{kthen:thenc, kelse:elsec}) }, Set(var, x) => { compile(*x, box ASSIGN{var:var, k:next} ) }, CallCC(x) => { let c = box CONTI{ k: box ARGUMENT{ k:compile(*x, box APPLY{unused:true}) } }; if is_tail(&next) { c...
case CLOSE : I: CLOSE ; A = Closur
conditional_block
lib.rs
(null? args) // (if (tail? next) // c // (list ’frame next c)) // (loop (cdr args) // (compile (car args) // (list ’argument c)))))])] // [else // (list ’constant x next)]))) pu...
S: Frame } impl VMState { fn make(a:Obj, x:Code, e:Scope, r:Vec<Obj>, s:Frame) -> VMState { VMState { A:a, X:x, E:e, R:r, S:s } } fn accumulator(&self) -> &Obj { &self.A } fn program(&self) -> &Code { &self.X } fn environment(&self) -> &Scope { &self.E } fn ...
// control stack (ptr to top call frame; frames have link to prev frame)
random_line_split
nvg.rs
the scaling /// since aforementioned pixel snapping. /// /// While this may sound a little odd, the setup allows you to always render the /// same way regardless of scaling. /// /// Note: currently only solid color fill is supported for text. pub fn create_font( &self, name:...
to_sys
identifier_name
nvg.rs
{ handle }), } } /// NanoVG allows you to load jpg, png, psd, tga, pic and gif files to be used for rendering. /// In addition you can upload your own image. The image loading is provided by stb_image. pub fn create_image( &self, filename: &str, ) -> std::result::Result<Ima...
} impl Style { /// Set the stroke of this style.
random_line_split
deployment-center-state-manager.ts
$ = new BehaviorSubject<string>(''); public bitBucketToken$ = new BehaviorSubject<string>(''); public gitHubToken$ = new BehaviorSubject<string>(''); public replacementPublishUrl = ''; constructor( private _cacheService: CacheService, private _azureDevOpsService: AzureDevOpsService, private _transl...
{ const repo = this.wizardValues.sourceSettings.repoUrl.replace(`${DeploymentCenterConstants.githubUri}/`, ''); const branch = this.wizardValues.sourceSettings.branch || 'master'; const workflowInformation = this._githubService.getWorkflowInformation( this.wizardValues.buildSettings, this.wizard...
identifier_body
deployment-center-state-manager.ts
stsScenarioCheck => { this.hideBuild = vstsScenarioCheck.status === 'disabled'; }); userService .getStartupInfo() .takeUntil(this._ngUnsubscribe$) .subscribe(r => { this._token = r.token; }); } public get wizardValues(): WizardForm { return this.wizardForm.val...
{ return this._updateMetadata(r.result.properties, sourceSettingsPayload); }
conditional_block
deployment-center-state-manager.ts
.hideBuild = vstsScenarioCheck.status === 'disabled'; }); userService .getStartupInfo() .takeUntil(this._ngUnsubscribe$) .subscribe(r => { this._token = r.token; }); } public get wizardValues(): WizardForm { return this.wizardForm.value; } public set wizardValues...
random_line_split
deployment-center-state-manager.ts
wizardValues(values: WizardForm) { this.wizardForm.patchValue(values); } public get sourceSettings(): FormGroup { return (this.wizardForm && (this.wizardForm.controls.sourceSettings as FormGroup)) || null; } public get buildSettings(): FormGroup { return (this.wizardForm && (this.wizardForm.contro...
_updateMetadata
identifier_name
actix.rs
: Self::Backend) -> Self::Backend { for handler in self.handlers.clone() { let inner = handler.inner; output = output.route(&handler.name, handler.method.clone(), move |request| { inner(request) }); } output } } impl ExtendApiBackend for a...
} } } /// Creates `actix_web::App` for the given aggregator and runtime configuration. pub(crate) fn create_app(aggregator: &ApiAggregator, runtime_config: ApiRuntimeConfig) -> App { let app_config = runtime_config.app_config; let access = runtime_config.access; let mut app = App::new(); a...
{ let handler = f.inner.handler; let actuality = f.inner.actuality; let mutability = f.mutability; let index = move |request: HttpRequest| -> FutureResponse { let handler = handler.clone(); let actuality = actuality.clone(); extract_query(request, muta...
identifier_body
actix.rs
() .header(header::LOCATION, new_location.clone()) .finish(), api::Error::NotFound(err) => HttpResponse::NotFound().body(err.to_string()), api::Error::Unauthorized => HttpResponse::Unauthorized().finish(), } } } /// Creates a `HttpResponse` object fro...
fmt
identifier_name
actix.rs
let warning_string = create_warning_header(&warning_text); response.header(header::WARNING, warning_string); } response.json(json_value) } /// Formats warning string according to the following format: /// "<warn-code> <warn-agent> \"<warn-text>\" [<warn-date>]" /// <warn-code> in our case is ...
match value {
random_line_split
seq2seq.py
_results = self.backward_rnn(inputs) if not self.merge_mode: # follow Bahdanau's paper backward_results[0] = layers.Concatenate()([forward_results[0], backward_results[0]]) final_results = backward_results else: merge_func = layers....
elif attn_method == 'dot': def f(*args): _, h, e = args h = tf.expand_dims(h, axis=-1) # ?*32*1 return tf.matmul(e, h) # ?*20*1 return f else: raise NotImplemented def __call__(self, inputs, encoder_output, enco...
enc_max_time_steps = kwargs.get('enc_max_time_steps', None) assert enc_max_time_steps fc = tf.layers.Dense(units=enc_max_time_steps) def f(*args): x = fc(tf.concat(args[:-1], axis=-1)) # ?*20 return tf.expand_dims(x, axis=-1) # ?*20*1 r...
conditional_block
seq2seq.py
(self, units, bidirectional=False, merge_mode=None): rnn_model = partial(self.gru(), units=units, return_sequences=True, return_state=True, unroll=True) self.forward_rnn = rnn_model(go_backwards=False, name='enc_forward_rnn') self.backward_rnn = rnn_model(go_backwards=True, name='enc_backward_rn...
__init__
identifier_name
seq2seq.py
_results = self.backward_rnn(inputs) if not self.merge_mode: # follow Bahdanau's paper backward_results[0] = layers.Concatenate()([forward_results[0], backward_results[0]]) final_results = backward_results else: merge_func = layers....
@staticmethod def build_attn_score_func(units, attn_method, **kwargs): # todo: share? if attn_method == 'concat': fcs = [ tf.layers.Dense(units=units, activation='tanh', name='w'), tf.layers.Dense(units=1, name='r') ] def f(*args): ...
self.rnn = self.gru()(units=units, return_state=True) self.attn_score = self.build_attn_score_func(units, attn_method, **kwargs) self.attn_combine = layers.Dense(units=units, activation='tanh', name='dec_attn_combine') self.attn_before_rnn = attn_before_rnn self.output_fc = layers.Dense(...
identifier_body
seq2seq.py
_results = self.backward_rnn(inputs) if not self.merge_mode: # follow Bahdanau's paper backward_results[0] = layers.Concatenate()([forward_results[0], backward_results[0]]) final_results = backward_results else: merge_func = layers....
print('TestSet Shape:{}'.format(X_test.shape)) build_dataloader = partial(DataLoader, batch_size=32, shuffle=False, last_batch='keep', batchify_fn=_default_batchify_fn) train_dataloader = build_dataloader(dataset=ArrayDataset(X_train, y_train)) test_dataloader = build_data...
X_test = load_data('./dataset/task8_test_input.csv') y_test = load_data('./dataset/task8_test_output.csv') X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, train_size=0.9, random_state=0) print('TrainSet Shape:{}'.format(X_train.shape))
random_line_split
mock.rs
atories: u16 = 4; pub const UnsignedPriority: u64 = 100; pub const EthNetworkId: <Runtime as Config>::NetworkId = 0; } #[derive(PartialEq, Eq, Clone, Encode, Decode, Debug)] pub struct MyTestXt<Call, Extra> { /// Signature of the extrinsic. pub signature: Option<(AccountId, Extra)>, /// Call of the...
else { Extra::pre_dispatch_unsigned(&self.call, info, len)?; None }; Ok(self.call.dispatch(maybe_who.into())) } } impl<Call, Extra> Serialize for MyTestXt<Call, Extra> where MyTestXt<Call, Extra>: Encode, { fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error> ...
{ Extra::pre_dispatch(extra, &who, &self.call, info, len)?; Some(who) }
conditional_block
mock.rs
atories: u16 = 4; pub const UnsignedPriority: u64 = 100; pub const EthNetworkId: <Runtime as Config>::NetworkId = 0; } #[derive(PartialEq, Eq, Clone, Encode, Decode, Debug)] pub struct MyTestXt<Call, Extra> { /// Signature of the extrinsic. pub signature: Option<(AccountId, Extra)>, /// Call of the...
impl sp_runtime::traits::ExtrinsicMetadata for TestExtrinsic { const VERSION: u8 = 1; type SignedExtensions = (); } construct_runtime!( pub enum Runtime where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedEx
type GetEthNetworkId = EthNetworkId; type WeightInfo = (); }
random_line_split
mock.rs
atories: u16 = 4; pub const UnsignedPriority: u64 = 100; pub const EthNetworkId: <Runtime as Config>::NetworkId = 0; } #[derive(PartialEq, Eq, Clone, Encode, Decode, Debug)] pub struct MyTestXt<Call, Extra> { /// Signature of the extrinsic. pub signature: Option<(AccountId, Extra)>, /// Call of the...
; pub type TestExtrinsic = MyTestXt<Call, MyExtra>; parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); pub const ExistentialDeposit: u1...
MyExtra
identifier_name
mock.rs
Number = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type Event = Event; type BlockHashCount = BlockHashCount; type DbWeight = (); type Version = (); type AccountData = pallet_...
{ let net_id = self.last_network_id; let multisig_account_id = bridge_multisig::Module::<Runtime>::multi_account_id( &self.root_account_id, 1, net_id as u64 + 10, ); let peers_keys = gen_peers_keys(&format!("OCW{}", net_id), peers_num.unwrap_or(4)); ...
identifier_body
lofsigrank.py
genes by burden of LOF mutations gene_scores = sorted(lof_sig_scores(lof_table, samples), key=lambda pair: pair[1]) # Step_3: Compare gene LOF scores to a simulated "background" distribution if args.permutations: # Calculate gene score percentiles orig_pctiles = nu...
gs_lookup = group_data_by_gs(data_table) for gene in my_genes: synonymous = missense_benign = missense_possibly = missense_probably = \ missense_na = frameshift = nonsense = splice = indel = 0 out_row = [gene] for sample in my_samples: normalized = [0] ...
"""Calculate gene-level mutational statistics from a table of mutations. Input: nested dict of genes -> samples -> list of mut. type, NMAF, Polyphen Output: table stratifying the mutational status of a gene in each sample. The output table has a row for each gene and a column for each sample, in which...
identifier_body
lofsigrank.py
genes by burden of LOF mutations gene_scores = sorted(lof_sig_scores(lof_table, samples), key=lambda pair: pair[1]) # Step_3: Compare gene LOF scores to a simulated "background" distribution if args.permutations: # Calculate gene score percentiles orig_pctiles = nu...
return gene_data # _____________________________________________________________________________ # Step_2: Rank genes by burden of LOF mutations def lof_sig_scores(table, samples, verbose=True): """Calculate LOF mutation burden scores for genes in the processed table.""" mut_probdam = 'Missense:Probably...
samp = row['sample'] gene = row['gene'] gene_data[gene][samp].append({ 'muttype': row['type'].strip(), 'normalized': row['Normalized'], # NMAF in the manuscript 'consequence': row['MissenseConsequence'].strip(), })
conditional_block
lofsigrank.py
genes by burden of LOF mutations gene_scores = sorted(lof_sig_scores(lof_table, samples), key=lambda pair: pair[1]) # Step_3: Compare gene LOF scores to a simulated "background" distribution if args.permutations: # Calculate gene score percentiles orig_pctiles = nu...
synonymous += 1 continue if entry['muttype'] == 'Intron': # Shouldn't be here; ignore continue if entry['muttype'] == 'Missense_Mutation': if entry['consequence'] == 'benign': ...
for sample in my_samples: normalized = [0] # Count mutations of each type for this gene and sample for entry in gs_lookup[gene][sample]: if entry['muttype'] == 'Silent':
random_line_split
lofsigrank.py
genes by burden of LOF mutations gene_scores = sorted(lof_sig_scores(lof_table, samples), key=lambda pair: pair[1]) # Step_3: Compare gene LOF scores to a simulated "background" distribution if args.permutations: # Calculate gene score percentiles orig_pctiles = nu...
(data_table): """Group relevant fields in a data table by gene and sample.""" gene_data = collections.defaultdict(lambda: collections.defaultdict(list)) for _idx, row in data_table.iterrows(): samp = row['sample'] gene = row['gene'] gene_data[gene][samp].append({ 'muttype...
group_data_by_gs
identifier_name
helpers.py
return name1 return name def get_field_attr(name): """leidt veldnaam, type en lengte af uit de definities in models.py """ # de variant met een repeating group (entiteit, dataitem) levert hier nog een probleem op. # is dat omdat er twee entiteiten in 1 scherm staan? fields = [] opts = my....
def get_object(soort, id, new=False): "return specified document object" if soort not in my.rectypes: raise Http404('Onbekend type `{}`'.format(soort)) if new: o = my.rectypes[soort]() else: try: o = my.rectypes[soort].objects.get(pk=id) except ObjectDoesNotEx...
random_line_split
helpers.py
def remove_relation(o, soort, r, srt): attr_name, multiple = get_relation(soort, srt) if multiple: o.__getattribute__(attr_name).remove(r) else: o.__setattr__(attr_name, None) o.save() def corr_naam(name): """convert name used in program to model name and back Note: all nam...
attr_name, multiple = get_relation(soort, srt) if multiple: o.__getattribute__(attr_name).add(r) else: o.__setattr__(attr_name, r) o.save()
identifier_body
helpers.py
name1 return name def get_field_attr(name): """leidt veldnaam, type en lengte af uit de definities in models.py """ # de variant met een repeating group (entiteit, dataitem) levert hier nog een probleem op. # is dat omdat er twee entiteiten in 1 scherm staan? fields = [] opts = my.rectype...
return first, second def get_names_for_type(typename): "get verbose names from model definition" return (my.rectypes[typename]._meta.verbose_name, my.rectypes[typename]._meta.verbose_name_plural, my.rectypes[typename].section) def get_projectlist(): "return list of all the p...
first = all_objects.count() second = str(_("waarvan {} {} en {} {} Actiereg").format(solved, hlp[0], working, hlp[1]))
conditional_block
helpers.py
enig gemeenschappelijke is loopen over get_fields deze werd bovendien nergens gebruikt """ fields = [] opts = my.rectypes[name]._meta for rel in opts.get_fields(): # print(rel, rel.one_to_many or rel.many_to_many) if rel.one_to_many or rel.many_to_many: try: ...
get_relation_buttons
identifier_name
js_lua_state.rs
// close. Is there a more explicit way to close event listeners, or is relying on // the GC a normal/reasonable approach? let lua = unsafe { Lua::unsafe_new_with(self.libraries) }; self.lua = Arc::new(lua) } } impl Default for LuaState { fn default() -> Self
} fn flag_into_std_lib(flag: u32) -> Option<StdLib> { const ALL_SAFE: u32 = u32::MAX - 1; match flag { #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52"))] 0x1 => Some(StdLib::COROUTINE), 0x2 => Some(StdLib::TABLE), 0x4 => Some(StdLib::IO), 0x8 => Some(S...
{ LuaState { libraries: StdLib::ALL_SAFE, lua: Arc::new(Lua::new_with(StdLib::ALL_SAFE).unwrap()), } }
identifier_body
js_lua_state.rs
// close. Is there a more explicit way to close event listeners, or is relying on // the GC a normal/reasonable approach? let lua = unsafe { Lua::unsafe_new_with(self.libraries) }; self.lua = Arc::new(lua) } } impl Default for LuaState { fn default() -> Self { LuaState ...
let libraries = build_libraries_option(cx, libs)?; // Because we're allowing the end user to dynamically choose their libraries, // we're using the unsafe call in case they include `debug`. We need to notify // the end user in the documentation about the caveats of `debug`. let lua = unsafe { ...
let libs = options.get(&mut cx, libraries_key)?;
random_line_split
js_lua_state.rs
// close. Is there a more explicit way to close event listeners, or is relying on // the GC a normal/reasonable approach? let lua = unsafe { Lua::unsafe_new_with(self.libraries) }; self.lua = Arc::new(lua) } } impl Default for LuaState { fn default() -> Self { LuaState ...
( mut cx: MethodContext<JsLuaState>, code: String, name: Option<String>, ) -> JsResult<JsValue> { let this = cx.this(); let lua: &Lua = { let guard = cx.lock(); let state = this.borrow(&guard); &state.lua.clone() }; match lua_execution::do_string_sync(lua, code, name...
do_string_sync
identifier_name
controllerserver.go
(ctx context.Context, req *csi.CreateVolumeRequest) (*csi.CreateVolumeResponse, error) { if err := cs.validateControllerServiceRequest(csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME); err != nil { glog.V(3).Infof("invalid create volume req: %v", req) return nil, err } // Check arguments if len(req.Ge...
CreateVolume
identifier_name
controllerserver.go
Capacity) } topologies := []*csi.Topology{ &csi.Topology{ Segments: map[string]string{TopologyKeyNode: cs.nodeID}, }, } // Need to check for already existing volume name, and if found // check for the requested capacity and already allocated capacity if exVol, err := getVolumeByName(req.GetName()); err =...
csi.ControllerServiceCapability_RPC_VOLUME_CONDITION,
random_line_split
controllerserver.go
also need to check that the other // fields in VolumeCapabilities are sane. The check above is // just enough to pass the "[Testpattern: Dynamic PV (block // volmode)] volumeMode should fail in binding dynamic // provisioned PV to PVC" storage E2E test. if accessTypeBlock && accessTypeMount { return nil, statu...
{ panic("implement me") }
identifier_body
controllerserver.go
"Name missing in request") } caps := req.GetVolumeCapabilities() if caps == nil { return nil, status.Error(codes.InvalidArgument, "Volume Capabilities missing in request") } // Keep a record of the requested access types. var accessTypeMount, accessTypeBlock bool for _, ca := range caps { if ca.GetBlock() ...
} // A real driver would also need to check that the other // fields in VolumeCapabilities are sane. The check above is // just enough to pass the "[Testpattern: Dynamic PV (block // volmode)] volumeMode should fail in binding dynamic // provisioned PV to PVC" storage E2E test. if accessTypeBlock && accessTyp...
{ accessTypeMount = true }
conditional_block
AwardEditModal.js
.create() export default class extends React.Component { state = { fileList :[], type:4 } getFile = (fileList) => { this.setState({ fileList }) } onCancel =()=>{ this.onProbabilityChange(this.props.row.probability) this.props.form.rese...
<FormItem label="奖品名称" {...formItemLayout}> {getFieldDecorator('name', { rules:[ {required:true,message:'请输入奖品名称'} ] })( <HzInput ...
)} </FormItem>: null}
random_line_split
AwardEditModal.js
if(!row.type){ row.type = 4 row.name = '谢谢参与' } this.setState({ type:row.type },()=>{ this.props.form.setFieldsValue(row) }) let {img_path} = this.props.row if(!img_pat...
niup.c
identifier_name
AwardEditModal.js
.create() export default class extends React.Component { state = { fileList :[], type:4 } getFile = (fileList) => { this.setState({ fileList }) } onCancel =()=>{ this.onProbabilityChange(this.props.row.probability) this.props.form.rese...
} } onProbabilityChange = (value) =>{ let {row,probabilityChange} = this.props let o = {...row} o.probability = value probabilityChange && probabilityChange(o) } typeChange=(type)=>{ this.props.form.resetFields() this.onProbabilityChange(this.prop...
callback(`中奖概率之和不能大于100`) }else{ callback()
conditional_block
PublicFunction.go
Only: false, MaxAge: maxAge} r.AddCookie(uid_cookie) } func GetTotal(price string, num string) string { fPrice, err1 := strconv.ParseFloat(price, 64) fnum, err2 := strconv.ParseFloat(num, 64) if err1 == nil && err2 == nil { return fmt.Sprintf("%1.2f", fPrice*fnum) } return "" } func RemovePath(path string...
e()会报错的 CreatePath(curdir + "/" + path + "/") } var ( status int err error ) defer func() { if nil != err { http.Error(res, err.Error(), status) } }() // parse request const _24K = (1 << 20) * 24 if err = req.ParseMultipartForm(_24K); nil != err { status = http.StatusInternalSe...
ng, userid string, typeid string) string { //Log("upload picture Task is running...") curdir := GetCurDir() var fileNames string = "#" if req.Method == "GET" { } else { ff, errr := os.Open(curdir + "/" + path + "/") if errr != nil && os.IsNotExist(errr) { Log(ff, ""+path+"文件不存在,创建") //为什么打印nil 是这样的如果file不...
identifier_body
PublicFunction.go
} for _, address := range addrs { // check the address type and if it is not a loopback the display it if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipnet.IP.To4() != nil { ipstr := ipnet.IP.String() index := strings.Index(ipstr, "127.0") if index > -1 { continue ...
Log("realip=" +
conditional_block
PublicFunction.go
string { var str string = "##" sorted_keys := make([]int, 0) for k, _ := range MapList { sorted_keys = append(sorted_keys, k) } // sort 'string' key in increasing order sort.Ints(sorted_keys) for _, k := range sorted_keys { //fmt.Printf("k=%v, v=%v\n", k, MapList[k]) jsonStr, err := json.Marshal(MapLi...
var tmp int32 binary.Read(bytesBuffer, binary.BigEndian, &tmp) return int(tmp) }
random_line_split
PublicFunction.go
} } fileNames = strings.Replace(fileNames, "#,", "", -1) fileNames = strings.Replace(fileNames, "#", "", -1) return fileNames } func SaveConfigTask(res http.ResponseWriter, req *http.Request, path string, filename string) string { //Log("upload picture Task is running...") curdir := GetCurDir() var fileNames st...
rid\": \"25\", \"touse
identifier_name
bot.js
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // bot.js is your main bot dialog entry point for handling activity types // Import required Bot Builder const { ActionTypes, ActivityTypes, CardFactory } = require('botbuilder'); const { LuisRecognizer } = require('botbui...
(step) { //console.log(step); // We do not need to store the token in the bot. When we need the token we can // send another prompt. If the token is valid the user will not need to log back in. // The token will be available in the Result property of the task. const tokenResponse = s...
processStep
identifier_name