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 |
|---|---|---|---|---|
term_gui.rs | // Copyright (c) The Swiboe development team. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE.txt
// in the project root for license information.
#[macro_use]
extern crate clap;
extern crate rustbox;
extern crate serde_json;
extern crate subsequence_match;
extern crate swiboe;
exter... | {
let options = parse_options();
let mut gui = TerminalGui::new(&options).unwrap();
while gui.handle_events().unwrap() {
gui.draw();
}
} | identifier_body | |
term_gui.rs | // Copyright (c) The Swiboe development team. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE.txt
// in the project root for license information.
#[macro_use]
extern crate clap;
extern crate rustbox;
extern crate serde_json;
extern crate subsequence_match;
extern crate swiboe;
exter... | (&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 | # -*- coding: utf-8 -*-
# Author: kelvinBen
# Github: https://github.com/kelvinBen/HistoricalArticlesToPdf
import os
import re
import math
import time
import json
import shutil
import psutil
import logging
import requests
from PIL import Image
from queue import Queue
from http import cookiejar
import urllib.parse as u... | 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 | # -*- coding: utf-8 -*-
# Author: kelvinBen
# Github: https://github.com/kelvinBen/HistoricalArticlesToPdf
import os
import re
import math
import time
import json
import shutil
import psutil
import logging
import requests
from PIL import Image
from queue import Queue
from http import cookiejar
import urllib.parse as u... | f.__head__(headers))
else:
resp = session.post(url = url, data = data, headers = self.__head__(headers))
if resp.status_code != 200:
log.error("网络异常或者错误:"+str(resp.status_code))
return session,None
if flag:
content = resp.text
if n... | 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 | # -*- coding: utf-8 -*-
# Author: kelvinBen
# Github: https://github.com/kelvinBen/HistoricalArticlesToPdf
import os
import re
import math
import time
import json
import shutil
import psutil
import logging
import requests
from PIL import Image
from queue import Queue
from http import cookiejar
import urllib.parse as u... | if method =='get':
resp = session.get(url=url,params=data,headers=self.__head__(headers),stream=stream)
else:
resp = session.post(url=url,data=data,headers=self.__head__(headers),stream=stream)
if resp.status_code == 200:
with open(path, 'wb+') as f:
... | 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 | # -*- coding: utf-8 -*-
# Author: kelvinBen
# Github: https://github.com/kelvinBen/HistoricalArticlesToPdf
import os
import re
import math
import time
import json
import shutil
import psutil
import logging
import requests
from PIL import Image
from queue import Queue
from http import cookiejar
import urllib.parse as u... | 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 | use std::{
cmp,
convert::TryInto,
io::{self, Write},
};
use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};
use cgmath::prelude::*;
use crate::{
prelude::*,
io::{PropKind, Error, ErrorKind},
};
use super::{Encoding, RawTriangle};
// ----------------------------------------------------------... | () -> 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 | use std::{
cmp,
convert::TryInto,
io::{self, Write},
};
use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};
use cgmath::prelude::*;
use crate::{
prelude::*,
io::{PropKind, Error, ErrorKind},
};
use super::{Encoding, RawTriangle};
// ----------------------------------------------------------... |
#[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 std::{
cmp,
convert::TryInto,
io::{self, Write},
}; | 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 | use std::{
cmp,
convert::TryInto,
io::{self, Write},
};
use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};
use cgmath::prelude::*;
use crate::{
prelude::*,
io::{PropKind, Error, ErrorKind},
};
use super::{Encoding, RawTriangle};
// ----------------------------------------------------------... |
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 | # -*- coding: utf-8 -*-
from . import op
Jh_BlockSize = 64
Jh_StateSize = 32
JH_HX = 8
JH_HY = 4
IV512 = [
(0x6fd14b96), (0x3e00aa17), (0x636a2e05), (0x7a15d543),
(0x8a225e8d), (0x0c97ef0b), (0xe9341259), (0xf2b3c361),
(0x891da0c1), (0x536f801e), (0x2aa9056b), (0xea2b6d80),
(0x588eccdb), (0x2075b... | (h, r, ro):
S(h[0], h[2], h[4], h[6], Ceven, r)
S(h[1], h[3], h[5], h[7], Codd, r)
L(h[0], h[2], h[4], h[6], h[1], h[3], h[5], h[7])
W(ro, h[1])
W(ro, h[3])
W(ro, h[5])
W(ro, h[7])
def READ_STATE(h, state):
h[0][3] = state[0]
h[0][2] = state[1]
h[0][1] = state[2]
h[0][0] = ... | SL | identifier_name |
jh.py | # -*- coding: utf-8 -*-
from . import op
Jh_BlockSize = 64
Jh_StateSize = 32
JH_HX = 8
JH_HY = 4
IV512 = [
(0x6fd14b96), (0x3e00aa17), (0x636a2e05), (0x7a15d543),
(0x8a225e8d), (0x0c97ef0b), (0xe9341259), (0xf2b3c361),
(0x891da0c1), (0x536f801e), (0x2aa9056b), (0xea2b6d80),
(0x588eccdb), (0x2075b... | state[9] = h[2][2]
state[10] = h[2][1]
state[11] = h[2][0]
state[12] = h[3][3]
state[13] = h[3][2]
state[14] = h[3][1]
state[15] = h[3][0]
state[16] = h[4][3]
state[17] = h[4][2]
state[18] = h[4][1]
state[19] = h[4][0]
state[20] = h[5][3]
state[21] = h[5][2]
state... | 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 | # -*- coding: utf-8 -*-
from . import op
Jh_BlockSize = 64
Jh_StateSize = 32
JH_HX = 8
JH_HY = 4
IV512 = [
(0x6fd14b96), (0x3e00aa17), (0x636a2e05), (0x7a15d543),
(0x8a225e8d), (0x0c97ef0b), (0xe9341259), (0xf2b3c361),
(0x891da0c1), (0x536f801e), (0x2aa9056b), (0xea2b6d80),
(0x588eccdb), (0x2075b... |
WRITE_STATE(V, ctx['state'])
ctx['ptr'] = ptr
def jh_close(ctx):
buf = bytearray(128)
l = [None] * 4
buf[0] = 0x80
ptr = ctx['ptr']
if ptr is 0:
numz = 47
else:
numz = 111 - ptr
buf[1:1+numz] = [0] * numz
blockCountLow = ctx['blockCountLow']
blockCountHigh ... | 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 | # -*- coding: utf-8 -*-
from . import op
Jh_BlockSize = 64
Jh_StateSize = 32
JH_HX = 8
JH_HY = 4
IV512 = [
(0x6fd14b96), (0x3e00aa17), (0x636a2e05), (0x7a15d543),
(0x8a225e8d), (0x0c97ef0b), (0xe9341259), (0xf2b3c361),
(0x891da0c1), (0x536f801e), (0x2aa9056b), (0xea2b6d80),
(0x588eccdb), (0x2075b... |
def W(ro, x):
if ro == 0:
return Wz(x, (0x55555555), 1)
elif ro == 1:
return Wz(x, (0x33333333), 2)
elif ro == 2:
return Wz(x, (0x0F0F0F0F), 4)
elif ro == 3:
return Wz(x, (0x00FF00FF), 8)
elif ro == 4:
return Wz(x, (0x0000FFFF), 16)
elif ro == 5:
... | 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 | //! This module contains functionality for parsing a regular expression into the intermediate
//! representation in repr.rs (from which it is compiled into a state graph), and optimizing that
//! intermediate representation.
#![allow(dead_code)]
use std::iter::FromIterator;
use std::ops::{Index, Range, RangeFull};
us... |
#[test]
fn test_parse_res() {
let case1 = (
"a(Bcd)e",
Pattern::Concat(vec![
Pattern::Char('a'),
Pattern::Submatch(Box::new(Pattern::Concat(vec![
Pattern::Char('B'),
Pattern::Char('c'),
... | {
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 | //! This module contains functionality for parsing a regular expression into the intermediate
//! representation in repr.rs (from which it is compiled into a state graph), and optimizing that
//! intermediate representation.
#![allow(dead_code)]
use std::iter::FromIterator;
use std::ops::{Index, Range, RangeFull};
us... | } 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 | //! This module contains functionality for parsing a regular expression into the intermediate
//! representation in repr.rs (from which it is compiled into a state graph), and optimizing that
//! intermediate representation.
#![allow(dead_code)]
use std::iter::FromIterator;
use std::ops::{Index, Range, RangeFull};
us... | <'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 | '''
BoardGameGeek Regression Prediction and Recommendation
CAPP 122 Final Project
Author: Syeda Jaisha
The following script runs a regression using data from BoardGameGeek (BGG) and
uses it to predict BGG rating and number of user reviews/ratings received,
for a game designed by our user as well as to make recommend... | '''
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 | '''
BoardGameGeek Regression Prediction and Recommendation
CAPP 122 Final Project
Author: Syeda Jaisha
The following script runs a regression using data from BoardGameGeek (BGG) and
uses it to predict BGG rating and number of user reviews/ratings received,
for a game designed by our user as well as to make recommend... | #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 | '''
BoardGameGeek Regression Prediction and Recommendation
CAPP 122 Final Project
Author: Syeda Jaisha
The following script runs a regression using data from BoardGameGeek (BGG) and
uses it to predict BGG rating and number of user reviews/ratings received,
for a game designed by our user as well as to make recommend... |
elif field == 'Type':
current_type_coefs = {}
game_type_coefs = {}
for game_type in django_to_local_cols['Type']:
if game_type in input_dict.values():
current_type_coefs[beta[game_type]] = game_type
else:
... | 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 | '''
BoardGameGeek Regression Prediction and Recommendation
CAPP 122 Final Project
Author: Syeda Jaisha
The following script runs a regression using data from BoardGameGeek (BGG) and
uses it to predict BGG rating and number of user reviews/ratings received,
for a game designed by our user as well as to make recommend... | (X, y, beta):
'''
Calculate R_sqauared for a regression model
Inputs:
X (pandas DataFrame): X matrix
y (pandas Series): y vector
beta(pandas DataFrame): beta vector
Output: (float) R_squared
'''
yhat = apply_beta(beta, X)
R2 = 1 - (np.sum((y - yhat)**2) / np.sum((y ... | calculate_R2 | identifier_name |
iggo.go | package main
import (
"encoding/json"
"fmt"
"github.com/dustin/go-humanize"
"github.com/gorilla/feeds"
"github.com/jacoduplessis/simplejson"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"time"
)
var templateFuncs = template.FuncMap{
"sizemax": sizemax,
"linkify"... |
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 | package main
import (
"encoding/json"
"fmt"
"github.com/dustin/go-humanize"
"github.com/gorilla/feeds"
"github.com/jacoduplessis/simplejson"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"time"
)
var templateFuncs = template.FuncMap{
"sizemax": sizemax,
"linkify"... |
func tagFetcher(r *http.Request) (interface{}, error) {
return GetTag(r)
}
func main() {
setupTemplates()
http.Handle("/user/", makeHandler(userFetcher, "user"))
http.Handle("/post/", makeHandler(postFetcher, "post"))
http.Handle("/tag/", makeHandler(tagFetcher, "tag"))
http.Handle("/static/", http.StripPrefix... | {
return GetPost(r)
} | identifier_body |
iggo.go | package main
import (
"encoding/json"
"fmt"
"github.com/dustin/go-humanize"
"github.com/gorilla/feeds"
"github.com/jacoduplessis/simplejson"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"time"
)
var templateFuncs = template.FuncMap{
"sizemax": sizemax,
"linkify"... | () appHandler {
return func(w http.ResponseWriter, r *http.Request) *appError {
q := r.FormValue("q")
if q != "" {
sr, _ := getSearchResult(q)
sr.Query = q
if r.URL.Query().Get("format") == "json" {
return renderJSON(w, &sr)
}
return renderTemplate(w, "search", sr)
}
return renderTemplate(... | makeIndex | identifier_name |
iggo.go | package main
import (
"encoding/json"
"fmt"
"github.com/dustin/go-humanize"
"github.com/gorilla/feeds"
"github.com/jacoduplessis/simplejson"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"time"
)
var templateFuncs = template.FuncMap{
"sizemax": sizemax,
"linkify"... |
func getListenAddr() string {
if port := os.Getenv("PORT"); port != "" {
return ":" + port
}
if addr := os.Getenv("LISTEN_ADDR"); addr != "" {
return addr
}
return "127.0.0.1:8000"
}
func userFetcher(r *http.Request) (interface{}, error) {
return GetUser(r)
}
func postFetcher(r *http.Request) (interface{},... |
return renderTemplate(w, templateKey, data)
}
} | random_line_split |
fib.rs | //! Fibonacci Heap (decent impl)
//!
use std::{
borrow::Borrow,
cmp::Ordering::*,
collections::{hash_map::Entry::*, HashMap},
fmt::{Debug, Display},
hash::Hash, mem::replace,
};
use common::hashmap;
use coll::*;
////////////////////////////////////////////////////////////////////////////////
//... | (&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 | //! Fibonacci Heap (decent impl)
//!
use std::{
borrow::Borrow,
cmp::Ordering::*,
collections::{hash_map::Entry::*, HashMap},
fmt::{Debug, Display},
hash::Hash, mem::replace,
};
use common::hashmap;
use coll::*;
////////////////////////////////////////////////////////////////////////////////
//... |
/// 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 | //! Fibonacci Heap (decent impl)
//!
use std::{
borrow::Borrow,
cmp::Ordering::*,
collections::{hash_map::Entry::*, HashMap},
fmt::{Debug, Display},
hash::Hash, mem::replace,
};
use common::hashmap;
use coll::*;
////////////////////////////////////////////////////////////////////////////////
//... | }
writeln!(f, "{}>> end <<{}", "-".repeat(28), "-".repeat(28))?;
Ok(())
}
}
impl<I: Ord + Hash + Clone + Debug, T: Ord + Clone + Debug> Clone for FibHeap<I, T> {
fn clone(&self) -> Self {
let len = self.len;
let rcnt = self.rcnt;
let mut nodes = HashMap::new();
... | (sib.is_some());
sib = right!(sib);
| conditional_block |
fib.rs | //! Fibonacci Heap (decent impl)
//!
use std::{
borrow::Borrow,
cmp::Ordering::*,
collections::{hash_map::Entry::*, HashMap},
fmt::{Debug, Display},
hash::Hash, mem::replace,
};
use common::hashmap;
use coll::*;
////////////////////////////////////////////////////////////////////////////////
//... | Self {
len,
rcnt,
min,
nodes,
}
}
}
#[cfg(test)]
mod tests {
use super::{ FibHeap, super::* };
use common::random;
#[ignore = "for debug"]
#[test]
fn debug_fib_heap() {}
#[test]
fn test_fibheap_fixeddata() {
... | min = Node::none();
}
| random_line_split |
main.rs | use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
const COLLECTED_ORE: u64 = 1000000000000;
#[derive(Debug, Eq, PartialEq)]
struct Reaction {
output: (String, u64),
ingredients: Vec<(String, u64)>,
}
type ReactionMap = HashMap<String, Reaction>;
fn calc_ore(reactions: &Rea... |
fn parse_chemical(chemical: &str) -> (String, u64) {
let mut iter = chemical.split_whitespace();
let count = iter.next().unwrap().parse::<u64>().unwrap();
let chem = iter.next().unwrap();
(String::from(chem), count)
}
fn parse_reactions(strs: &[String]) -> ReactionMap {
let mut reactions = HashM... | {
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 | use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
const COLLECTED_ORE: u64 = 1000000000000;
#[derive(Debug, Eq, PartialEq)]
struct Reaction {
output: (String, u64),
ingredients: Vec<(String, u64)>,
}
type ReactionMap = HashMap<String, Reaction>;
fn calc_ore(reactions: &Rea... | () {
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 | use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
const COLLECTED_ORE: u64 = 1000000000000;
#[derive(Debug, Eq, PartialEq)]
struct Reaction {
output: (String, u64),
ingredients: Vec<(String, u64)>,
}
type ReactionMap = HashMap<String, Reaction>;
fn calc_ore(reactions: &Rea... | }
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 | use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
const COLLECTED_ORE: u64 = 1000000000000;
#[derive(Debug, Eq, PartialEq)]
struct Reaction {
output: (String, u64),
ingredients: Vec<(String, u64)>,
}
type ReactionMap = HashMap<String, Reaction>;
fn calc_ore(reactions: &Rea... |
}
// 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 | /**
* $time.js
* @require loot
*/
(function() {
// date/time -------------------------------------------------------
function $now() {
return new Date().getTime();
}
/* $timeAgo
/*
* Javascript Humane Dates
* Copyright (c) 2008 Dean Landolt (deanlandolt.com)
* Re-write by Zach Leatherman (zachleat.... | oot.extend({
$now: $now,
$date: $dateFormat,
$timeAgo: $timeAgo,
$timer: $timer,
$secondsToTime: $secondsToTime,
$millisToTime: $millisToTime
});
}()); | return $secondsToTime(parseInt(ms, 10)/1000);
}
l | identifier_body |
$time.js | /**
* $time.js
* @require loot
*/
(function() {
// date/time -------------------------------------------------------
function $now() {
return new Date().getTime();
}
/* $timeAgo
/*
* Javascript Humane Dates
* Copyright (c) 2008 Dean Landolt (deanlandolt.com)
* Re-write by Zach Leatherman (zachleat.... | (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 | /**
* $time.js
* @require loot
*/
(function() {
// date/time -------------------------------------------------------
function $now() {
return new Date().getTime();
}
/* $timeAgo
/*
* Javascript Humane Dates
* Copyright (c) 2008 Dean Landolt (deanlandolt.com)
* Re-write by Zach Leatherman (zachleat.... | l: pad(L, 3),
L: pad(L > 99 ? Math.round(L / 10) : L),
t: H < 12 ? "a" : "p",
tt: H < 12 ? "am" : "pm",
T: H < 12 ? "A" : "P",
TT: H < 12 ? "AM" : "PM",
Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
o: (o > 0 ? "-... | M: M,
MM: pad(M),
s: s,
ss: pad(s), | random_line_split |
$time.js | /**
* $time.js
* @require loot
*/
(function() {
// date/time -------------------------------------------------------
function $now() {
return new Date().getTime();
}
/* $timeAgo
/*
* Javascript Humane Dates
* Copyright (c) 2008 Dean Landolt (deanlandolt.com)
* Re-write by Zach Leatherman (zachleat.... |
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 | // Copyright (c) The XPeer Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module implements an instantiation of a verifiable random function known as
//! [ECVRF-ED25519-SHA512-TAI](https://tools.ietf.org/html/draft-irtf-cfrg-vrf-04).
//!
//! # Examples
//!
//! ```
//! use nextgen_crypto::{traits::Un... |
}
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 | // Copyright (c) The XPeer Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module implements an instantiation of a verifiable random function known as
//! [ECVRF-ED25519-SHA512-TAI](https://tools.ietf.org/html/draft-irtf-cfrg-vrf-04).
//!
//! # Examples
//!
//! ```
//! use nextgen_crypto::{traits::Un... | .result()[..],
);
k_buf
}
pub(super) fn hash_points(points: &[EdwardsPoint]) -> ed25519_Scalar {
let mut result = [0u8; 32];
let mut hash = Sha512::new().chain(&[SUITE, TWO]);
for point in points.iter() {
hash = hash.chain(point.compress().to_bytes());
}
result[..16].cop... | random_line_split | |
ecvrf.rs | // Copyright (c) The XPeer Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module implements an instantiation of a verifiable random function known as
//! [ECVRF-ED25519-SHA512-TAI](https://tools.ietf.org/html/draft-irtf-cfrg-vrf-04).
//!
//! # Examples
//!
//! ```
//! use nextgen_crypto::{traits::Un... | 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 | // Copyright (c) The XPeer Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module implements an instantiation of a verifiable random function known as
//! [ECVRF-ED25519-SHA512-TAI](https://tools.ietf.org/html/draft-irtf-cfrg-vrf-04).
//!
//! # Examples
//!
//! ```
//! use nextgen_crypto::{traits::Un... | (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 | /*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | else if !ok {
return fmt.Errorf("failed to merge %q", headSHA)
}
}
return nil
}
// Am tries to apply the patch in the given path into the current branch
// by performing a three-way merge (similar to git cherry-pick). It returns
// an error if the patch cannot be applied.
func (i *interactor) Am(path string) e... | {
return err
} | conditional_block |
interactor.go | /*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
// RemoteUpdate fetches all updates from the remote.
func (i *interactor) RemoteUpdate() error {
i.logger.Info("Updating from remote")
if out, err := i.executor.Run("remote", "update", "--prune"); err != nil {
return fmt.Errorf("error updating: %w %v", err, string(out))
}
return nil
}
// Fetch fetches all upda... | {
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 | /*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | (commitlike string) (string, error) {
i.logger.Infof("Getting the commit sha for commitlike %s", commitlike)
out, err := i.executor.Run("show-ref", "-s", commitlike)
if err != nil {
return "", fmt.Errorf("failed to get commit sha for commitlike %s: %w", commitlike, err)
}
return strings.TrimSpace(string(out)), n... | ShowRef | identifier_name |
interactor.go | /*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | }
return nil
}
// Am tries to apply the patch in the given path into the current branch
// by performing a three-way merge (similar to git cherry-pick). It returns
// an error if the patch cannot be applied.
func (i *interactor) Am(path string) error {
i.logger.Infof("Applying patch at %s", path)
out, err := i.exe... | return fmt.Errorf("failed to merge %q", headSHA)
} | random_line_split |
eulerlib.py | import math
import time
import quadratic
import random
def time_it(f, args=None):
t0 = time.time()
print('--- Timed execution for {} ----------------'.format(f.__name__))
print('Running...')
result = f(*args) if args is not None else f()
print('Solution is {}'.format(result))
t1 = time.time()
... | 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 | import math
import time
import quadratic
import random
def time_it(f, args=None):
t0 = time.time()
print('--- Timed execution for {} ----------------'.format(f.__name__))
print('Running...')
result = f(*args) if args is not None else f()
print('Solution is {}'.format(result))
t1 = time.time()
... | return i
def next_permutation(P):
"""
For any given permutation P, give the next permutation.
If there is no next permutation, P will be returned.
:param P:
:return:
"""
n = len(P)
# Find the first index with the bigger neighbour.
i = _first_index_with_bigger_neighbour(P)
... | -= 1
| conditional_block |
eulerlib.py | import math
import time
import quadratic
import random
def time_it(f, args=None):
t0 = time.time()
print('--- Timed execution for {} ----------------'.format(f.__name__))
print('Running...')
result = f(*args) if args is not None else f()
print('Solution is {}'.format(result))
t1 = time.time()
... | Returns the union of all sets in S.
:param S:
:return:
"""
res = set()
for s in S:
res |= s
return res
def intersect_sets(S):
"""
Returns the intersection of all sets in S.
:param S:
:return:
"""
res = S[0]
for s in S:
res &= s
return res
d... | def union_sets(S):
""" | random_line_split |
eulerlib.py | import math
import time
import quadratic
import random
def time_it(f, args=None):
t0 = time.time()
print('--- Timed execution for {} ----------------'.format(f.__name__))
print('Running...')
result = f(*args) if args is not None else f()
print('Solution is {}'.format(result))
t1 = time.time()
... |
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 | """Constant folding optimisation for bytecode.
This optimisation adds a new pseudo-opcode, LOAD_FOLDED_CONST, which encodes the
type of a complex literal constant in its `arg` field, in a "typestruct" format
described below. There is a corresponding function, build_folded_type, which
constructs a vm type from the enco... | elts = const.elements
return collect_tuple(state, elts)
elif tag == 'map':
return collect_map(state, params, const.elements)
else:
assert False, ('Unexpected type tag:', const.typ) | elts = tuple(typeconst(t) for t in params)
else: | random_line_split |
constant_folding.py | """Constant folding optimisation for bytecode.
This optimisation adds a new pseudo-opcode, LOAD_FOLDED_CONST, which encodes the
type of a complex literal constant in its `arg` field, in a "typestruct" format
described below. There is a corresponding function, build_folded_type, which
constructs a vm type from the enco... |
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 | """Constant folding optimisation for bytecode.
This optimisation adds a new pseudo-opcode, LOAD_FOLDED_CONST, which encodes the
type of a complex literal constant in its `arg` field, in a "typestruct" format
described below. There is a corresponding function, build_folded_type, which
constructs a vm type from the enco... |
elif tag == 'map':
k, v = vals
return (tag, (union(k), union(v)))
else:
vals, = vals # pylint: disable=self-assigning-variable
return (tag, union(vals))
else:
return tuple(expand(tup))
def optimize(code):
"""Fold all constant literals in the bytecode into LOAD_FOLDED_CONST op... | params = tuple(expand(vals))
return (tag, params) | conditional_block |
constant_folding.py | """Constant folding optimisation for bytecode.
This optimisation adds a new pseudo-opcode, LOAD_FOLDED_CONST, which encodes the
type of a complex literal constant in its `arg` field, in a "typestruct" format
described below. There is a corresponding function, build_folded_type, which
constructs a vm type from the enco... | (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 | use crate::Result;
use pom::char_class::{alpha, alphanum, multispace};
use pom::parser::*;
use std::str::FromStr;
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
#[derive(Debug, Clone, PartialEq)]
pub struct StateMachine {
pub name: String,
pub states: Vec<State>,
pub accept_states: Vec<... | <'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 | use crate::Result;
use pom::char_class::{alpha, alphanum, multispace};
use pom::parser::*;
use std::str::FromStr;
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
#[derive(Debug, Clone, PartialEq)]
pub struct StateMachine {
pub name: String,
pub states: Vec<State>,
pub accept_states: Vec<... |
#[test]
fn line_counter_works() {
let file_path_str = "assets/fsml/simple-state-machine.fsml";
let byte_vec: Vec<u8> = std::fs::read(file_path_str).unwrap();
let actual = count_lines(&byte_vec);
assert_eq!(12, actual);
}
#[test]
fn parse_state_machine_file() {
... | {
let line_parser = (to_eol() - eol()).repeat(0..);
let parse_result = line_parser.parse(byte_slice).unwrap();
parse_result.len()
} | identifier_body |
parser.rs | use crate::Result;
use pom::char_class::{alpha, alphanum, multispace};
use pom::parser::*;
use std::str::FromStr;
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
#[derive(Debug, Clone, PartialEq)]
pub struct StateMachine {
pub name: String,
pub states: Vec<State>,
pub accept_states: Vec<... |
Err(e) => panic!("{}", e),
};
println!("{:?}", parse_result);
}
}
| {
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 | use crate::Result;
use pom::char_class::{alpha, alphanum, multispace};
use pom::parser::*;
use std::str::FromStr;
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
#[derive(Debug, Clone, PartialEq)]
pub struct StateMachine {
pub name: String,
pub states: Vec<State>,
pub accept_states: Vec<... | 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 | // (A,X,E,R,S)
//
// Lizzie Borden took an axe
// And gave her mother forty whacks.
// When she saw what she had done,
// She gave her father forty-one.
//
#![feature(struct_variant)]
#![allow(dead_code)]
#![allow(uppercase_variables)]
#![allow(unused_variable)]
#![allow(unused_imports)]
//#![allow(visible_private_typ... | 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 | // (A,X,E,R,S)
//
// Lizzie Borden took an axe
// And gave her mother forty whacks.
// When she saw what she had done,
// She gave her father forty-one.
//
#![feature(struct_variant)]
#![allow(dead_code)]
#![allow(uppercase_variables)]
#![allow(unused_variable)]
#![allow(unused_imports)]
//#![allow(visible_private_typ... | e(I.vars, E, I.body); X = I.next
CLOSE {vars:ref vars, body:ref body, k:ref k} => {
let a = Closure { params:vars.clone(), env:E.clone(), body:body.clone() };
A = OClosure(a);
k.clone()
},
// case TEST : I: TEST ; X = (A == true) ? I.thenc : I.elsec
TEST {kthen:ref kthen, kelse:ref kelse} => {
le... | case CLOSE : I: CLOSE ; A = Closur | conditional_block |
lib.rs | // (A,X,E,R,S)
//
// Lizzie Borden took an axe
// And gave her mother forty whacks.
// When she saw what she had done,
// She gave her father forty-one.
//
#![feature(struct_variant)]
#![allow(dead_code)]
#![allow(uppercase_variables)]
#![allow(unused_variable)]
#![allow(unused_imports)]
//#![allow(visible_private_typ... | 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 | //! NanoVG is small antialiased vector graphics rendering library with a lean
//! API modeled after the HTML5 Canvas API. It can be used to draw gauge
//! instruments in MSFS. See `Gauge::create_nanovg`.
use crate::sys;
type Result = std::result::Result<(), Box<dyn std::error::Error>>;
/// A NanoVG render context.
p... | (self) -> sys::NVGwinding {
match self {
Direction::Clockwise => sys::NVGwinding_NVG_CW,
Direction::CounterClockwise => sys::NVGwinding_NVG_CCW,
}
}
}
#[derive(Debug)]
#[doc(hidden)]
pub enum PaintOrColor {
Paint(Paint),
Color(Color),
}
impl From<Paint> for PaintOrC... | to_sys | identifier_name |
nvg.rs | //! NanoVG is small antialiased vector graphics rendering library with a lean
//! API modeled after the HTML5 Canvas API. It can be used to draw gauge
//! instruments in MSFS. See `Gauge::create_nanovg`.
use crate::sys;
type Result = std::result::Result<(), Box<dyn std::error::Error>>;
/// A NanoVG render context.
p... | pub fn stroke<T: Into<PaintOrColor>>(mut self, stroke: T) -> Self {
self.stroke = Some(stroke.into());
self
}
/// Set the fill of this style.
pub fn fill<T: Into<PaintOrColor>>(mut self, fill: T) -> Self {
self.fill = Some(fill.into());
self
}
}
/// Colors in NanoVG... | }
impl Style {
/// Set the stroke of this style. | random_line_split |
deployment-center-state-manager.ts | import { ReplaySubject } from 'rxjs/ReplaySubject';
import { FormGroup, FormControl } from '@angular/forms';
import { WizardForm, SourceSettings } from './deployment-center-setup-models';
import { Observable } from 'rxjs/Observable';
import { CacheService } from '../../../../shared/services/cache.service';
import { Arm... |
private _deployKudu() {
const payload = this.wizardValues.sourceSettings;
payload.isGitHubAction = this.wizardValues.buildProvider === 'github';
payload.isManualIntegration = this.wizardValues.sourceProvider === 'external';
if (this.wizardValues.sourceProvider === 'localgit') {
return this._... | {
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 | import { ReplaySubject } from 'rxjs/ReplaySubject';
import { FormGroup, FormControl } from '@angular/forms';
import { WizardForm, SourceSettings } from './deployment-center-setup-models';
import { Observable } from 'rxjs/Observable';
import { CacheService } from '../../../../shared/services/cache.service';
import { Arm... | else {
return Observable.throw(r);
}
})
.switchMap(r => {
if (r && r.status === 200) {
return this._patchSiteConfigForGitHubAction();
} else {
return Observable.throw(r);
}
})
.catch(r => Observable.throw(r))
.map(r => r.json()... | {
return this._updateMetadata(r.result.properties, sourceSettingsPayload);
} | conditional_block |
deployment-center-state-manager.ts | import { ReplaySubject } from 'rxjs/ReplaySubject';
import { FormGroup, FormControl } from '@angular/forms';
import { WizardForm, SourceSettings } from './deployment-center-setup-models';
import { Observable } from 'rxjs/Observable';
import { CacheService } from '../../../../shared/services/cache.service';
import { Arm... | }
})
.switchMap(r => {
if (r && r.status === 200) {
return this._patchSiteConfigForGitHubAction();
} else {
return Observable.throw(r);
}
})
.catch(r => Observable.throw(r))
.map(r => r.json());
}
private _updateMetadata(properties: ... | random_line_split | |
deployment-center-state-manager.ts | import { ReplaySubject } from 'rxjs/ReplaySubject';
import { FormGroup, FormControl } from '@angular/forms';
import { WizardForm, SourceSettings } from './deployment-center-setup-models';
import { Observable } from 'rxjs/Observable';
import { CacheService } from '../../../../shared/services/cache.service';
import { Arm... | (properties: { [key: string]: string }, sourceSettingsPayload: SourceSettings) {
delete properties['RepoUrl'];
delete properties['ScmUri'];
delete properties['CloneUri'];
delete properties['branch'];
properties['RepoUrl'] = sourceSettingsPayload.repoUrl;
properties['branch'] = sourceSettingsPay... | _updateMetadata | identifier_name |
actix.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
}
/// 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();
app = app.scope("... | {
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 | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SystemRuntime").finish()
}
}
/// CORS header specification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AllowOrigin {
/// Allows access from any host.
Any,
/// Allows access only from the specified hosts.
Whitelist(Vec... | fmt | identifier_name |
actix.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | "*" => Ok(AllowOrigin::Any),
_ => Ok(AllowOrigin::Whitelist(vec![value.to_string()])),
}
}
fn visit_seq<A>(self, seq: A) -> result::Result<AllowOrigin, A::Error>
where
A: de::SeqAccess<'de>,
{
... | match value { | random_line_split |
seq2seq.py | from functools import partial
import tensorflow as tf
layers = tf.keras.layers
class _Seq2SeqBase(object):
@staticmethod
def gru():
return layers.CuDNNGRU if tf.test.is_gpu_available() else layers.GRU
@staticmethod
def lstm():
return layers.CuDNNLSTM if tf.test.is_gpu_available() el... |
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 | from functools import partial
import tensorflow as tf
layers = tf.keras.layers
class _Seq2SeqBase(object):
@staticmethod
def gru():
return layers.CuDNNGRU if tf.test.is_gpu_available() else layers.GRU
@staticmethod
def lstm():
return layers.CuDNNLSTM if tf.test.is_gpu_available() el... | (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 | from functools import partial
import tensorflow as tf
layers = tf.keras.layers
class _Seq2SeqBase(object):
@staticmethod
def gru():
return layers.CuDNNGRU if tf.test.is_gpu_available() else layers.GRU
@staticmethod
def lstm():
return layers.CuDNNLSTM if tf.test.is_gpu_available() el... |
@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 | from functools import partial
import tensorflow as tf
layers = tf.keras.layers
class _Seq2SeqBase(object):
@staticmethod
def gru():
return layers.CuDNNGRU if tf.test.is_gpu_available() else layers.GRU
@staticmethod
def lstm():
return layers.CuDNNLSTM if tf.test.is_gpu_available() el... | 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 | // This file is part of the SORA network and Polkaswap app.
// Copyright (c) 2020, 2021, Polka Biome Ltd. All rights reserved.
// SPDX-License-Identifier: BSD-4-Clause
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
... | 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 | // This file is part of the SORA network and Polkaswap app.
// Copyright (c) 2020, 2021, Polka Biome Ltd. All rights reserved.
// SPDX-License-Identifier: BSD-4-Clause
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
... | impl sp_runtime::traits::ExtrinsicMetadata for TestExtrinsic {
const VERSION: u8 = 1;
type SignedExtensions = ();
}
construct_runtime!(
pub enum Runtime where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic
{
System: frame_system::{Module, Call,... | type GetEthNetworkId = EthNetworkId;
type WeightInfo = ();
}
| random_line_split |
mock.rs | // This file is part of the SORA network and Polkaswap app.
// Copyright (c) 2020, 2021, Polka Biome Ltd. All rights reserved.
// SPDX-License-Identifier: BSD-4-Clause
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
... | ;
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 | // This file is part of the SORA network and Polkaswap app.
// Copyright (c) 2020, 2021, Polka Biome Ltd. All rights reserved.
// SPDX-License-Identifier: BSD-4-Clause
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
... |
pub fn build(self) -> (TestExternalities, State) {
let (offchain, offchain_state) = TestOffchainExt::new();
let (pool, pool_state) = TestTransactionPoolExt::new();
let authority_account_id =
bridge_multisig::Module::<Runtime>::multi_account_id(&self.root_account_id, 1, 0);
... | {
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 | #!/usr/bin/env python
"""Identify significantly mutated genes in a set of many WES samples.
Prints a table of each gene's observed and expected loss-of-function (LOF)
mutation burdens and estimated false discovery rate (FDR) for predicted tumor
suppressors.
"""
from __future__ import print_function, division
import ... |
def group_data_by_gs(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... | """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 | #!/usr/bin/env python
"""Identify significantly mutated genes in a set of many WES samples.
Prints a table of each gene's observed and expected loss-of-function (LOF)
mutation burdens and estimated false discovery rate (FDR) for predicted tumor
suppressors.
"""
from __future__ import print_function, division
import ... |
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 | #!/usr/bin/env python
"""Identify significantly mutated genes in a set of many WES samples.
Prints a table of each gene's observed and expected loss-of-function (LOF)
mutation burdens and estimated false discovery rate (FDR) for predicted tumor
suppressors.
"""
from __future__ import print_function, division
import ... | 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 | #!/usr/bin/env python
"""Identify significantly mutated genes in a set of many WES samples.
Prints a table of each gene's observed and expected loss-of-function (LOF)
mutation burdens and estimated false discovery rate (FDR) for predicted tumor
suppressors.
"""
from __future__ import print_function, division
import ... | (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 | """Processing for MyProjects Web Application
"""
import datetime
from django.http import Http404
from django.core.exceptions import ObjectDoesNotExist, FieldError # , DoesNotExist
from django.utils.translation import gettext as _
import docs.models as my
from myprojects.settings import MEDIA_ROOT, SITES
RELTXT = '<b... | 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 | """Processing for MyProjects Web Application
"""
import datetime
from django.http import Http404
from django.core.exceptions import ObjectDoesNotExist, FieldError # , DoesNotExist
from django.utils.translation import gettext as _
import docs.models as my
from myprojects.settings import MEDIA_ROOT, SITES
RELTXT = '<b... |
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 | """Processing for MyProjects Web Application
"""
import datetime
from django.http import Http404
from django.core.exceptions import ObjectDoesNotExist, FieldError # , DoesNotExist
from django.utils.translation import gettext as _
import docs.models as my
from myprojects.settings import MEDIA_ROOT, SITES
RELTXT = '<b... |
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 | """Processing for MyProjects Web Application
"""
import datetime
from django.http import Http404
from django.core.exceptions import ObjectDoesNotExist, FieldError # , DoesNotExist
from django.utils.translation import gettext as _
import docs.models as my
from myprojects.settings import MEDIA_ROOT, SITES
RELTXT = '<b... | (proj, soort, id, button_lijst):
"build buttons to create related documents"
# in het document krijg ik per soort te relateren document eerst een "leg relatie" knop
# daarna als er relaties zijn de verwijzingen met een knop "verwijder relatie"
# en tenslotte dit setje knoppen, dat van mij ook wel bij de... | get_relation_buttons | identifier_name |
js_lua_state.rs | use std::sync::Arc;
use std::{fs, thread};
use crate::js_traits::{FromJs, ToJs};
use crate::lua_execution;
use crate::value::Value;
use mlua::{Lua, StdLib};
use neon::context::Context;
use neon::handle::Handle;
use neon::prelude::*;
use neon::declare_types;
fn lua_version() -> &'static str {
if cfg!(feature = "... |
}
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 | use std::sync::Arc;
use std::{fs, thread};
use crate::js_traits::{FromJs, ToJs};
use crate::lua_execution;
use crate::value::Value;
use mlua::{Lua, StdLib};
use neon::context::Context;
use neon::handle::Handle;
use neon::prelude::*;
use neon::declare_types;
fn lua_version() -> &'static str {
if cfg!(feature = "... | 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 | use std::sync::Arc;
use std::{fs, thread};
use crate::js_traits::{FromJs, ToJs};
use crate::lua_execution;
use crate::value::Value;
use mlua::{Lua, StdLib};
use neon::context::Context;
use neon::handle::Handle;
use neon::prelude::*;
use neon::declare_types;
fn lua_version() -> &'static str {
if cfg!(feature = "... | (
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 | package hostpath
import (
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/golang/glog"
"github.com/google/uuid"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"strconv"
)
const (
deviceID = "deviceID"
maxStorageCapacity = tib
)
type a... | (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 | package hostpath
import (
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/golang/glog"
"github.com/google/uuid"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"strconv"
)
const (
deviceID = "deviceID"
maxStorageCapacity = tib
)
type a... | }),
nodeID: nodeID,
}
}
func getControllerServiceCapabilities(cl []csi.ControllerServiceCapability_RPC_Type) []*csi.ControllerServiceCapability {
var csc []*csi.ControllerServiceCapability
for _, ca := range cl {
glog.Infof("Enabling controller service capability: %v", ca.String())
csc = append(csc, &csi.... | csi.ControllerServiceCapability_RPC_VOLUME_CONDITION, | random_line_split |
controllerserver.go | package hostpath
import (
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/golang/glog"
"github.com/google/uuid"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"strconv"
)
const (
deviceID = "deviceID"
maxStorageCapacity = tib
)
type a... |
func (cs controllerServer) ControllerGetVolume(ctx context.Context, request *csi.ControllerGetVolumeRequest) (*csi.ControllerGetVolumeResponse, error) {
panic("implement me")
}
func NewControllerServer(ephemeral bool, nodeID string) *controllerServer {
if ephemeral {
return &controllerServer{caps: getControllerS... | {
panic("implement me")
} | identifier_body |
controllerserver.go | package hostpath
import (
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/golang/glog"
"github.com/google/uuid"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"strconv"
)
const (
deviceID = "deviceID"
maxStorageCapacity = tib
)
type a... |
}
// 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 | import React from "react"
import { Modal ,Form, Input,message, Select,Upload,Icon,InputNumber } from "antd"
import { connect } from 'dva'
import HzInput from '@/components/HzInput'
import { ACTIVIT_TYPE } from '../../../services/lottery_activity'
const FormItem = Form.Item
const Option = Select.Option
const imgMap = {... |
<FormItem label="奖品名称" {...formItemLayout}>
{getFieldDecorator('name', {
rules:[
{required:true,message:'请输入奖品名称'}
]
})(
<HzInput ... | )}
</FormItem>: null} | random_line_split |
AwardEditModal.js | import React from "react"
import { Modal ,Form, Input,message, Select,Upload,Icon,InputNumber } from "antd"
import { connect } from 'dva'
import HzInput from '@/components/HzInput'
import { ACTIVIT_TYPE } from '../../../services/lottery_activity'
const FormItem = Form.Item
const Option = Select.Option
const imgMap = {... | om/',
accept: ".jpg,.jpeg,.png",
headers: {},
data: {
token: photoToken,
},
listType: "picture-card",
multiple: true,
onPreview: () => this.handlePreview(fileList),
beforeUpload: this.beforeUpload,
... | niup.c | identifier_name |
AwardEditModal.js | import React from "react"
import { Modal ,Form, Input,message, Select,Upload,Icon,InputNumber } from "antd"
import { connect } from 'dva'
import HzInput from '@/components/HzInput'
import { ACTIVIT_TYPE } from '../../../services/lottery_activity'
const FormItem = Form.Item
const Option = Select.Option
const imgMap = {... |
}
}
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 | package public
import (
"crypto/md5"
"encoding/json"
"fmt"
"io"
"log"
"mime/multipart"
"net"
"net/http"
"os"
"reflect"
"sort"
"strconv"
"github.com/otiai10/copy"
//"strconv"
//"net/http/cookiejar"
"io/ioutil"
//"log"
//"path/filepath"
//"path"
"os/exec"
"path/filepath"
"strings"
"time"
//"gi... | 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 | package public
import (
"crypto/md5"
"encoding/json"
"fmt"
"io"
"log"
"mime/multipart"
"net"
"net/http"
"os"
"reflect"
"sort"
"strconv"
"github.com/otiai10/copy"
//"strconv"
//"net/http/cookiejar"
"io/ioutil"
//"log"
//"path/filepath"
//"path"
"os/exec"
"path/filepath"
"strings"
"time"
//"gi... | realip)
}
| Log("realip=" + | conditional_block |
PublicFunction.go | package public
import (
"crypto/md5"
"encoding/json"
"fmt"
"io"
"log"
"mime/multipart"
"net"
"net/http"
"os"
"reflect"
"sort"
"strconv"
"github.com/otiai10/copy"
//"strconv"
//"net/http/cookiejar"
"io/ioutil"
//"log"
//"path/filepath"
//"path"
"os/exec"
"path/filepath"
"strings"
"time"
//"gi... |
func RealIPHand(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if rip := RealIP(r); rip != "" {
r.RemoteAddr = rip
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
var xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
var xForwardedFor2 = http.CanonicalHea... | var tmp int32
binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return int(tmp)
} | random_line_split |
PublicFunction.go | package public
import (
"crypto/md5"
"encoding/json"
"fmt"
"io"
"log"
"mime/multipart"
"net"
"net/http"
"os"
"reflect"
"sort"
"strconv"
"github.com/otiai10/copy"
//"strconv"
//"net/http/cookiejar"
"io/ioutil"
//"log"
//"path/filepath"
//"path"
"os/exec"
"path/filepath"
"strings"
"time"
//"gi... | rid\": \"56\",\"message\": \"hhhhhaaaaaa\",\"time\": \"2017-12-12 12:11:11\"}]}}';
index := strings.IndexRune(jsonstr, '{')
jsonstr = jsonstr[index : len(jsonstr)-index]
if len(jsonstr) > 4 && strings.Index(jsonstr, "{") > -1 && strings.Index(jsonstr, "}") > -1 {
mapp := GetMapByJsonStr(jsonstr)
//Log(mapp)
ma... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.