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 |
|---|---|---|---|---|
mod.rs | enum FluentValue<'source> {
String(Cow<'source, str>),
Number(FluentNumber),
Custom(Box<dyn FluentType + Send>),
None,
Error,
}
impl<'s> PartialEq for FluentValue<'s> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(FluentValue::String(s), FluentValue::String(s... | {
FluentValue::String(s.into())
} | identifier_body | |
mod.rs | uentResource;
/// Custom types can implement the [`FluentType`] trait in order to generate a string
/// value for use in the message generation process.
pub trait FluentType: fmt::Debug + AnyEq + 'static {
/// Create a clone of the underlying type.
fn duplicate(&self) -> Box<dyn FluentType + Send>;
/// Co... | match self {
FluentValue::String(s) => w.write_str(s),
FluentValue::Number(n) => w.write_str(&n.as_string()),
FluentValue::Custom(s) => w.write_str(&scope.bundle.intls.stringify_value(&**s)),
FluentValue::Error => Ok(()),
FluentValue::None => Ok(()),
... | }
} | random_line_split |
simplesnake.js | NOTE: the code is styled in a very specific but not very popular
* style in part to illustrate different approaches to code
* organization and structuring.
*
*
*
**********************************************************************/
var VERSION = '2.0'
/*******************************************... |
while(length > 0){
var c = this._cells[x + y * this.field_size.width]
c.classList.add('wall')
c.style.backgroundColor = ''
x += direction == 'e' ?
1
: direction == 'w' ?
-1
: 0
x = x < 0 ?
this.field_size.width + x
: x % this.field_size.width
y += directi... | length = length
|| Math.random() * this.field_size.width
| random_line_split |
simplesnake.js | ''
var j = turn == 'left' ?
directions.indexOf(direction) - 1
: directions.indexOf(direction) + 1
j = j < 0 ? 3 : j
direction = directions[j]
that.players[color] = '' }
// get next cell index...
var next =
direction == 'n' ?
(i < w ?
... | showScore | identifier_name | |
simplesnake.js | .querySelector(field)
: field
this._make_field()
this._cells = [].slice.call(field.querySelectorAll('td'))
this.field_size = {
width: field.querySelector('tr').querySelectorAll('td').length,
height: field.querySelectorAll('tr').length,
}
this.players = {}
return this
.appleEaten(null)
... | {
document.body.classList.remove('hints') } | identifier_body | |
simplesnake.js | NOTE: the code is styled in a very specific but not very popular
* style in part to illustrate different approaches to code
* organization and structuring.
*
*
*
**********************************************************************/
var VERSION = '2.0'
/*******************************************... | else {
that.snakeKilled(color, age+2) }
// do the move...
if(move){
next.tick = tick
next.style.backgroundColor = color
next.classList.add('snake')
next.age = age + 1
next.direction = direction }
delete cell.direction } }
cell.tick = tick })
this.t... | {
move = true
// other -> kill...
} | conditional_block |
realtimeLogger.py | .strptime(date_str, '%Y-%m-%d %H:%M:%S.%f')
return date.strftime('%H:%M:%S')
def my_makedirs(path):
if not os.path.isdir(path):
os.makedirs(path)
def df_maker(f,C_mode):
df_list = {'Time':[],'1ch':[],'2ch':[],'3ch':[],'4ch':[]}
index = 0
for row in f:#row is list
if index == 0:... |
# print(data[990])
df = df_maker(data,C_mode)
# 折れ線グラフを再描画する
ax_1ch.yaxis.grid(True)
ax_2ch.yaxis.grid(True)
ax_3ch.yaxis.grid(True)
ax_4ch.yaxis.grid(True)
t_1ch = df[0]
d_1ch = df[1]
d_2ch = df[2]
d_3ch = df[3]
d_4ch = df[4]
ax_1ch.set_ylabel('X [nT]', f... | print("redraw") | random_line_split |
realtimeLogger.py | .strptime(date_str, '%Y-%m-%d %H:%M:%S.%f')
return date.strftime('%H:%M:%S')
def my_makedirs(path):
if not os.path.isdir(path):
os.makedirs(path)
def df_maker(f,C_mode):
df_list = {'Time':[],'1ch':[],'2ch':[],'3ch':[],'4ch':[]}
index = 0
for row in f:#row is list
if index == 0:... | (time_dat,dat,Cutoff):
out = {'time':[],'data':[]}
now_time = eliminate_f(time_dat[0])
buf_t = []
buf_d = []
i = -1
try:
while(1):
i += 1
buf_t.append(time_dat[i])
buf_d.append(dat[i])
if i+1 == len(dat):
clean_d... | medianFilter | identifier_name |
realtimeLogger.py | .strptime(date_str, '%Y-%m-%d %H:%M:%S.%f')
return date.strftime('%H:%M:%S')
def my_makedirs(path):
if not os.path.isdir(path):
os.makedirs(path)
def df_maker(f,C_mode):
df_list = {'Time':[],'1ch':[],'2ch':[],'3ch':[],'4ch':[]}
index = 0
for row in f:#row is list
if index == 0:... |
return df_list['Time'],df_list['1ch'],df_list['2ch'],df_list['3ch'],df_list['4ch']
def get_Srate(time_dat):
now_time = eliminate_f(time_dat[0])
i = 0
try:
#### load head ####
while(1):
i += 1
if now_time != eliminate_f(time_dat[i]):
now_time = e... | df_list['Time'].append(dataday + row[0])
df_list['1ch'].append(float(row[1]))
df_list['2ch'].append(float(row[2]))
df_list['3ch'].append(float(row[3]))
df_list['4ch'].append(float(row[4])) | conditional_block |
realtimeLogger.py | .strptime(date_str, '%Y-%m-%d %H:%M:%S.%f')
return date.strftime('%H:%M:%S')
def my_makedirs(path):
|
def df_maker(f,C_mode):
df_list = {'Time':[],'1ch':[],'2ch':[],'3ch':[],'4ch':[]}
index = 0
for row in f:#row is list
if index == 0:
dataday = row[0]
index = 1
else:
if row[0] != 0:
df_list['Time'].append(dataday + row[0])
... | if not os.path.isdir(path):
os.makedirs(path) | identifier_body |
validation.py | _OPERATION_RESPONSES,
)
from .events import (
ReferenceNotFoundValidationError,
ParameterDefinitionValidationError,
SecurityDefinitionNotFoundValidationError,
OAuth2ScopeNotFoundInSecurityDefinitionValidationError,
DuplicateOperationIdValidationError,
JsonSchemaValidationError,
ValidationErr... | try:
rt, obj = reference[2:].split("/")
except ValueError:
events.add(
ReferenceInvalidSyntax(
path=path, reason=f"reference {reference} not of the form '#/section/item'"
)
)
... |
for _, reference, path in get_elements(swagger, ref_jspath):
# handle only local references
if reference.startswith("#/"):
# decompose reference (error if not possible) | random_line_split |
validation.py | _OPERATION_RESPONSES,
)
from .events import (
ReferenceNotFoundValidationError,
ParameterDefinitionValidationError,
SecurityDefinitionNotFoundValidationError,
OAuth2ScopeNotFoundInSecurityDefinitionValidationError,
DuplicateOperationIdValidationError,
JsonSchemaValidationError,
ValidationErr... | # resolve reference (error if not possible)
try:
swagger[rt][obj]
except KeyError:
events.add(
ReferenceNotFoundValidationError(
path=path, reason=f"reference '#/{rt}/{obj}' does not exist"
... | if reference.startswith("#/"):
# decompose reference (error if not possible)
try:
rt, obj = reference[2:].split("/")
except ValueError:
events.add(
ReferenceInvalidSyntax(
path=path, reason=f"reference {refer... | conditional_block |
validation.py | _OPERATION_RESPONSES,
)
from .events import (
ReferenceNotFoundValidationError,
ParameterDefinitionValidationError,
SecurityDefinitionNotFoundValidationError,
OAuth2ScopeNotFoundInSecurityDefinitionValidationError,
DuplicateOperationIdValidationError,
JsonSchemaValidationError,
ValidationErr... | path=path_param,
reason=f"The parameter is required yet it has a default value",
parameter_name=name,
)
)
# check if type==array that there is an items
if _type == "array" and "items" not in param:
events.add(
ParameterDefi... | """Check a parameter structure
For a parameter, the check for consistency are on:
- required and default
- type/format and default
- enum
"""
events = set()
name = param.get("name", "unnamed-parameter")
required = param.get("required", False)
default = param.get("default")
_typ... | identifier_body |
validation.py | _RESPONSES,
)
from .events import (
ReferenceNotFoundValidationError,
ParameterDefinitionValidationError,
SecurityDefinitionNotFoundValidationError,
OAuth2ScopeNotFoundInSecurityDefinitionValidationError,
DuplicateOperationIdValidationError,
JsonSchemaValidationError,
ValidationError,
Re... | (swagger: Dict):
"""
Find reference in paths, for /definitions/ and /responses/ /securityDefinitions/.
Follow from these, references to other references, till no more added.
:param swagger:
:return:
"""
events = set()
ref_jspath = JSPATH_REFERENCES
for _, reference, path in get_e... | check_references | identifier_name |
staged_file.rs | file::WriteError),
/// Failed to rename the staged file.
#[error("Failed to rename temp file to target: {0}")]
RenameError(#[from] fuchsia_fs::node::RenameError),
/// Failed to flush data.
#[error("Failed to flush to disk: {0}")]
FlushError(#[source] zx::Status),
/// Failed to close the s... | &temp_filename,
fio::OpenFlags::RIGHT_READABLE
| fio::OpenFlags::RIGHT_WRITABLE
| fio::OpenFlags::CREATE,
)
.await?;
Ok(StagedFile { dir_proxy, temp_filename, file_proxy })
}
/// Writes data to the backing staged file proxy.
/... | let temp_filename = generate_tempfile_name(tempfile_prefix);
let file_proxy = fuchsia_fs::directory::open_file(
dir_proxy, | random_line_split |
staged_file.rs | ::WriteError),
/// Failed to rename the staged file.
#[error("Failed to rename temp file to target: {0}")]
RenameError(#[from] fuchsia_fs::node::RenameError),
/// Failed to flush data.
#[error("Failed to flush to disk: {0}")]
FlushError(#[source] zx::Status),
/// Failed to close the stage... |
}
}
}
if failures.is_empty() {
Ok(())
} else {
Err(failures)
}
}
}
/// Generates a temporary filename using |thread_rng| to append random chars to
/// a given |prefix|.
fn generate_tempfile_name(prefix: &str) -> String {
// G... | {
if let Err(unlink_err) = unlink_res {
failures.push(StagedFileError::UnlinkError(zx::Status::from_raw(
unlink_err,
)));
}
} | conditional_block |
staged_file.rs | {
/// Invalid arguments.
#[error("Invalid arguments to create a staged file: {0}")]
InvalidArguments(String),
/// Failed to open a file or directory.
#[error("Failed to open: {0}")]
OpenError(#[from] fuchsia_fs::node::OpenError),
/// Failed during a FIDL call.
#[error("Failed during F... | StagedFileError | identifier_name | |
staged_file.rs | |target_filename|s given when calling StagedFile::commit.
/// It would have been preferable to use the tempfile crate here, but it lacks
/// the ability to open things without making use of paths and namespaces, and
/// as such, StagedFile should only be used in cases where we must supply our
/// own |DirectoryProxy|.... | {
let tmp_dir = TempDir::new().unwrap();
let dir = fuchsia_fs::directory::open_in_namespace(
tmp_dir.path().to_str().unwrap(),
fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_WRITABLE,
)
.expect("could not open temp dir");
// Write a variety of sta... | identifier_body | |
python3 | :
return U / S
def main():
options = _parse_args()
V = 1000
data = np.genfromtxt("a-leer.csv", delimiter="\t")
t = data[:,0]
U = data[:,1] / V / 1000
U_err = 0.7e-3 / V
offset = np.mean(U[-3:])
x = np.linspace(min(t), max(t))
y = np.ones(x.size) * offset
pl.plot(x, y * 1... | f(U) | identifier_name | |
python3 |
pl.plot(x, y * 10**6, label=ur"$90\%$")
pl.errorbar(t, U * 10**6, yerr=U_err * 10**6, linestyle="none", marker="+",
label="Messdaten")
pl.grid(True)
pl.legend(loc="best")
pl.title(u"Bestimmung der Ansprechzeit")
pl.xlabel(ur"Zeit $t / \mathrm{s}$")
pl.ylabel(ur"Thermospannu... | glanz_popt, glanz_pconv = op.curve_fit(boltzmann, glanz[:,0], glanz_phi)
matt_popt, matt_pconv = op.curve_fit(boltzmann, matt[:,0], matt_phi)
schwarz_popt, schwarz_pconv = op.curve_fit(boltzmann, schwarz[:,0], schwarz_phi)
weiss_popt, weiss_pconv = op.curve_fit(boltzmann, weiss[:,0], weiss_phi)
glanz_... | n epsilon * sigma * T**4 + offset
| identifier_body |
python3 | warz_popt[0], np.sqrt(schwarz_pconv.diagonal()[0]))
print "schwarz offset = {:.3g} ± {:.3g}".format(schwarz_popt[1], np.sqrt(schwarz_pconv.diagonal()[1]))
print "weiss ε = {:.3g} ± {:.3g}".format(weiss_popt[0], np.sqrt(weiss_pconv.diagonal()[0]))
print "weiss offset = {:.3g} ± {:.3g}".format(weiss_popt[1], ... | random_line_split | ||
python3 |
pl.plot(x, y * 10**6, label=ur"$90\%$")
pl.errorbar(t, U * 10**6, yerr=U_err * 10**6, linestyle="none", marker="+",
label="Messdaten")
pl.grid(True)
pl.legend(loc="best")
pl.title(u"Bestimmung der Ansprechzeit")
pl.xlabel(ur"Zeit $t / \mathrm{s}$")
pl.ylabel(ur"Thermospannu... | le
print
epsilon = 0.1
x = np.linspace(min([min(x) for x in [glanz[:,0], matt[:,0], schwarz[:,0],
weiss[:,0]]]),
max([max(x) for x in [glanz[:,0], matt[:,0], schwarz[:,0],
weiss[:,0]]]),
... | row)
print weiss_tab | conditional_block |
table1.py |
def __str__ (this):
return this.functor+"("+",".join(this.varList)+") = "+str(this.val)
def __repr__ (this):
return str(this)
""" No used, no more
def match (this, node, grounding):
if not node.isLiteralNode():
raise Exception ("Attempt to match nonprobabil... | this.functor = functor
this.varList = varList
this.val = val | identifier_body | |
table1.py | Attempt to match nonprobability Node "+str(node)+" with probability value")
if this.functor != node.functor:
return (False,0)
else:
for (var,val) in zip(node.varList, this.varList):
if val != grounding.val(var):
return (False,(var,val... | (this, varList):
this.varList = varList
def val (this, var):
for (v, ground) in this.varList:
if v == var:
return ground
else:
raise Exception ("Var not ground: " + var)
def groundNode (this, node):
gndList = []
for var in node.v... | __init__ | identifier_name |
table1.py | Attempt to match nonprobability Node "+str(node)+" with probability value")
if this.functor != node.functor:
return (False,0)
else:
for (var,val) in zip(node.varList, this.varList):
if val != grounding.val(var):
return (False,(var,val... |
else:
return range[0]
def atomList(joints):
""" Return the atoms, derived from the first entry in the joint probability table """
assert len(joints) > 0
first = joints[0]
functorList = first[1][:-2] # Second element of row, last two elements of that are joint prob and log prob
atomList... | return range[1] | conditional_block |
table1.py | Attempt to match nonprobability Node "+str(node)+" with probability value")
if this.functor != node.functor:
return (False,0)
else:
for (var,val) in zip(node.varList, this.varList):
if val != grounding.val(var):
return (False,(var,val... | this.prob = prob
def __str__(this):
return "P("+str(this.child)+" | "+",".join([str(n) for n in this.parentList])+") = "+str(this.prob)
class Grounding (object):
""" A specific assignment of constants to variables """
def __init__ (this, varList):
this.varList = varList
def ... | """ A rule specifying a conditional probability (the class is likely misnamed) """
def __init__ (this, child, parentList, prob):
this.child = child
this.parentList = parentList | random_line_split |
result.rs | match le {
LdapError::Io { source, .. } => source,
_ => io::Error::new(io::ErrorKind::Other, format!("{}", le)),
}
}
}
/// Common components of an LDAP operation result.
///
/// This structure faithfully replicates the components dictated by the standard,
/// and is distinctly C-li... | CompareResult | identifier_name | |
result.rs | .
#[error("result recv error: {source}")]
ResultRecv {
#[from]
source: oneshot::error::RecvError,
},
/// Error while sending an internal ID scrubbing request to the connection handler.
#[error("id scrub send error: {source}")]
IdScrubSend {
#[from]
source: mpsc::... | /// interface, but there are scenarios where this would preclude intentional
/// incorporation of error conditions into query design. Instead, the struct
/// implements helper methods, [`success()`](#method.success) and
/// [`non_error()`](#method.non_error), which may be used for ergonomic error
/// handling when simp... | /// This structure faithfully replicates the components dictated by the standard,
/// and is distinctly C-like with its reliance on numeric codes for the indication
/// of outcome. It would be tempting to hide it behind an automatic `Result`-like | random_line_split |
graph_views.py | and test_data.count() == 0:
return redirect('study:two_input')
# 今日の日付を取得
base = datetime.datetime.today()
print('base= ', base)
# ■■■■■■ 勉強時間入力データの加工 ■■■■■■
# record_data = Record.objects.filter(author=request.user).all()
if record_data.count() >0:
record_df = read_frame(record_... | nt() == 0 | identifier_name | |
graph_views.py | 'author', 'created_at', 'category', 'time'])
record_df = record_df.replace(
{'国語': '1', '数学': '2', '英語': '3', '理科': '4', '社会': '5'})
record_df['date'] = pd.to_datetime(record_df['created_at'].dt.strftime("%Y-%m-%d"))
record_df['time'] = record_df['time'].astype(int) # ... | _data, fieldnames=[
| conditional_block | |
graph_views.py | ■■■■ クロス集計表の作成 ■■■■■■
# dfを縦に結合
if record_data.count() ==0:
record_df = dates_df_5cate
else:
record_df = pd.concat([record_df, base_df]).sort_values('date')
record_df['date'] = pd.to_datetime(record_df['date']).dt.strftime("%Y-%m-%d")
record_df = record_df.pivot_table(
index... | 'text': '学習記録',
'x': 0.05,
'xref': 'paper', | random_line_split | |
graph_views.py | # test_df = Test.objects.filter(author=request.user).all()
test_df_nan = pd.DataFrame([
[0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, base]],
columns=['id', 't国', 't数', 't英', 't理', '... |
print('base= ', base)
# ■■■■■■ 勉強時間入力データの加工 ■■■■■■
# record_data = Record.objects.filter(author=request.user).all()
if record_data.count() >0:
record_df = read_frame(record_data, fieldnames=[
'author', 'created_at', 'category', 'time'])
record_df = record_df.rep... | identifier_body | |
bytesDemo.go | = []byte("迁客骚人,文人墨客无不倾倒于俺滴代码")
c = []byte("人,文人墨客")
co := bytes.Contains(b, c)
fmt.Printf("c 是否在 b 中:%v", co) //true
}
//ContainsAny 报告字符中的任何 UTF-8 编码的 Unicode 代码点是否在 d 中
//3 看字节中utf8字符串是否包含 字符串 忽视空格
func containsAnyDemo() {
d = []byte("若能杯水如名淡,应信村茶比酒香") //字节
ca := bytes.ContainsAny(d, "茶比,香") //忽视空格,忽略顺序... | 2 := func(c r | identifier_name | |
bytesDemo.go | 70 154 228 186 186 44 230 150 135 228 186 186 229 162 168 229 174 162 230 151 160 228 184 141 229 128 190 229 128 146 228 186 142 228 191 186 230 187 180 228 187 163 231 160 129]
//c byte : [231 179 159 232 128 129 229 164 180 229 173 144 229 157 143 229 190 151 229 190 136]
}
}
//func Contains(b, subslice []byte) ... | ello, 世界"), f2))
fmt.Println(bytes.IndexFunc([]byte("Hello, world"), f2))
}
//16 func Join 指定分隔符拼接byte数组
//func Join(s [][]byte, sep []byte) []byte
//Join 连接 s的元素以创建一个新的字节片。分隔符 sep 放置在生成的切片中的元素之间。
func jsonDemo() {
s := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")}
fmt.Printf("%s", bytes.Join(s, []byte(", "... | .IndexFunc([]byte("H | conditional_block |
bytesDemo.go | "), []byte("go")))
fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("go")))
fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("rodent")))
}
//18 func LastIndexAny :它返回字符中任何 Unicode 代码点的最后一次出现的字节索引。
//func LastIndexAny(s []byte, chars string) int
//LastIndexAny 将 s 解释为UTF-8编码的 Unicode 代码点序列。
// 它返回字符中任何... | //28 SplitAfterN 参考SplitN
//func SplitAfterN(s, sep []byte, n int) [][]byte
//在每个 sep 实例之后,SplitAfterN 将 s 分割成子项,并返回这些子项的一部分。
// 如果 sep 为空,则 SplitAfterN 在每个 UTF-8 序列之后分割。计数确定要返回的子备份数量: | random_line_split | |
bytesDemo.go | 70 154 228 186 186 44 230 150 135 228 186 186 229 162 168 229 174 162 230 151 160 228 184 141 229 128 190 229 128 146 228 186 142 228 191 186 230 187 180 228 187 163 231 160 129]
//c byte : [231 179 159 232 128 129 229 164 180 229 173 144 229 157 143 229 190 151 229 190 136]
}
}
//func Contains(b, subslice []byte) ... | byte
//Join 连接 s的元素以创建一个新的字节片。分隔符 sep 放置在生成的切片中的元素之间。
func jsonDemo() {
s := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")}
fmt.Printf("%s", bytes.Join(s, []byte(", ")))
}
//17 func LastIndex
//func LastIndex(s, sep []byte) int
//LastIndex 返回 s 中最后一个 sep 实例的索引,如果 sep 中不存在 s,则返回-1。
func lastIndexDemo() {
fmt... | xFuncDemo() {
f2 := func(c rune) bool {
return unicode.Is(unicode.Han, c)
}
fmt.Println(bytes.IndexFunc([]byte("Hello, 世界"), f2))
fmt.Println(bytes.IndexFunc([]byte("Hello, world"), f2))
}
//16 func Join 指定分隔符拼接byte数组
//func Join(s [][]byte, sep []byte) [] | identifier_body |
dom-utils.ts |
function nthChild(element: HTMLElement) {
let childNumber = 0
const childNodes = element.parentNode!.childNodes
for (const node of childNodes) {
if (node.nodeType === Node.ELEMENT_NODE) ++childNumber
if (node === element) return `:nth-child('${childNumber}')`
}
}
function attributes(element: HTMLElem... | {
let classSelector = ''
const classList = element.classList
for (const c of classList) {
classSelector += '.' + c
}
return classSelector
} | identifier_body | |
dom-utils.ts | attr.name}="${attr.value}"]`
}
return attributes
}
export function path(el: HTMLElement, rootNode = document.documentElement) : string {
const selector = el.tagName.toLowerCase() + id(el) + classes(el) + attributes(el) + nthChild(el)
const hasParent = el.parentNode && el.parentNode !== rootNode && (el.parentNo... |
}
export class Bounds {
left = 0
top = 0
width = 0
height = 0
copy(rect: Bounds) {
this.top = rect.top
this.left = rect.left
this.width = rect.width
this.height = rect.height
return this
}
}
export class Edges {
left = 0
top = 0
right = 0
bottom = 0
copy(rect: Edges) {
t... | {
sheet.addRule(selector, rules, index)
} | conditional_block |
dom-utils.ts | ${attr.name}="${attr.value}"]`
}
return attributes
}
export function path(el: HTMLElement, rootNode = document.documentElement) : string {
const selector = el.tagName.toLowerCase() + id(el) + classes(el) + attributes(el) + nthChild(el)
const hasParent = el.parentNode && el.parentNode !== rootNode && (el.parent... | top += parseFloat(computedStyle.borderTopWidth) || 0
left += parseFloat(computedStyle.borderLeftWidth) || 0
offsetParent = el.offsetParent as HTMLElement
}
prevComputedStyle = computedStyle
}
// if (prevComputedStyle.position === 'relative' || prevComputedStyle.position === 'static') {
... | left += el.offsetLeft | random_line_split |
dom-utils.ts | attr.name}="${attr.value}"]`
}
return attributes
}
export function path(el: HTMLElement, rootNode = document.documentElement) : string {
const selector = el.tagName.toLowerCase() + id(el) + classes(el) + attributes(el) + nthChild(el)
const hasParent = el.parentNode && el.parentNode !== rootNode && (el.parentNo... | (bounds: Bounds) {
if (!viewportTester.parentNode) document.documentElement.append(viewportTester)
bounds.left = pageXOffset
bounds.top = pageYOffset
bounds.width = viewportTester.offsetWidth
bounds.height = viewportTester.offsetHeight
return bounds
}
const viewportTester = document.createElement('div')
vie... | getViewportBounds | identifier_name |
Legend.js | ) {
button.show();
button.setHandler(function () {
sheet && sheet.show();
});
}
// TODO: Investigate why we have to set parent to null.
view.setParent(null);
view.setScroll... | /**
* Shows the legend if it is currently hidden.
*/
show: function () { | random_line_split | |
Legend.js | : 'Legend',
items: [
{
xtype: 'spacer'
},
{
text: 'OK'
}
]
}
]
},
button: {
... | {
// Calculate the natural size
view.show();
view.element.setSize(isVertical ? undef : null, isVertical ? null : undef); //clear fixed scroller length
legendWidth = view.element.getWidth();
legendHeight = view.element.getHeight();
... | conditional_block | |
deflate.rs | / 2));
println!("{}", 2u32.pow(code as u32 / 2 - 1));
println!("{}", 2u32.pow(code as u32 / 2) + 2u32.pow(code as u32 / 2 - 1) + 1);
2u32.pow(code as u32 / 2) + 2u32.pow(code as u32 / 2 - 1) + 1
},
_ => panic!("Logic error handling base distance"),
};
let num_distance_extra_bits = match code {
... | {
DEFLATEReader{
buffered_writer: BufferedWriter::new(),
bit_stream: BitStream::new(input),
has_seen_final_block: false,
current_block: None,
}
} | identifier_body | |
deflate.rs | // A code ends up mapping to some base distance plus some
// extra bits to read to add to that base distance
let code = DynamicBlock::get_next_huffman_encoded_value(&distance_huffman, input_stream);
println!("Modulo: {}", code % 2);
let base_distance = match code {
0 ... 3 => {
code as u32 + 1
},
... | DEFLATEReader | identifier_name | |
deflate.rs | , &code_length_huffman);
let distance_huffman = DynamicBlock::read_distance_huffman(hdist, bit_stream, &code_length_huffman);
DynamicBlock{
repeats_remaining: 0,
last_repeat_distance: 0,
literal_length_huffman,
distance_huffman,
}
}
fn read_repeat_distance(distance_huffman: &Huffman<usize>, input_... | println!("Literal/Length Huffman = {:?}", result);
result
}
fn read_distance_huffman(length: usize, input_stream: &mut BitStream, code_length_huffman: &Huffman<usize>) -> Huffman<usize> {
let alphabet = (0..length).collect();
let lengths = DynamicBlock::read_code_lengths(length, input_stream, code_length_huf... | let result = Huffman::new(&alphabet, &lengths); | random_line_split |
deflate.rs | &code_length_huffman);
let distance_huffman = DynamicBlock::read_distance_huffman(hdist, bit_stream, &code_length_huffman);
DynamicBlock{
repeats_remaining: 0,
last_repeat_distance: 0,
literal_length_huffman,
distance_huffman,
}
}
fn read_repeat_distance(distance_huffman: &Huffman<usize>, input_s... |
},
Huffman::Leaf(value) => *value,
Huffman::DeadEnd => panic!("Reached dead end!"),
}
}
fn next(&mut self, bit_stream: &mut BitStream) -> DEFLATEResult {
if self.repeats_remaining > 0 {
self.repeats_remaining -= 1;
return DEFLATEResult::Repeat(self.last_repeat_distance)
}
let value = Dynamic... | {
DynamicBlock::get_next_huffman_encoded_value(zero, input_stream)
} | conditional_block |
pykernel.py | the PUB objects with the message about to be executed.
* Implement random port and security key logic.
* Implement control messages.
* Implement event loop and poll version.
"""
#-----------------------------------------------------------------------------
# Imports
#--------------------------------------------------... | (self, ident, parent):
try:
code = parent[u'content'][u'code']
except:
print>>sys.__stderr__, "Got bad msg: "
print>>sys.__stderr__, Message(parent)
return
pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent)
self.pub_socket.s... | execute_request | identifier_name |
pykernel.py | the PUB objects with the message about to be executed.
* Implement random port and security key logic.
* Implement control messages.
* Implement event loop and poll version.
"""
#-----------------------------------------------------------------------------
# Imports
#--------------------------------------------------... | handler(ident, omsg)
def record_ports(self, xrep_port, pub_port, req_port, hb_port):
"""Record the ports that this kernel is using.
The creator of the Kernel instance must call this methods if they
want the :meth:`connect_request` method to return the port numbers.
... | print>>sys.__stdout__, omsg
handler = self.handlers.get(omsg.msg_type, None)
if handler is None:
print >> sys.__stderr__, "UNKNOWN MESSAGE TYPE:", omsg
else: | random_line_split |
pykernel.py | the PUB objects with the message about to be executed.
* Implement random port and security key logic.
* Implement control messages.
* Implement event loop and poll version.
"""
#-----------------------------------------------------------------------------
# Imports
#--------------------------------------------------... |
return symbol, []
#-----------------------------------------------------------------------------
# Kernel main and launch functions
#-----------------------------------------------------------------------------
def launch_kernel(ip=None, xrep_port=0, pub_port=0, req_port=0, hb_port=0,
inde... | new_symbol = getattr(symbol, name, None)
if new_symbol is None:
return symbol, context[i:]
else:
symbol = new_symbol | conditional_block |
pykernel.py | the PUB objects with the message about to be executed.
* Implement random port and security key logic.
* Implement control messages.
* Implement event loop and poll version.
"""
#-----------------------------------------------------------------------------
# Imports
#--------------------------------------------------... |
def start(self):
""" Start the kernel main loop.
"""
while True:
ident = self.reply_socket.recv()
assert self.reply_socket.rcvmore(), "Missing message part."
msg = self.reply_socket.recv_json()
omsg = Message(msg)
print>>sys.__std... | super(Kernel, self).__init__(**kwargs)
self.user_ns = {}
self.history = []
self.compiler = CommandCompiler()
self.completer = KernelCompleter(self.user_ns)
# Build dict of handlers for message types
msg_types = [ 'execute_request', 'complete_request',
... | identifier_body |
E4418.py | not available on RS422', 'DTR/DSR is only available on the RS232 interface.'),
error_item(-222, 'Data out of range', 'A numeric parameter value is outside the valid range for the command. For example, SENS:FREQ 2KHZ.'),
error_item(-224, 'Illegal parameter value', 'A discrete parameter was received whic... | if msg == e.msg:
emsg = '%s (%d)'%(e.msg, e.num)
msg = 'Power meter returned Error message.\n'
msg += '*'*len(emsg) + '\n'
msg += emsg + '\n'
msg += '*'*len(emsg) + '\n'
msg += e.txt + '\n'
raise StandardErro... | conditional_block | |
E4418.py | 'Illegal parameter value', 'A discrete parameter was received which was not a valid choice for the command. You may have used an invalid parameter choice. For example, TRIG:SOUR EXT.'),
error_item(-226, 'Lists not same length', 'This occurs when SENSe:CORRection:CSET[1]|CSET2:STATe is set to ON and the frequen... | if num==0: return
for e in cls.error_list:
if msg == e.msg:
emsg = '%s (%d)'%(e.msg, e.num)
msg = 'Power meter returned Error message.\n'
msg += '*'*len(emsg) + '\n'
msg += emsg + '\n'
msg += '*'*len(emsg) + '\n'
... | identifier_body | |
E4418.py | -------------------------------
This command is used to enable and disable averaging.
Args
====
< on_off : int or str : 0,1,'ON','OFF' >
Specify the averaging status.
0 = 'OFF', 1 = 'ON'
< ch : int : 1,2 >
Specify the ... | def average_on_off(self, on_off, ch=1):
"""
SENSn:AVER : Set Average ON/OFF | random_line_split | |
E4418.py | (self):
err_num, err_msg = self.error_query()
error_handler.check(err_num, err_msg)
return
def error_query(self):
"""
SYST:ERR? : Query Error Numbers
-------------------------------
This query returns error numbers and messages from the power meter's
... | _error_check | identifier_name | |
main.rs | -> Self{
// init upyunconfig
UpYun{
UpYunConfig: config,
..Default::default()
}
}
fn set_httpc(mut self) -> Self{
self.httpc = "".to_string();
self
}
fn set_deprecated(mut self) -> Self{
self.deprecated = true;
self
}... | }
fn md5str(s: String) -> String {
let mut hasher = md5::Md5::new();
hasher.input_str(&s);
hasher.result_str()
}
fn escapeUri(s: String) -> String {
// let s = String::from("/xx/中文.log");
if s == "" {
let _s = String::from("中文");
}
let escape: [u32; 8] = [
0xffffffff, 0xfc0... |
}
Ok(())
} | random_line_split |
main.rs | Self{
// init upyunconfig
UpYun{
UpYunConfig: config,
..Default::default()
}
}
fn set_httpc(mut self) -> Self{
self.httpc = "".to_string();
self
}
fn set_deprecated(mut self) -> Self{
self.deprecated = true;
self
}
... | yper::Method, url:String, headers: HashMap<String,String>, body: Vec<u8>){
match hyper::Request::builder().method(method).uri(url).body(body){
Ok(req) => {
for (key,value) in headers{
if key.to_lowercase() == "host"{
// req.
... | Some(Value ) => Value.to_string(),
None => host
}
}
/// FIXME
fn doHTTPRequest(&mut self,method: h | identifier_body |
main.rs | (self) -> Self {
self
}
}
impl UpYunConfig {
fn new(Bucket: String, Operator: String, Password: String) -> Self{
UpYunConfig{
Bucket:Bucket,
Operator:Operator,
Password: Password,
..Default::default()
}
}
fn build(mut self) -> Sel... | build | identifier_name | |
main.rs | 0xb8000001, 0xffffffff, 0xffffffff, 0xffffffff,
0xffffffff,
];
let hexMap = "0123456789ABCDEF".as_bytes();
let mut size = 0;
let ss = s.as_bytes();
for i in 0..ss.len() {
let c = ss[i];
if escape.get((c >> 5) as usize).unwrap() & (1 << (c & 0x1f)) > 0 {
size += ... | ring> = vec![
"Upyun".to_string(),
"Operator" | conditional_block | |
BankDataset.py | .drop(trainSet.index)
return trainSet, testSet
# ## Logistic function
# We are using sigmoid as a logistic function defined as <img src="https://wikimedia.org/api/rest_v1/media/math/render/svg/9537e778e229470d85a68ee0b099c08298a1a3f6">
# <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/88/Logi... |
"""Shuffle the indices"""
np.random.shuffle(indices)
"""Will split. May be uneven"""
batches = np.array_split(indices, batchSize)
if verbose:
print("Total batches created"+str(len(batches)))
... | print("Epoch-"+str(i)) | conditional_block |
BankDataset.py | B = B - B.mean()
return ((A * B).sum())/(sqrt((A * A).sum()) * sqrt((B * B).sum()))
# ### TextEncoder
#
# Here the data is mix of numbers and text. Text value cannot be directly used and should be converted to numeric data.<br>
# For this I have created a function text encoder which accepts a pandas series.... | """Generate pearson's coefficient"""
def generatePearsonCoefficient(A, B):
A = A - A.mean() | random_line_split | |
BankDataset.py | (x):
mean = np.mean(x)
stdDeviation = np.std(x)
return x.apply(lambda y: ((y * 1.0) - mean)/(stdDeviation))
# ## SplitDataSet Procedure
# This method splits the dataset into trainset and testset based upon the trainSetSize value. For splitting the dataset, I am using pandas.sample to split the data. This ... | scaleFeature | identifier_name | |
BankDataset.py | .drop(trainSet.index)
return trainSet, testSet
# ## Logistic function
# We are using sigmoid as a logistic function defined as <img src="https://wikimedia.org/api/rest_v1/media/math/render/svg/9537e778e229470d85a68ee0b099c08298a1a3f6">
# <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/88/Logi... |
# ## Regularization
# <img src="https://wikimedia.org/api/rest_v1/media/math/render/svg/d55221bf8c9b730ff7c4eddddb9473af47bb1d1c">
# ### L2 loss
# L2 loss or Tikhonov regularization
# <img src="https://wikimedia.org/api/rest_v1/media/math/render/svg/7328255ad4abce052b3f6f39c43e974808d0cdb6">
# Caution: Do not regul... | return 1.0/(1.0 + np.exp(-x)) | identifier_body |
tos.py | p = self._read()
sys.stdout.write(".")
if not self._debug:
sys.stdout.write("\n")
self._s.close()
self._s = serial.Serial(port, baudrate, rtscts=0, timeout=None)
thread.start_new_thread(self.run, ())
def run(self):
while True:
... |
self._out_lock.acquire()
self._seqno = (self._seqno + 1) % 100
packet = DataFrame();
packet.protocol = self.SERIAL_PROTO_PACKET_ACK
packet.seqno = self._seqno
packet.dispatch = 0
packet.data = payload
packet = packet.payload()
crc = self._crc16(0,... | payload = payload.payload() | conditional_block |
tos.py | ", self._s.read())[0]
return r
except struct.error:
# Serial port read timeout
raise socket.timeout
def _put_bytes(self, data):
#print "DEBUG: _put_bytes:", data
for b in data:
self._s.write(struct.pack('B', b))
def _unescape(self... | ActiveMessage | identifier_name | |
tos.py | p = self._read()
sys.stdout.write(".")
if not self._debug:
sys.stdout.write("\n")
self._s.close()
self._s = serial.Serial(port, baudrate, rtscts=0, timeout=None)
thread.start_new_thread(self.run, ())
def run(self):
while True:
... | self._s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._s.connect((host, port))
data = self._s.recv(2)
if data != 'U ':
print "Wrong handshake"
self._s.send("U ")
print "Connected"
thread.start_new_thread(self.run, ())
def run(self):
... | class SFClient:
def __init__(self, host, port, qsize=10):
self._in_queue = Queue(qsize) | random_line_split |
tos.py | = 0
packet.data = payload
packet = packet.payload()
crc = self._crc16(0, packet)
packet.append(crc & 0xff)
packet.append((crc >> 8) & 0xff)
packet = [self.HDLC_FLAG_BYTE] + self._escape(packet) + [self.HDLC_FLAG_BYTE]
while True:
self._put_bytes(pack... | if type(name) == type(0):
return self._names[name]
else:
return self._values[self._names.index(name)] | identifier_body | |
screen.component.ts | Filter;
@Input() metricTree: INode;
@Input() metricMapping: IMetricMapping;
subscriptions: Subscription[] = [];
renderer: WebGLRenderer;
scene: Scene = new Scene();
// (see https://github.com/nicolaspanel/three-orbitcontrols-ts/issues/1)
camera: THREE.PerspectiveCamera;
controls: OrbitControls;
spati... | );
this.subscriptions.push(
this.screenInteractionService.cursorState$.subscribe((state => {
if (state.position) {
this.spatialCursor.position.copy(state.position);
this.tooltipService.setMousePosition(this.getTooltipPosition(), this.screenType);
}
this.spatialC... | this.highlightBoxes.forEach((value, index) => this.highlightElement(this.scene.getObjectByName(highlightedElements[index]), value));
}) | random_line_split |
screen.component.ts | ;
@Input() metricTree: INode;
@Input() metricMapping: IMetricMapping;
subscriptions: Subscription[] = [];
renderer: WebGLRenderer;
scene: Scene = new Scene();
// (see https://github.com/nicolaspanel/three-orbitcontrols-ts/issues/1)
camera: THREE.PerspectiveCamera;
controls: OrbitControls;
spatialCurs... | (changes: SimpleChanges) {
if (this.activeViewType !== null && this.metricTree !== null && this.activeFilter !== null) {
this.isMergedView = this.activeViewType === ViewType.MERGED;
this.interactionHandler.setIsMergedView(this.isMergedView);
if (this.isMergedView) {
this.view = new Merged... | ngOnChanges | identifier_name |
screen.component.ts | ;
@Input() metricTree: INode;
@Input() metricMapping: IMetricMapping;
subscriptions: Subscription[] = [];
renderer: WebGLRenderer;
scene: Scene = new Scene();
// (see https://github.com/nicolaspanel/three-orbitcontrols-ts/issues/1)
camera: THREE.PerspectiveCamera;
controls: OrbitControls;
spatialCurs... |
}
resumeRendering() {
if (this.renderingIsPaused) {
this.render();
this.renderingIsPaused = false;
}
}
prepareView(metricTree) {
if (metricTree.children.length === 0) {
return;
}
this.view.setMetricTree(metricTree);
this.view.recalculate();
this.view.getBlockElem... | {
cancelAnimationFrame(this.requestAnimationFrameId);
this.resetScene();
this.renderingIsPaused = true;
} | conditional_block |
screen.component.ts | this.activeViewType !== null && this.metricTree !== null && this.activeFilter !== null) {
this.isMergedView = this.activeViewType === ViewType.MERGED;
this.interactionHandler.setIsMergedView(this.isMergedView);
if (this.isMergedView) {
this.view = new MergedView(this.screenType, this.metricMa... | {
window.addEventListener('resize', this.handleViewChanged.bind(this), false);
} | identifier_body | |
zun.go | fmt.Errorf("mysql op is error : %s ", err)
}
return err
}
func CreateZunContainerOpts(pod *v1.Pod) (createOpts zun_container.CreateOpts, err error) {
if pod == nil {
err = fmt.Errorf("Pod is null.CreateZunContainerOpts function in zun ")
return
}
for _, container := range pod.Spec.Containers {
// get pod ... | (c *zun_container.Container, podInfo *PodOTemplate) (pod *v1.Pod, err error) {
containers := make([]v1.Container, 1)
containerStatuses := make([]v1.ContainerStatus, 0)
containerMemoryMB := 0
if c.Memory != "" {
containerMemory, err := strconv.Atoi(c.Memory)
if err != nil {
log.Println(err)
}
containerMem... | containerToPod | identifier_name |
zun.go | fmt.Errorf("mysql op is error : %s ", err)
}
return err
}
func CreateZunContainerOpts(pod *v1.Pod) (createOpts zun_container.CreateOpts, err error) {
if pod == nil {
err = fmt.Errorf("Pod is null.CreateZunContainerOpts function in zun ")
return
}
for _, container := range pod.Spec.Containers {
// get pod ... |
createOpts.Cpu = cpuLimit
createOpts.Memory = int(memoryLimit)
} else if container.Resources.Requests != nil {
cpuRequests := float64(1)
if _, ok := container.Resources.Requests[v1.ResourceCPU]; ok {
cpuRequests = float64(container.Resources.Requests.Cpu().MilliValue()) / 1000.00
}
memoryRequ... | {
memoryLimit = float64(container.Resources.Limits.Memory().Value()) / (1024 * 1024)
} | conditional_block |
zun.go | fmt.Errorf("mysql op is error : %s ", err)
}
return err
}
func CreateZunContainerOpts(pod *v1.Pod) (createOpts zun_container.CreateOpts, err error) {
if pod == nil {
err = fmt.Errorf("Pod is null.CreateZunContainerOpts function in zun ")
return
}
for _, container := range pod.Spec.Containers {
// get pod ... | cpuLimit = float64(container.Resources.Limits.Cpu().MilliValue()) / 1000.00
}
memoryLimit := 0.5
if _, ok := container.Resources.Limits[v1.ResourceMemory]; ok {
memoryLimit = float64(container.Resources.Limits.Memory().Value()) / (1024 * 1024)
}
createOpts.Cpu = cpuLimit
createOpts.Memory = ... | if container.Resources.Limits != nil {
cpuLimit := float64(1)
if _, ok := container.Resources.Limits[v1.ResourceCPU]; ok { | random_line_split |
zun.go | odUid,
"CreationTimestamp": zunPod.podCreatetime,
}
// create container info
metadata.Name = zunPod.NamespaceName
podTemplate.Metadata = metadata
return podTemplate
}
func containerToPod(c *zun_container.Container, podInfo *PodOTemplate) (pod *v1.Pod, err error) {
containers := make([]v1.Container, 1)
contai... | {
return &v1.NodeDaemonEndpoints{
KubeletEndpoint: v1.DaemonEndpoint{
Port: p.daemonEndpointPort,
},
}
} | identifier_body | |
EDA.py | .reset_index(inplace=True)
get_data = h1_df.loc[h1_df['symbol'] == cp]['mid']
data = h1_df
t=10 # Rolling time window, and calculate mean and standard error
rolmean = get_data.rolling(window=t).mean()
rolstd = get_data.rolling(window=t).std()
BollingerBand(cp, data, rolmean, rolstd)
... | model = ARIMA(data_train, order=(p,1,1))
model_fit = model.fit(disp=0)
if model_fit.aic <= best_AIC:
best_model, best_AIC = model, model_fit.aic | conditional_block | |
EDA.py | qb.AddForex("EURUSD")
USDJPY = qb.AddForex("USDJPY")
GBPUSD = qb.AddForex("GBPUSD")
# ### III. Exploratory Data Analysis (EDA)
# #### This section analyses and justifies the various currency pairs chosen. Our group compared the volatility of the currency pairs using Bollinger Bands.
# #### Volatility Analysis of C... | dfoutput['Critical Value (%s)'%key] = value
print (dfoutput)
# #### This time, we find that Dickey-Fuller test is significant (p-value<5%). This means, after removing general trend, the time series data probably become stationary.
#
# #### However, let us decompose the time series into trend, seasonality and re... | # Dickey-Fuller test
dftest = adfuller(data_log_moving_avg_diff, autolag=None)
dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])
for key, value in dftest[4].items(): | random_line_split |
EDA.py | qb.AddForex("EURUSD")
USDJPY = qb.AddForex("USDJPY")
GBPUSD = qb.AddForex("GBPUSD")
# ### III. Exploratory Data Analysis (EDA)
# #### This section analyses and justifies the various currency pairs chosen. Our group compared the volatility of the currency pairs using Bollinger Bands.
# #### Volatility Analysis of C... |
ax.legend()
plt.show();
bollinger_upper = list(mean + std*2)
bollinger_lower = list(mean - std*2)
# In[271]:
## modified function for plotting BollingerBand ##
'''
Based off some research done online, our group has decided to drill down further
into the following 3 currency pairs due... | plt.style.use('fivethirtyeight')
fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot(111)
ax.set_title(cp)
ax.set_xlabel('Time')
ax.set_ylabel('Exchange Rate')
x_axis = list(data.loc[data['symbol'] == cp]['time'])
# x_axis = data.loc[data['symbol'] == cp].index.get_level_values(0)
... | identifier_body |
EDA.py | qb.AddForex("EURUSD")
USDJPY = qb.AddForex("USDJPY")
GBPUSD = qb.AddForex("GBPUSD")
# ### III. Exploratory Data Analysis (EDA)
# #### This section analyses and justifies the various currency pairs chosen. Our group compared the volatility of the currency pairs using Bollinger Bands.
# #### Volatility Analysis of C... | (cp, data, mean, std):
plt.style.use('fivethirtyeight')
fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot(111)
ax.set_title(cp)
ax.set_xlabel('Time')
ax.set_ylabel('Exchange Rate')
x_axis = list(data.loc[data['symbol'] == cp]['time'])
# x_axis = data.loc[data['symbol'] == cp].in... | BollingerBand | identifier_name |
inference.py | sequence': one_hots,
'sequence_length': row_lengths,
},
signature=signature,
as_dict=True).values())[0]
def in_graph_inferrer(sequences,
savedmodel_dir_path,
signature,
name_scope='inferrer'):
| """
# Add variable to make it easier to refactor with multiple tags in future.
tags = [tf.saved_model.tag_constants.SERVING]
# Tokenization
residues = tf.strings.unicode_split(sequences, 'UTF-8')
# Convert to one-hots and pad.
one_hots, row_lengths = utils.in_graph_residues_to_onehot(residues)
module_s... | """Add an in-graph inferrer to the active default graph.
Additionally performs in-graph preprocessing, splitting strings, and encoding
residues.
Args:
sequences: A tf.string Tensor representing a batch of sequences with shape
[None].
savedmodel_dir_path: Path to the directory with the SavedModel b... | identifier_body |
inference.py | sequence': one_hots,
'sequence_length': row_lengths,
},
signature=signature,
as_dict=True).values())[0]
def in_graph_inferrer(sequences,
savedmodel_dir_path,
signature,
name_scope='inferrer'):
"""Add an in-gr... | (self, name):
return self._graph.get_tensor_by_name('{}/{}'.format(
self._model_name_scope, name))
def _get_activations_for_batch_unmemoized(self,
seqs,
custom_tensor_to_retrieve=None):
"""Gets activations for eac... | _get_tensor_by_name | identifier_name |
inference.py |
"""Compute activations for trained model from input sequences."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import base64
import functools
import gzip
import io
import itertools
import os
from typing import Dict, FrozenSet, Iterator, List, Text, Tupl... | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License. | random_line_split | |
inference.py | .
Additionally performs in-graph preprocessing, splitting strings, and encoding
residues.
Args:
sequences: A tf.string Tensor representing a batch of sequences with shape
[None].
savedmodel_dir_path: Path to the directory with the SavedModel binary.
signature: Name of the signature to use in `... | raise ValueError('No SavedModels found in %s' % protein_export_base_path) | conditional_block | |
session.go | .
type Session struct {
*zoo.Zoo
id int
context context.Context
log *log.Entry
started time.Time
manager SessionManager
session netproto.Session
pumpErrors chan error
inactivityTimer *time.Timer
inactivityTimeout time.Duration
loc... |
l := log.WithField("streamType", streamType)
stream, err := s.session.OpenStream()
if err != nil {
return nil, err
}
streamId := stream.ID()
l = l.WithField("stream", streamId)
l.Debug("Stream opened (by us)")
rw := packet.NewPacketReadWriter(stream)
err = rw.WriteProtoPacket(&StreamInit{StreamType: uint... | {
return nil, fmt.Errorf("Unknown stream type: %d", streamType)
} | conditional_block |
session.go | peer.
type Session struct {
*zoo.Zoo
id int
context context.Context
log *log.Entry
started time.Time
manager SessionManager
session netproto.Session
pumpErrors chan error
inactivityTimer *time.Timer
inactivityTimeout time.Duration... | // GetLocalAddr returns the local address.
func (s *Session) GetLocalAddr() net.Addr {
return s.session.LocalAddr()
}
// GetRemoteAddr returns the remote address.
func (s *Session) GetRemoteAddr() net.Addr {
return | }
| random_line_split |
session.go | .
type Session struct {
*zoo.Zoo
id int
context context.Context
log *log.Entry
started time.Time
manager SessionManager
session netproto.Session
pumpErrors chan error
inactivityTimer *time.Timer
inactivityTimeout time.Duration
loc... |
// GetLocalAddr returns the local address.
func (s *Session) GetLocalAddr() net.Addr {
return s.session.LocalAddr()
}
// GetRemoteAddr returns the remote address.
func (s *Session) GetRemoteAddr() net.Addr | {
if s.inter != nil {
return s.inter
}
remAddr := s.session.RemoteAddr()
uadr, ok := remAddr.(*net.UDPAddr)
if !ok {
return nil
}
inter, _ := network.FromAddr(uadr.IP)
s.inter = inter
return inter
} | identifier_body |
session.go | .
type Session struct {
*zoo.Zoo
id int
context context.Context
log *log.Entry
started time.Time
manager SessionManager
session netproto.Session
pumpErrors chan error
inactivityTimer *time.Timer
inactivityTimeout time.Duration
loc... | (handler StreamHandler, stream netproto.Stream) {
id := stream.ID()
s.streamHandlersMtx.Lock()
s.streamHandlers[uint32(id)] = handler
s.streamHandlersMtx.Unlock()
ctx, ctxCancel := context.WithCancel(s.childContext)
defer ctxCancel()
err := handler.Handle(ctx)
l := s.log.WithField("stream", uint32(id))
sele... | runStreamHandler | identifier_name |
rpnet.py | out_channels=192, kernel_size=5, padding=2),
nn.BatchNorm2d(num_features=192),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2, padding=1),
nn.Dropout(0.2)
)
hidden8 = nn.Sequential(
nn.Conv2d(in_channels=192, out_channels=192, kernel_size=5, ... | x2 = self.wR2.module.features[2](_x1)
_x3 = self.wR2.module.features[3](x2)
x4 = self.wR2.module.features[4](_x3)
_x5 = self.wR2.module.features[5](x4)
x6 = self.wR2.module.features[6](_x5)
x7 = self.wR2.module.features[7](x6)
x8 = self.wR2.module.features[8](x7)... | torch.cuda.device_count()))
else:
self.wR2 = torch.nn.DataParallel(self.wR2)
if not path is None:
if use_gpu:
self.wR2.load_state_dict(torch.load(path))
else:
self.wR2.load_state_dict(torch.load(path,map_location='cpu'))
# ... | identifier_body |
rpnet.py | out_channels=192, kernel_size=5, padding=2),
nn.BatchNorm2d(num_features=192),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2, padding=1),
nn.Dropout(0.2)
)
hidden8 = nn.Sequential(
nn.Conv2d(in_channels=192, out_channels=192, kernel_size=5, ... |
class fh02(nn.Module):
def __init__(self, num_points, num_classes, wrPath=None):
super(fh02, self).__init__()
self.load_wR2(wrPath)
self.classifier1 = nn.Sequential(
# nn.Dropout(),
nn.Linear(53248, 128),
# nn.ReLU(inplace=True),
# nn.Dropout... | def forward(self, x):
x1 = self.features(x)
x11 = x1.view(x1.size(0), -1)
x = self.classifier(x11)
return x | random_line_split |
rpnet.py | tial(
nn.Conv2d(in_channels=3, out_channels=48, kernel_size=5, padding=2, stride=2),
nn.BatchNorm2d(num_features=48),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2, padding=1),
nn.Dropout(0.2)
)
hidden2 = nn.Sequential(
nn.Conv2d(... | uen | identifier_name | |
rpnet.py | reflects
(top, left, bottom, right)
:param rec2: (y0, x0, y1, x1)
:return: scala value of IoU
"""
# computing area of each rectangles
S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1])
S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1])
# computing the sum_area
sum_area = S... | {}/{}]===>train average loss:{} = [detection_loss : {} + cl | conditional_block | |
LatexGenerator.py | (nested_dict)
self.data = nested_dict ()
def organize (self):
self._group (self.truth_rs)
self._group (self.build_rs)
def _group (self, result_set):
for weakness in result_set.weaknesses ():
for suite in weakness.suites:
# Handle the flaws
for flaw in suite.flaws:
#... |
# Handle the bugs
for bug in suite.bugs:
# Find the target, this will create the necessary keys if required
target = self._get_target (weakness, suite, bug)
if not target:
# First time seeing this file/fuction/line, need to set its value
newdict =... | target['flaws'].append (flaw) | conditional_block |
LatexGenerator.py | (nested_dict)
self.data = nested_dict ()
def organize (self):
self._group (self.truth_rs)
self._group (self.build_rs)
def _group (self, result_set):
for weakness in result_set.weaknesses ():
for suite in weakness.suites:
# Handle the flaws
for flaw in suite.flaws:
#... |
# If there are 0 expected flaws, don't report on this datapoint.
# This can happen when there are only incidental flaws for
# the grainularity (i.e. line-based reporting where a line
# only has an incidental flaw)
if (0 == datapoint.tp + datapoint.fn):
logging.debug ('... | organizer = Organizer (grainularity,
truth,
build)
organizer.organize ()
# We create two permutations for each grainularity:
# One where Bugs with wrong checkers count as false postives ([tool].[grainularity].tex)
# One where Bugs with wrong checker... | identifier_body |
LatexGenerator.py | (nested_dict)
self.data = nested_dict ()
def organize (self):
self._group (self.truth_rs)
self._group (self.build_rs)
def _group (self, result_set):
for weakness in result_set.weaknesses ():
for suite in weakness.suites:
# Handle the flaws
for flaw in suite.flaws:
#... | (self, args):
# Call the base class (Command) init
super (LatexGenerator, self).parse_args (args)
self.pages = []
self.appendix = None
self.load_pages ()
#
# Load the pages
#
def load_pages (self):
# Some pages are repeated per grainularity (i.e. Summary). These should
# be in the... | parse_args | identifier_name |
LatexGenerator.py | (nested_dict)
self.data = nested_dict ()
| def organize (self):
self._group (self.truth_rs)
self._group (self.build_rs)
def _group (self, result_set):
for weakness in result_set.weaknesses ():
for suite in weakness.suites:
# Handle the flaws
for flaw in suite.flaws:
# Find the target, this will create the necessa... | random_line_split | |
admin.js | (e) {
dropArea.classList.add('highlight')
}
function unhighlight(e) {
dropArea.classList.remove('active')
}
function handleDrop(e) {
e.preventDefault();
e.stopPropagation();
var items = e.dataTransfer.items;
var files = e.dataTransfer.files;
console.log(items, files);
let p = Promise... | highlight | identifier_name | |
admin.js | .value = 0
uploadProgress = []
for (let i = numFiles; i > 0; i--) {
uploadProgress.push(0)
}
}
function updateProgress(fileNumber, percent) {
uploadProgress[fileNumber] = percent
let total = uploadProgress.reduce((tot, curr) => tot + curr, 0) / uploadProgress.length
console.debug('upda... | {
initVersionPanel();
initFi | identifier_body | |
admin.js | {
dropArea.classList.add('highlight')
}
function unhighlight(e) {
dropArea.classList.remove('active')
}
function handleDrop(e) {
e.preventDefault();
e.stopPropagation();
var items = e.dataTransfer.items;
var files = e.dataTransfer.files;
console.log(items, files);
let p = Promise.re... | });
}
function onUploadFilesDone() {
let data = {
version: document.getElementById("publishVersion").value,
update_teacher: document.getElementById("checkbox-update-teacher").checked,
update_student: document.getElementById("checkbox-update-student").checked,
update_server: docu... | random_line_split | |
admin.js | dropArea.classList.add('highlight')
}
function unhighlight(e) {
dropArea.classList.remove('active')
}
function handleDrop(e) {
e.preventDefault();
e.stopPropagation();
var items = e.dataTransfer.items;
var files = e.dataTransfer.files;
console.log(items, files);
let p = Promise.resol... | }, false);
return xhr;
},
type: "POST",
url: "./upload.php",
processData: false,
contentType: false,
success: function (data) {
console.log(data);
if (da... | var percentComplete = evt.loaded / evt.total;
//Do something with upload progress
$('#progressbar').css("width", (percentComplete * 100) + "%");
console.log(percentComplete);
}
| conditional_block |
demo.py | Initialized biophysical model", modelID
print '''
Please select from the following options:
1 - Run test pulse on model
2 - Fit model parameter to data
3 - Display static neuron model
4 - Visualize model dynamics
5 - Quit
'''
try:
... | continue
# test pulse example
if selection == 1:
# Run the model with a test pulse of the 'long square' type
print "Running model with a long square current injection pulse of 210pA"
output = currModel.long_square(0.21)
... | print "Invalid selection."
| random_line_split |
demo.py | except ValueError:
print "Invalid selection."
continue
# test pulse example
if selection == 1:
# Run the model with a test pulse of the 'long square' type
print "Running model with a long square current injection pulse of 21... | print "Loading parameters for model", modelID
selection=raw_input('Would you like to download NWB data for model? [Y/N] ')
if selection[0] == 'y' or selection[0] == 'Y':
currModel = Model(modelID, cache_stim = True)
if selection[0] == 'n' or selection[0] == 'N':
currModel = Model(modelI... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.