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
mod.rs
//! `types` module contains types necessary for Fluent runtime //! value handling. //! The core struct is [`FluentValue`] which is a type that can be passed //! to the [`FluentBundle::format_pattern`](crate::bundle::FluentBundle) as an argument, it can be passed //! to any Fluent Function, and any function may return i...
} impl<'source> From<&'source str> for FluentValue<'source> { fn from(s: &'source str) -> Self { FluentValue::String(s.into()) } } impl<'source> From<Cow<'source, str>> for FluentValue<'source> { fn from(s: Cow<'source, str>) -> Self { FluentValue::String(s) } } impl<'source, T> From...
{ FluentValue::String(s.into()) }
identifier_body
mod.rs
//! `types` module contains types necessary for Fluent runtime //! value handling. //! The core struct is [`FluentValue`] which is a type that can be passed //! to the [`FluentBundle::format_pattern`](crate::bundle::FluentBundle) as an argument, it can be passed //! to any Fluent Function, and any function may return i...
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
/********************************************************************** * * Simple Snake * * This code is designed to illustrate the non-intuitive approach to an * implementation, building a snake game as a cellular automaton rather * than the more obvious, set of entities (OOP) or a number of sets * of proce...
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
/********************************************************************** * * Simple Snake * * This code is designed to illustrate the non-intuitive approach to an * implementation, building a snake game as a cellular automaton rather * than the more obvious, set of entities (OOP) or a number of sets * of proce...
(color, age){ score = snake.__top_score = (!snake.__top_score || snake.__top_score.score < age) ? { color: color || '', score: age || 0, } : snake.__top_score snake._field.setAttribute('score', score.score) snake._field.setAttribute('snake', score.color) snake._field.setAttri...
showScore
identifier_name
simplesnake.js
/********************************************************************** * * Simple Snake * * This code is designed to illustrate the non-intuitive approach to an * implementation, building a snake game as a cellular automaton rather * than the more obvious, set of entities (OOP) or a number of sets * of proce...
function digitizeBackground(snake, walls){ snake._cells.forEach(function(c){ var v = Math.floor(Math.random() * 6) // bg cell... c.classList.length == 0 ? (c.style.backgroundColor = `rgb(${255 - v}, ${255 - v}, ${255 - v})`) // wall... : walls && c.classList.contains('wall') ? (c.style....
{ document.body.classList.remove('hints') }
identifier_body
simplesnake.js
/********************************************************************** * * Simple Snake * * This code is designed to illustrate the non-intuitive approach to an * implementation, building a snake game as a cellular automaton rather * than the more obvious, set of entities (OOP) or a number of sets * of proce...
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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #### test #### # import random ############## import sys import os from ADS1256_definitions import * from pipyadc import ADS1256 import time, datetime import csv import numpy as np from matplotlib import pyplot as plt import pandas as pd import matplotlib as mpl mpl.rc...
# 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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #### test #### # import random ############## import sys import os from ADS1256_definitions import * from pipyadc import ADS1256 import time, datetime import csv import numpy as np from matplotlib import pyplot as plt import pandas as pd import matplotlib as mpl mpl.rc...
(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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #### test #### # import random ############## import sys import os from ADS1256_definitions import * from pipyadc import ADS1256 import time, datetime import csv import numpy as np from matplotlib import pyplot as plt import pandas as pd import matplotlib as mpl mpl.rc...
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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #### test #### # import random ############## import sys import os from ADS1256_definitions import * from pipyadc import ADS1256 import time, datetime import csv import numpy as np from matplotlib import pyplot as plt import pandas as pd import matplotlib as mpl mpl.rc...
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
"""Swagger 2.0 validation see https://github.com/swagger-api/swagger-editor/tree/master/src/plugins/validate-semantic for semantic rules (i.e. beyond teh JSONSchema validation of the swagger)""" import json import numbers import re from itertools import groupby from pathlib import Path from typing import Set, Dict, Tu...
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
"""Swagger 2.0 validation see https://github.com/swagger-api/swagger-editor/tree/master/src/plugins/validate-semantic for semantic rules (i.e. beyond teh JSONSchema validation of the swagger)""" import json import numbers import re from itertools import groupby from pathlib import Path from typing import Set, Dict, Tu...
return events def detect_duplicate_operationId(swagger: Dict): """Return list of Action with duplicate operationIds""" events = set() # retrieve all operationIds operationId_jspath = JSPATH_OPERATIONID def get_operationId_name(name_value_path): return name_value_path[1] operat...
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
"""Swagger 2.0 validation see https://github.com/swagger-api/swagger-editor/tree/master/src/plugins/validate-semantic for semantic rules (i.e. beyond teh JSONSchema validation of the swagger)""" import json import numbers import re from itertools import groupby from pathlib import Path from typing import Set, Dict, Tu...
def check_parameters(swagger: Dict): """ Check parameters for: - duplicate items in enum - default parameter is in line with type when type=string :param swagger: :return: """ events = set() parameters_jspath = JSPATH_PARAMETERS for _, param, path in get_elements(swagger, p...
"""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
"""Swagger 2.0 validation see https://github.com/swagger-api/swagger-editor/tree/master/src/plugins/validate-semantic for semantic rules (i.e. beyond teh JSONSchema validation of the swagger)""" import json import numbers import re from itertools import groupby from pathlib import Path from typing import Set, Dict, Tu...
(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
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { fidl_fuchsia_io as fio, fuchsia_zircon as zx, rand::{thread_rng, Rng}, tracing::warn, }; const TEMPFILE_RANDOM_LENGTH: usize = 8usize; ...
&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
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { fidl_fuchsia_io as fio, fuchsia_zircon as zx, rand::{thread_rng, Rng}, tracing::warn, }; const TEMPFILE_RANDOM_LENGTH: usize = 8usize; ...
} } } 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
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { fidl_fuchsia_io as fio, fuchsia_zircon as zx, rand::{thread_rng, Rng}, tracing::warn, }; const TEMPFILE_RANDOM_LENGTH: usize = 8usize; ...
{ /// 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
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { fidl_fuchsia_io as fio, fuchsia_zircon as zx, rand::{thread_rng, Rng}, tracing::warn, }; const TEMPFILE_RANDOM_LENGTH: usize = 8usize; ...
#[test] fn test_generate_tempfile_name() { let name1 = generate_tempfile_name("temp-12345"); let name2 = generate_tempfile_name("temp-12345"); let prefix = "temp-12345-"; assert!(name1.starts_with(prefix)); assert!(name2.starts_with(prefix)); assert_eq!(name1.le...
{ 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
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright © 2013 Martin Ueding <dev@martin-ueding.de> import argparse import matplotlib.pyplot as pl import numpy as np import scipy.optimize as op from prettytable import PrettyTable __docformat__ = "restructuredtext en" # Sensitivität der Thermosäule S = 30e-6 def phi
: 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
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright © 2013 Martin Ueding <dev@martin-ueding.de> import argparse import matplotlib.pyplot as pl import numpy as np import scipy.optimize as op from prettytable import PrettyTable __docformat__ = "restructuredtext en" # Sensitivität der Thermosäule S = 30e-6 def phif...
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
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright © 2013 Martin Ueding <dev@martin-ueding.de> import argparse import matplotlib.pyplot as pl import numpy as np import scipy.optimize as op from prettytable import PrettyTable __docformat__ = "restructuredtext en" # Sensitivität der Thermosäule S = 30e-6 def phif...
return parser.parse_args() if __name__ == "__main__": main()
random_line_split
python3
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright © 2013 Martin Ueding <dev@martin-ueding.de> import argparse import matplotlib.pyplot as pl import numpy as np import scipy.optimize as op from prettytable import PrettyTable __docformat__ = "restructuredtext en" # Sensitivität der Thermosäule S = 30e-6 def phif...
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
""" Compute joint probabilities and pseudo-likelihood estimate for a Bayes Net according to random selection semantics from a database. Written in haste---bugs likely remain! It's also been eight months since I wrote real python, so some things might be more concisely expressed using standard idioms. ...
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
""" Compute joint probabilities and pseudo-likelihood estimate for a Bayes Net according to random selection semantics from a database. Written in haste---bugs likely remain! It's also been eight months since I wrote real python, so some things might be more concisely expressed using standard idioms. ...
(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
""" Compute joint probabilities and pseudo-likelihood estimate for a Bayes Net according to random selection semantics from a database. Written in haste---bugs likely remain! It's also been eight months since I wrote real python, so some things might be more concisely expressed using standard idioms. ...
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
""" Compute joint probabilities and pseudo-likelihood estimate for a Bayes Net according to random selection semantics from a database. Written in haste---bugs likely remain! It's also been eight months since I wrote real python, so some things might be more concisely expressed using standard idioms. ...
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
//! Operation result structures and helpers. //! //! Most LDAP operations return an [`LdapResult`](struct.LdapResult.html). This module //! contains its definition, as well as that of a number of wrapper structs and //! helper methods, which adapt LDAP result and error handling to be a closer //! match to Rust conventi...
(pub LdapResult); impl CompareResult { /// If the result code is 5 (compareFalse) or 6 (compareTrue), return the corresponding /// boolean value wrapped in `Ok()`, otherwise wrap the `LdapResult` part in an `LdapError`. pub fn equal(self) -> Result<bool> { match self.0.rc { 5 => Ok(fals...
CompareResult
identifier_name
result.rs
//! Operation result structures and helpers. //! //! Most LDAP operations return an [`LdapResult`](struct.LdapResult.html). This module //! contains its definition, as well as that of a number of wrapper structs and //! helper methods, which adapt LDAP result and error handling to be a closer //! match to Rust conventi...
/// 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
# from re import X # from django.db.models import Q # from django.http import request # from django.http.response import HttpResponse # Qオブジェクトは、モデルのデータの中からor検索をする from django.shortcuts import get_object_or_404, redirect, render # from django.views import generic # from plotly import graph_objs # from .forms import Re...
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
# from re import X # from django.db.models import Q # from django.http import request # from django.http.response import HttpResponse # Qオブジェクトは、モデルのデータの中からor検索をする from django.shortcuts import get_object_or_404, redirect, render # from django.views import generic # from plotly import graph_objs # from .forms import Re...
'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
# from re import X # from django.db.models import Q # from django.http import request # from django.http.response import HttpResponse # Qオブジェクトは、モデルのデータの中からor検索をする from django.shortcuts import get_object_or_404, redirect, render # from django.views import generic # from plotly import graph_objs # from .forms import Re...
'y': 0.94, 'yanchor': 'bottom', 'yref': 'paper'}, {'font': {'size': 14}, 'showarrow': False, 'text': '学年順位', 'x': 0.05, 'xref': 'paper', ...
'text': '学習記録', 'x': 0.05, 'xref': 'paper',
random_line_split
graph_views.py
# from re import X # from django.db.models import Q # from django.http import request # from django.http.response import HttpResponse # Qオブジェクトは、モデルのデータの中からor検索をする from django.shortcuts import get_object_or_404, redirect, render # from django.views import generic # from plotly import graph_objs # from .forms import Re...
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
package main import ( "bytes" "fmt" "unicode" ) func main() { //compareDemo() //containsDemo() //containsAnyDemo() //containsRuneDemo() //countDemo() //equalDemo() //equalFoldDemo() //fieldsDemo() //fieldsFuncDemo() //hasPrefixDemo() //hasSuffixDemo() //indexFuncDemo() //jsonDemo() //lastIndexDemo() ...
une) bool { if c == '世' { return true } return false } fmt.Println(bytes.LastIndexFunc([]byte("Hello, 世界"), f2)) fmt.Println(bytes.LastIndexFunc([]byte("Hello, world"), f2)) } //21 func Map(mapping func(r rune) rune, s []byte) []byte //做替换单个字符 //Map 根据映射函数返回字节切片s的所有字符修改后的副本。如果映射返回负值, // 则字符将从字符串中删除而不会被替换。 ...
2 := func(c r
identifier_name
bytesDemo.go
package main import ( "bytes" "fmt" "unicode" ) func main() { //compareDemo() //containsDemo() //containsAnyDemo() //containsRuneDemo() //countDemo() //equalDemo() //equalFoldDemo() //fieldsDemo() //fieldsFuncDemo() //hasPrefixDemo() //hasSuffixDemo() //indexFuncDemo() //jsonDemo() //lastIndexDemo() ...
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
package main import ( "bytes" "fmt" "unicode" ) func main() { //compareDemo() //containsDemo() //containsAnyDemo() //containsRuneDemo() //countDemo() //equalDemo() //equalFoldDemo() //fieldsDemo() //fieldsFuncDemo() //hasPrefixDemo() //hasSuffixDemo() //indexFuncDemo() //jsonDemo() //lastIndexDemo() ...
//29 func Title 转大写 //func Title(s []byte) []byte //标题返回一个 s 的副本,其中包含所有 Unicode 字母,这些字母开始被映射到其标题大小写。 //BUG(rsc):规则标题用于单词边界的规则不能正确处理 Unicode 标点符号。 func titleDemo() { //ToTitle 全部大写 title首字母大写 fmt.Printf("%s", bytes.ToTitle([]byte("her royal highness"))) } //30 func ToLower 转小写 //func ToLower(s []byte) []byte //To...
//28 SplitAfterN 参考SplitN //func SplitAfterN(s, sep []byte, n int) [][]byte //在每个 sep 实例之后,SplitAfterN 将 s 分割成子项,并返回这些子项的一部分。 // 如果 sep 为空,则 SplitAfterN 在每个 UTF-8 序列之后分割。计数确定要返回的子备份数量:
random_line_split
bytesDemo.go
package main import ( "bytes" "fmt" "unicode" ) func main() { //compareDemo() //containsDemo() //containsAnyDemo() //containsRuneDemo() //countDemo() //equalDemo() //equalFoldDemo() //fieldsDemo() //fieldsFuncDemo() //hasPrefixDemo() //hasSuffixDemo() //indexFuncDemo() //jsonDemo() //lastIndexDemo() ...
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
import { Matrix4 } from "three/src/math/Matrix4" function id(element: HTMLElement) { return element.id ? `#${element.id}` : '' } function classes(element: HTMLElement)
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
import { Matrix4 } from "three/src/math/Matrix4" function id(element: HTMLElement) { return element.id ? `#${element.id}` : '' } function classes(element: HTMLElement) { let classSelector = '' const classList = element.classList for (const c of classList) { classSelector += '.' + c } return classSelec...
} 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
import { Matrix4 } from "three/src/math/Matrix4" function id(element: HTMLElement) { return element.id ? `#${element.id}` : '' } function classes(element: HTMLElement) { let classSelector = '' const classList = element.classList for (const c of classList) { classSelector += '.' + c } return classSelec...
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
import { Matrix4 } from "three/src/math/Matrix4" function id(element: HTMLElement) { return element.id ? `#${element.id}` : '' } function classes(element: HTMLElement) { let classSelector = '' const classList = element.classList for (const c of classList) { classSelector += '.' + c } return classSelec...
(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
/** * Defines a legend for a chart's series. * The 'chart' member must be set prior to rendering. * The legend class displays a list of legend items each of them related with a * series being rendered. In order to render the legend item of the proper series * the series configuration object must have {@link Ext.ch...
(this.getPopup() ? this.getSheet() : this.getView()).show(); }, /** * Hides the legend if it is currently shown. */ hide: function () { (this.getPopup() ? this.getSheet() : this.getView()).hide(); }, /** * @protected Fired when two legend items are combined via drag-...
/** * Shows the legend if it is currently hidden. */ show: function () {
random_line_split
Legend.js
/** * Defines a legend for a chart's series. * The 'chart' member must be set prior to rendering. * The legend class displays a list of legend items each of them related with a * series being rendered. In order to render the legend item of the proper series * the series configuration object must have {@link Ext.ch...
else { view.hide(); } } }, /** * Calculate and return the number of pixels that should be reserved for the legend along * its edge. Only returns a non-zero value if the legend is positioned to one of the four * named edges, and if it is not {@link #dock docke...
{ // 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
use super::Source; use super::huffman::Huffman; use super::bitstream::BitStream; use super::bufferedwriter::BufferedWriter; struct DynamicBlock { // If we encounter a repeat, we should set our state so that we keep producing // repeats until they run out, instead of reading from the bit stream. repeats_remaining: u...
} impl <'a> Source<Option<u8>> for DEFLATEReader<'a> { fn next(self: &mut DEFLATEReader<'a>) -> Option<u8> { // We set this field when we have finished with a block or haven't started yet // this field tells us that we should begin reading a new block which involves // decoding all the headers and huffman tree...
{ DEFLATEReader{ buffered_writer: BufferedWriter::new(), bit_stream: BitStream::new(input), has_seen_final_block: false, current_block: None, } }
identifier_body
deflate.rs
use super::Source; use super::huffman::Huffman; use super::bitstream::BitStream; use super::bufferedwriter::BufferedWriter; struct DynamicBlock { // If we encounter a repeat, we should set our state so that we keep producing // repeats until they run out, instead of reading from the bit stream. repeats_remaining: u...
<'a> { // The following two fields are used to manage input/output buffered_writer: BufferedWriter, bit_stream: BitStream<'a>, // The following two fields control if we read another block has_seen_final_block: bool, current_block: Option<DynamicBlock>, } const BTYPE_DYNAMIC : u8 = 0b10; impl <'a> DEFLATEReader...
DEFLATEReader
identifier_name
deflate.rs
use super::Source; use super::huffman::Huffman; use super::bitstream::BitStream; use super::bufferedwriter::BufferedWriter; struct DynamicBlock { // If we encounter a repeat, we should set our state so that we keep producing // repeats until they run out, instead of reading from the bit stream. repeats_remaining: u...
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
use super::Source; use super::huffman::Huffman; use super::bitstream::BitStream; use super::bufferedwriter::BufferedWriter; struct DynamicBlock { // If we encounter a repeat, we should set our state so that we keep producing // repeats until they run out, instead of reading from the bit stream. repeats_remaining: u...
}, 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
#!/usr/bin/env python """A simple interactive kernel that talks to a frontend over 0MQ. Things to do: * Implement `set_parent` logic. Right before doing exec, the Kernel should call set_parent on all the PUB objects with the message about to be executed. * Implement random port and security key logic. * Implement c...
(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
#!/usr/bin/env python """A simple interactive kernel that talks to a frontend over 0MQ. Things to do: * Implement `set_parent` logic. Right before doing exec, the Kernel should call set_parent on all the PUB objects with the message about to be executed. * Implement random port and security key logic. * Implement c...
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
#!/usr/bin/env python """A simple interactive kernel that talks to a frontend over 0MQ. Things to do: * Implement `set_parent` logic. Right before doing exec, the Kernel should call set_parent on all the PUB objects with the message about to be executed. * Implement random port and security key logic. * Implement c...
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
#!/usr/bin/env python """A simple interactive kernel that talks to a frontend over 0MQ. Things to do: * Implement `set_parent` logic. Right before doing exec, the Kernel should call set_parent on all the PUB objects with the message about to be executed. * Implement random port and security key logic. * Implement c...
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
import time from ..SCPI import scpi # main class # ========== class E4418(scpi.scpi_family): manufacturer = 'Agilent' product_name = 'E4418' classification = 'Power Meter' _scpi_enable = '*CLS *DDT *ESE *ESR? *IDN? *OPC *OPT? *RCL *RST *SAV ' +\ '*SRE *STB? *TST? *WAI' ...
_msg = 'Power meter returned Error message.\n' emsg = '%s (%d)\n'%(msg, num) _msg += '*'*len(emsg) + '\n' _msg += emsg _msg += '*'*len(emsg) + '\n' raise StandardError(_msg) return
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
import time from ..SCPI import scpi # main class # ========== class E4418(scpi.scpi_family): manufacturer = 'Agilent' product_name = 'E4418' classification = 'Power Meter' _scpi_enable = '*CLS *DDT *ESE *ESR? *IDN? *OPC *OPT? *RCL *RST *SAV ' +\ '*SRE *STB? *TST? *WAI' ...
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
import time from ..SCPI import scpi # main class # ========== class E4418(scpi.scpi_family): manufacturer = 'Agilent' product_name = 'E4418' classification = 'Power Meter' _scpi_enable = '*CLS *DDT *ESE *ESR? *IDN? *OPC *OPT? *RCL *RST *SAV ' +\ '*SRE *STB? *TST? *WAI' ...
------------------------------- 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
import time from ..SCPI import scpi # main class # ========== class E4418(scpi.scpi_family): manufacturer = 'Agilent' product_name = 'E4418' classification = 'Power Meter' _scpi_enable = '*CLS *DDT *ESE *ESR? *IDN? *OPC *OPT? *RCL *RST *SAV ' +\ '*SRE *STB? *TST? *WAI' ...
(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
// #! global // #![warn()] enable // #![allow()] disable #![allow(non_snake_case)] #![allow(dead_code)] use hmac::Hmac; use http::method; use openssl::{hash, pkcs5::pbkdf2_hmac}; use reqwest::Client; use std::{borrow::Borrow, collections::{HashMap, VecDeque}, default, ops::Index}; use std::{fs::File, usize}; // use sh...
} 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
// #! global // #![warn()] enable // #![allow()] disable #![allow(non_snake_case)] #![allow(dead_code)] use hmac::Hmac; use http::method; use openssl::{hash, pkcs5::pbkdf2_hmac}; use reqwest::Client; use std::{borrow::Borrow, collections::{HashMap, VecDeque}, default, ops::Index}; use std::{fs::File, usize}; // use sh...
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
// #! global // #![warn()] enable // #![allow()] disable #![allow(non_snake_case)] #![allow(dead_code)] use hmac::Hmac; use http::method; use openssl::{hash, pkcs5::pbkdf2_hmac}; use reqwest::Client; use std::{borrow::Borrow, collections::{HashMap, VecDeque}, default, ops::Index}; use std::{fs::File, usize}; // use sh...
(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
// #! global // #![warn()] enable // #![allow()] disable #![allow(non_snake_case)] #![allow(dead_code)] use hmac::Hmac; use http::method; use openssl::{hash, pkcs5::pbkdf2_hmac}; use reqwest::Client; use std::{borrow::Borrow, collections::{HashMap, VecDeque}, default, ops::Index}; use std::{fs::File, usize}; // use sh...
.to_string(), ":".to_string(), sign_str, ]; let _back_str = back_vec.concat(); } #[test] fn hmac_test() { let value = "xx".as_bytes(); let key = "yy".as_bytes(); assert_eq!( "3124cf1daef6d713c312065988652d8b7fca587e".to_string(), ...
ring> = vec![ "Upyun".to_string(), "Operator"
conditional_block
BankDataset.py
# coding: utf-8 # In[1]: get_ipython().run_cell_magic('javascript', '', '<!-- Ignore this block -->\nIPython.OutputArea.prototype._should_scroll = function(lines) {\n return false;\n}') # In[2]: #%config InlineBackend.figure_format = 'retina' from __future__ import division import pandas as pd from itertool...
"""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
# coding: utf-8 # In[1]: get_ipython().run_cell_magic('javascript', '', '<!-- Ignore this block -->\nIPython.OutputArea.prototype._should_scroll = function(lines) {\n return false;\n}') # In[2]: #%config InlineBackend.figure_format = 'retina' from __future__ import division import pandas as pd from itertools...
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
# coding: utf-8 # In[1]: get_ipython().run_cell_magic('javascript', '', '<!-- Ignore this block -->\nIPython.OutputArea.prototype._should_scroll = function(lines) {\n return false;\n}') # In[2]: #%config InlineBackend.figure_format = 'retina' from __future__ import division import pandas as pd from itertool...
(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
# coding: utf-8 # In[1]: get_ipython().run_cell_magic('javascript', '', '<!-- Ignore this block -->\nIPython.OutputArea.prototype._should_scroll = function(lines) {\n return false;\n}') # In[2]: #%config InlineBackend.figure_format = 'retina' from __future__ import division import pandas as pd from itertool...
# ## 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
# Copyright (c) 2008 Johns Hopkins University. # All rights reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose, without fee, and without written # agreement is hereby granted, provided that the above copyright # notice, the (updated) modification history ...
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
# Copyright (c) 2008 Johns Hopkins University. # All rights reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose, without fee, and without written # agreement is hereby granted, provided that the above copyright # notice, the (updated) modification history ...
(Packet): def __init__(self, gpacket = None, amid = 0x00, dest = 0xFFFF): if type(gpacket) == type([]): payload = gpacket else: # Assume this will be derived from Packet payload = None Packet.__init__(self, [('destination', 'int', 2...
ActiveMessage
identifier_name
tos.py
# Copyright (c) 2008 Johns Hopkins University. # All rights reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose, without fee, and without written # agreement is hereby granted, provided that the above copyright # notice, the (updated) modification history ...
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
# Copyright (c) 2008 Johns Hopkins University. # All rights reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose, without fee, and without written # agreement is hereby granted, provided that the above copyright # notice, the (updated) modification history ...
def __setattr__(self, name, value): if type(name) == type(0): self._values[name] = value else: self._values[self._names.index(name)] = value def __ne__(self, other): if other.__class__ == self.__class__: return self._values != other._values ...
if type(name) == type(0): return self._names[name] else: return self._values[self._names.index(name)]
identifier_body
screen.component.ts
import {Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges} from '@angular/core'; import * as THREE from 'three'; import { BoxGeometry, Line, Mesh, MeshBasicMaterial, Object3D, Scene, Vector2, Vector3, WebGLRenderer } from 'three'; import * as TWEEN from '@tweenjs/tween.js'; import {Subscr...
); 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
import {Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges} from '@angular/core'; import * as THREE from 'three'; import { BoxGeometry, Line, Mesh, MeshBasicMaterial, Object3D, Scene, Vector2, Vector3, WebGLRenderer } from 'three'; import * as TWEEN from '@tweenjs/tween.js'; import {Subscr...
(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
import {Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges} from '@angular/core'; import * as THREE from 'three'; import { BoxGeometry, Line, Mesh, MeshBasicMaterial, Object3D, Scene, Vector2, Vector3, WebGLRenderer } from 'three'; import * as TWEEN from '@tweenjs/tween.js'; import {Subscr...
} 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
import {Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges} from '@angular/core'; import * as THREE from 'three'; import { BoxGeometry, Line, Mesh, MeshBasicMaterial, Object3D, Scene, Vector2, Vector3, WebGLRenderer } from 'three'; import * as TWEEN from '@tweenjs/tween.js'; import {Subscr...
private handleViewChanged() { this.updateCamera(); this.updateRenderer(); } private applyFilter(activeFilter: IFilter) { for (let i = this.scene.children.length - 1; i >= 0; i--) { const node = this.scene.children[i]; if (node.userData && (node.userData.type === NodeType.FILE || node.us...
{ window.addEventListener('resize', this.handleViewChanged.bind(this), false); }
identifier_body
zun.go
package openstack import ( "context" "fmt" "github.com/gophercloud/gophercloud" "github.com/gophercloud/gophercloud/openstack" zun_container "github.com/gophercloud/gophercloud/openstack/container/v1/container" "github.com/gophercloud/gophercloud/pagination" "github.com/virtual-kubelet/virtual-kubelet/manager" ...
(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
package openstack import ( "context" "fmt" "github.com/gophercloud/gophercloud" "github.com/gophercloud/gophercloud/openstack" zun_container "github.com/gophercloud/gophercloud/openstack/container/v1/container" "github.com/gophercloud/gophercloud/pagination" "github.com/virtual-kubelet/virtual-kubelet/manager" ...
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
package openstack import ( "context" "fmt" "github.com/gophercloud/gophercloud" "github.com/gophercloud/gophercloud/openstack" zun_container "github.com/gophercloud/gophercloud/openstack/container/v1/container" "github.com/gophercloud/gophercloud/pagination" "github.com/virtual-kubelet/virtual-kubelet/manager" ...
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
package openstack import ( "context" "fmt" "github.com/gophercloud/gophercloud" "github.com/gophercloud/gophercloud/openstack" zun_container "github.com/gophercloud/gophercloud/openstack/container/v1/container" "github.com/gophercloud/gophercloud/pagination" "github.com/virtual-kubelet/virtual-kubelet/manager" ...
// OperatingSystem returns the operating system the provider is for. func (p *ZunProvider) OperatingSystem() string { if p.operatingSystem != "" { return p.operatingSystem } return providers.OperatingSystemLinux } func zunContainerStausToContainerStatus(cs *zun_container.Container) v1.ContainerState { // Zun a...
{ return &v1.NodeDaemonEndpoints{ KubeletEndpoint: v1.DaemonEndpoint{ Port: p.daemonEndpointPort, }, } }
identifier_body
EDA.py
#!/usr/bin/env python # coding: utf-8 # ![QuantConnect Logo](https://cdn.quantconnect.com/web/i/logo-small.png) # # ## BT2101 Final Project # ### I. Import Libraries # In[268]: get_ipython().run_line_magic('matplotlib', 'inline') # Imports from clr import AddReference AddReference("System") AddReference("QuantCo...
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
#!/usr/bin/env python # coding: utf-8 # ![QuantConnect Logo](https://cdn.quantconnect.com/web/i/logo-small.png) # # ## BT2101 Final Project # ### I. Import Libraries # In[268]: get_ipython().run_line_magic('matplotlib', 'inline') # Imports from clr import AddReference AddReference("System") AddReference("QuantCo...
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
#!/usr/bin/env python # coding: utf-8 # ![QuantConnect Logo](https://cdn.quantconnect.com/web/i/logo-small.png) # # ## BT2101 Final Project # ### I. Import Libraries # In[268]: get_ipython().run_line_magic('matplotlib', 'inline') # Imports from clr import AddReference AddReference("System") AddReference("QuantCo...
# 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 to their relatively higher volatility. The pair with the highest volatility was eventually chosen as the base pair acting a...
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
#!/usr/bin/env python # coding: utf-8 # ![QuantConnect Logo](https://cdn.quantconnect.com/web/i/logo-small.png) # # ## BT2101 Final Project # ### I. Import Libraries # In[268]: get_ipython().run_line_magic('matplotlib', 'inline') # Imports from clr import AddReference AddReference("System") AddReference("QuantCo...
(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
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
@functools.lru_cache(maxsize=None) def memoized_inferrer( savedmodel_dir_path, activation_type=tf.saved_model.signature_constants .DEFAULT_SERVING_SIGNATURE_DEF_KEY, batch_size=16, use_tqdm=False, session_config=None, memoize_inference_results=False, use_latest_savedmodel=False, ): ...
"""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
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
(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
# coding=utf-8 # Copyright 2020 The Google Research 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 #
"""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
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
# Sort by suffix to take the model corresponding the most # recent training step. return os.path.join(protein_export_base_path, sorted(suffixes)[-1]) def predictions_for_df(df, inferrer): """Returns df with column that's the activations for each sequence. Args: df: DataFrame with columns 'sequence' a...
raise ValueError('No SavedModels found in %s' % protein_export_base_path)
conditional_block
session.go
package session import ( "context" "crypto/tls" "crypto/x509" "errors" "fmt" "io" "net" "sync" "time" log "github.com/Sirupsen/logrus" "github.com/fuserobotics/netproto" "github.com/fuserobotics/quic-channel/identity" "github.com/fuserobotics/quic-channel/network" "github.com/fuserobotics/quic-channel/p...
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
package session import ( "context" "crypto/tls" "crypto/x509" "errors" "fmt" "io" "net" "sync" "time" log "github.com/Sirupsen/logrus" "github.com/fuserobotics/netproto" "github.com/fuserobotics/quic-channel/identity" "github.com/fuserobotics/quic-channel/network" "github.com/fuserobotics/quic-channel/p...
// 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 s.session.RemoteAddr() } // acceptStreamPump handles incoming streams. func (s *Session) acceptStream...
}
random_line_split
session.go
package session import ( "context" "crypto/tls" "crypto/x509" "errors" "fmt" "io" "net" "sync" "time" log "github.com/Sirupsen/logrus" "github.com/fuserobotics/netproto" "github.com/fuserobotics/quic-channel/identity" "github.com/fuserobotics/quic-channel/network" "github.com/fuserobotics/quic-channel/p...
// 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 s.session.RemoteAddr() } // acceptStreamPump handles incoming streams. func (s *Session) acceptStre...
{ 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
package session import ( "context" "crypto/tls" "crypto/x509" "errors" "fmt" "io" "net" "sync" "time" log "github.com/Sirupsen/logrus" "github.com/fuserobotics/netproto" "github.com/fuserobotics/quic-channel/identity" "github.com/fuserobotics/quic-channel/network" "github.com/fuserobotics/quic-channel/p...
(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
# Compared to fh0.py # fh02.py remove the redundant ims in model input from __future__ import print_function, division import cv2 import torch import torch.nn as nn import torch.optim as optim import sys from torch.autograd import Variable import numpy as np import os import argparse from time import time from load_dat...
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
# Compared to fh0.py # fh02.py remove the redundant ims in model input from __future__ import print_function, division import cv2 import torch import torch.nn as nn import torch.optim as optim import sys from torch.autograd import Variable import numpy as np import os import argparse from time import time from load_dat...
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
# Compared to fh0.py # fh02.py remove the redundant ims in model input from __future__ import print_function, division import cv2 import torch import torch.nn as nn import torch.optim as optim import sys from torch.autograd import Variable import numpy as np import os import argparse from time import time from load_dat...
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
# Compared to fh0.py # fh02.py remove the redundant ims in model input from __future__ import print_function, division import cv2 import torch import torch.nn as nn import torch.optim as optim import sys from torch.autograd import Variable import numpy as np import os import argparse from time import time from load_dat...
assfication_loss:{} ] spend time:{}'.format(epoch,i,torch.sum(total)//batchSize//batchSize, sum(lossAver) / len(lossAver), detection_loss,classfication_loss, time()-start)) # if i % 50 == 1:#没50个batch写一次日志 # with open(args['writeFile'], 'a') as outF: # outF.write('...
{}/{}]===>train average loss:{} = [detection_loss : {} + cl
conditional_block
LatexGenerator.py
#!/bin/env python ################################################################################ # # file : LatexGenerator.py # # author: Lakshmi Manohar Rao Velicheti - lveliche@iupui.edu # ################################################################################ from ..ReportGenerator import ReportGenerat...
# 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
#!/bin/env python ################################################################################ # # file : LatexGenerator.py # # author: Lakshmi Manohar Rao Velicheti - lveliche@iupui.edu # ################################################################################ from ..ReportGenerator import ReportGenerat...
# # Build a datapoint from the provided data structure # def build_datapoint (self, organizer, data, wrong_checker_is_fp): # Get the probability matrix (tp, fp, fn) = self.compute_probability (data, wrong_checker_is_fp) # Build a data point result = DataPoint () result.tp = tp result...
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
#!/bin/env python ################################################################################ # # file : LatexGenerator.py # # author: Lakshmi Manohar Rao Velicheti - lveliche@iupui.edu # ################################################################################ from ..ReportGenerator import ReportGenerat...
(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
#!/bin/env python ################################################################################ # # file : LatexGenerator.py # # author: Lakshmi Manohar Rao Velicheti - lveliche@iupui.edu # ################################################################################ from ..ReportGenerator import ReportGenerat...
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
// ************************ Drag and drop ***************** // let dropArea = document.getElementById("drop-area") // Prevent default drag behaviors ; ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { dropArea.addEventListener(eventName, preventDefaults, false) document.body.addEventListene...
(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
// ************************ Drag and drop ***************** // let dropArea = document.getElementById("drop-area") // Prevent default drag behaviors ; ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { dropArea.addEventListener(eventName, preventDefaults, false) document.body.addEventListene...
lterComponent(queryData); // updateChart(); // renderGraph(); })
{ initVersionPanel(); initFi
identifier_body
admin.js
// ************************ Drag and drop ***************** // let dropArea = document.getElementById("drop-area") // Prevent default drag behaviors ; ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { dropArea.addEventListener(eventName, preventDefaults, false) document.body.addEventListene...
}); } 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
// ************************ Drag and drop ***************** // let dropArea = document.getElementById("drop-area") // Prevent default drag behaviors ; ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { dropArea.addEventListener(eventName, preventDefaults, false) document.body.addEventListene...
}, 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
#!/usr/bin/env python ######################################## # Mario Rosasco, 2017 ######################################## from Model import * from Visualization import * from scipy.optimize import minimize from allensdk.ephys.ephys_features import detect_putative_spikes import numpy as np import sys ...
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
#!/usr/bin/env python ######################################## # Mario Rosasco, 2017 ######################################## from Model import * from Visualization import * from scipy.optimize import minimize from allensdk.ephys.ephys_features import detect_putative_spikes import numpy as np import sys ...
def run_visualization(currModel, show_simulation_dynamics = False): print "Setting up visualization..." morphology = currModel.get_reconstruction() # Prepare model coordinates for uploading to OpenGL. tempIndices = [] tempVertices = [] n_index = 0 tempX = [] ...
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