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 |
|---|---|---|---|---|
polynom.py |
else:
return NotImplemented
def __hash__(self):
return hash((self.v, self.n))
def __bool__(self):
return bool(self.v)
def __add__(a, b):
assert isinstance(b, ModInt)
assert a.n == b.n
return ModInt(a.v + b.v, a.n)
def __radd__(a, b):
... | return not bool(a - b) | conditional_block | |
polynom.py | :
raise ZeroDivisionError
return ModInt(ModInt._inv(self.v, self.n), self.n)
@staticmethod
def _inv(k, n):
k %= n
if k == 1:
return k
return (n - n // k) * ModInt._inv(n % k, n) % n
def __truediv__(a, b):
assert isinstance(b, ModInt)
... | (A, B):
Q = [0 * B[0]] * max(0, len(A) - len(B) + 1)
while len(A.C) >= len(B.C):
Q[len(A.C) - len(B.C)] = A[-1] / B[-1]
A -= B.shift(len(A) - len(B)) * (A[-1] / B[-1])
return Polynomial(Q), A
def __floordiv__(A, B):
assert isinstance(B, Polynomial)
re... | euclidean_division | identifier_name |
models.go | json:"updated"`
Created time.Time `json:"created"`
}
func (r *RoleDTO) LogID() string {
var org string
if r.Global() {
org = "Global"
} else {
org = fmt.Sprintf("OrgId:%v", r.OrgID)
}
if r.UID != "" {
return fmt.Sprintf("[%s RoleUID:%v]", org, r.UID)
}
return fmt.Sprintf("[%s Role:%v]", org, r.Name)
}
... | () bool {
return strings.HasPrefix(r.Name, FixedRolePrefix)
}
func (r *RoleDTO) IsPlugin() bool {
return strings.HasPrefix(r.Name, PluginRolePrefix)
}
func (r *RoleDTO) IsBasic() bool {
return strings.HasPrefix(r.Name, BasicRolePrefix) || strings.HasPrefix(r.UID, BasicRoleUIDPrefix)
}
func (r *RoleDTO) IsExternal... | IsFixed | identifier_name |
models.go | :"updated"`
Created time.Time `json:"created"`
}
func (r *RoleDTO) LogID() string {
var org string
if r.Global() {
org = "Global"
} else {
org = fmt.Sprintf("OrgId:%v", r.OrgID)
}
if r.UID != "" {
return fmt.Sprintf("[%s RoleUID:%v]", org, r.UID)
}
return fmt.Sprintf("[%s Role:%v]", org, r.Name)
}
fun... |
dedupMap[cmd.Permissions[i]] = true
dedup = append(dedup, cmd.Permissions[i])
}
cmd.Permissions = dedup
if cmd.ServiceAccountID <= 0 {
return fmt.Errorf("invalid service account id %d", cmd.ServiceAccountID)
}
return nil
}
const (
GlobalOrgID = 0
FixedRolePrefix = "fixed:"... | {
continue
} | conditional_block |
models.go | json:"updated"`
Created time.Time `json:"created"`
}
func (r *RoleDTO) LogID() string {
var org string
if r.Global() {
org = "Global"
} else {
org = fmt.Sprintf("OrgId:%v", r.OrgID)
}
if r.UID != "" {
return fmt.Sprintf("[%s RoleUID:%v]", org, r.UID)
}
return fmt.Sprintf("[%s Role:%v]", org, r.Name)
}
... | }
type SaveExternalServiceRoleCommand struct {
OrgID int64
Global bool
ExternalServiceID string
ServiceAccountID int64
Permissions []Permission
}
func (cmd *SaveExternalServiceRoleCommand) Validate() error {
if cmd.ExternalServiceID == "" {
return errors.New("external service id ... | BuiltinRole string `json:"builtInRole,omitempty"`
Permission string `json:"permission"` | random_line_split |
models.go | :"updated"`
Created time.Time `json:"created"`
}
func (r *RoleDTO) LogID() string {
var org string
if r.Global() {
org = "Global"
} else {
org = fmt.Sprintf("OrgId:%v", r.OrgID)
}
if r.UID != "" {
return fmt.Sprintf("[%s RoleUID:%v]", org, r.UID)
}
return fmt.Sprintf("[%s Role:%v]", org, r.Name)
}
fun... |
func (r *RoleDTO) IsFixed() bool {
return strings.HasPrefix(r.Name, FixedRolePrefix)
}
func (r *RoleDTO) IsPlugin() bool {
return strings.HasPrefix(r.Name, PluginRolePrefix)
}
func (r *RoleDTO) IsBasic() bool {
return strings.HasPrefix(r.Name, BasicRolePrefix) || strings.HasPrefix(r.UID, BasicRoleUIDPrefix)
}
f... | {
return strings.HasPrefix(r.Name, ManagedRolePrefix)
} | identifier_body |
hslcolor.rs | bound::Bound;
use color::{Color, RGBColor, XYZColor};
use coord::Coord;
use csscolor::{parse_hsl_hsv_tuple, CSSParseError};
use illuminants::Illuminant;
/// A color in the HSL color space, a direct transformation of the sRGB space. sHSL is used to
/// distinguish this space from a similar transformation of a differen... | random_line_split | ||
hslcolor.rs | agon but simply stretched into a circle, and the area of a
//! horizontal cross-section varies with lightness. A special note: some implementations of HSV and
//! HSL are circular in nature, using polar coordinates explicitly. This implementation is instead
//! hexagonal: first values are put on a hexagon, and then th... |
}
impl From<HSLColor> for Coord {
fn from(val: HSLColor) -> Self {
Coord {
x: val.h,
y: val.s,
z: val.l,
}
}
}
impl Bound for HSLColor {
fn bounds() -> [(f64, f64); 3] {
[(0., 360.), (0., 1.), (0., 1.)]
}
}
impl FromStr for HSLColor {
t... | {
HSLColor {
h: c.x,
s: c.y,
l: c.z,
}
} | identifier_body |
hslcolor.rs | agon but simply stretched into a circle, and the area of a
//! horizontal cross-section varies with lightness. A special note: some implementations of HSV and
//! HSL are circular in nature, using polar coordinates explicitly. This implementation is instead
//! hexagonal: first values are put on a hexagon, and then th... | else if self.h <= 180.0 {
(0.0, chroma, x)
} else if self.h <= 240.0 {
(0.0, x, chroma)
} else if self.h <= 300.0 {
(x, 0.0, chroma)
} else {
(chroma, 0.0, x)
};
// now we add the right value to each component to get the correct li... | {
(x, chroma, 0.0)
} | conditional_block |
hslcolor.rs | XYZColor};
use coord::Coord;
use csscolor::{parse_hsl_hsv_tuple, CSSParseError};
use illuminants::Illuminant;
/// A color in the HSL color space, a direct transformation of the sRGB space. sHSL is used to
/// distinguish this space from a similar transformation of a different RGB space, which can cause
/// some confu... | test_hsl_rgb_conversion | identifier_name | |
channel_layout.rs | ,
Channel::TopSideLeft,
Channel::TopSideRight,
Channel::TopBackCenter,
Channel::BottomFrontCenter,
Channel::BottomFrontLeft,
Channel::BottomFrontRight,
]);
pub const _2POINT1: ChannelLayout = Self::STEREO.with_channels_native(&[Channel::LowFrequency]);
pub const _2_1: ChannelLayout = Self::STEREO.with_ch... | NewLayout | identifier_name | |
channel_layout.rs | : ChannelLayout =
Self::_5POINT1.with_channels_native(&[Channel::FrontLeftOfCenter, Channel::FrontRightOfCenter]);
pub const _7POINT1_WIDE_BACK: ChannelLayout =
Self::_5POINT1_BACK.with_channels_native(&[Channel::FrontLeftOfCenter, Channel::FrontRightOfCenter]);
}
impl From<ChannelLayout> for AVChannelLayout {
f... | {
round_trip_debug(ChannelLayout::native(&[Channel::StereoRight, Channel::LowFrequency]));
round_trip_debug(ChannelLayout::custom(&[
CustomChannel::new(Channel::LowFrequency, Some("low-freq")),
CustomChannel::new(Channel::BackCenter, None),
]));
} | identifier_body | |
channel_layout.rs | channels = self.custom_channels_unchecked();
Some(
channels
.iter()
.all(|ch| self.contains_avchannel(ch.0.id).unwrap_or(false)),
)
},
// no information about channels available
(AVChannelOrder::AV_CHANNEL_ORDER_UNSPEC, _) | (_, AVChannelOrder::AV_CHANNEL_ORDER_UNSPEC) => None,
(A... | } | random_line_split | |
homework1.py | -star (only 1%), which means this dataset is extremely unbalanced.
#
# The dataset only has 6 rows containing NA value and we decide to remove them from the data.
#%% [markdown]
# ## Problem 3
# Train a simple predictor to predict the star rating using two features:
#
# star_rating ≃ θ0 + θ1 × [review is verified] + ... | atureNames, labelName):
train = data[:int(len(data)*ratio)]
test = data[int(len(data)*ratio):]
print("================ For ratio ", ratio, "================")
myRegression(featureNames, labelName, train, test)
#%%
trainByRatio(0.9, data, featureNames, labelName)
#%% [markdown]
# ## Problem 6
# R... | taTrain[labelName]
theta, residuals, rank, s = np.linalg.lstsq(X, y)
print("================ Training ================")
MSE = ((y - np.dot(X, theta))**2).mean()
for i in range(len(theta)):
print("Theta%1d: %.5f" % (i, theta[i]))
print("MSE: %.3f" % MSE)
print("================ Testing =... | identifier_body |
homework1.py | that only uses one feature:
#
# star rating ≃ θ0 + θ1 × [review is verified]
#
# Report the values of θ0 and θ1. Note that coefficient you found here might be quite different (i.e., much larger or smaller) than the one from Question 3, even though these coefficients refer to the same feature. Provide an explanation ... | ame):
tr | identifier_name | |
homework1.py |
#%% [markdown]
# ## Problem 3
# Train a simple predictor to predict the star rating using two features:
#
# star_rating ≃ θ0 + θ1 × [review is verified] + θ2 × [review length].
#
# Report the values of θ0, θ1, and θ2. Briefly describe your interpretation of these values, i.e., what do θ0, θ1, and θ2 represent? Explain... |
#%% [markdown]
# We can see from the above plot and printout that most of ratings are 5-star (87%) while the least rating is 2-star (only 1%), which means this dataset is extremely unbalanced.
#
# The dataset only has 6 rows containing NA value and we decide to remove them from the data. | random_line_split | |
homework1.py | [markdown]
# We can see from the above plot and printout that most of ratings are 5-star (87%) while the least rating is 2-star (only 1%), which means this dataset is extremely unbalanced.
#
# The dataset only has 6 rows containing NA value and we decide to remove them from the data.
#%% [markdown]
# ## Problem 3
# T... | "The percent of %1d-star: %.1f%%" % (i, (len(data[data['star_rating']==i])/len(data)*100)))
#%% | conditional_block | |
page-email-management.js | enable: true,
createddate: '',
lastupdate: '',
createdby: '',
updatedby: ''
};
em.CategoryMailList = ko.observableArray([]);
em.UserMailList = ko.observableArray([]);
em.AlarmCodesMailList = ko.observableArray([]);
em.TemplateMailList = ko.observable();
em.isAlarmCode = ko.observable(false);
em.isInte... | em.isInterval(true);
}
});
var catVal = $('#categoryList').data('kendoDropDownList').value();
if(catVal == "alarm01") {
$('#templateMail').html(em.TemplateMailList().alarmTemplate)
} else {
$('#templateMail').html(em.TemplateMailList().dataTemplate)
}
}
em.reset... | em.isAlarmCode(true);
} else if(val.indexOf("isInterval") >= 0) { | random_line_split |
page-email-management.js | : true,
createddate: '',
lastupdate: '',
createdby: '',
updatedby: ''
};
em.CategoryMailList = ko.observableArray([]);
em.UserMailList = ko.observableArray([]);
em.AlarmCodesMailList = ko.observableArray([]);
em.TemplateMailList = ko.observable();
em.isAlarmCode = ko.observable(false);
em.isInterval = ... |
}
};
em.checkCategory = function() {
em.showHide($('#categoryList').data('kendoDropDownList').value());
}
em.showHide = function(category) {
var resObj = em.CategoryMailList().filter(function(obj) {
return obj.value == category;
});
var condition = resObj[0].condition.split(",");
em.i... | {
(function () {
var idtemp = '';
$('.deletecheck').each(function (index) {
$(this).prop("checked", false);
idtemp = $(this).attr('idcheck');
em.tempCheckIdDelete.remove(function (item) {
retu... | conditional_block |
binary_search_tree1.py | time
logging.basicConfig(
level=logging.ERROR,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class Node():
def __init__(self, data=None):
self._data = data
self._left, self._right = None, None
def __str__(self):
return 'N... | ly one child or no child 的情形
if node.left and node.right:
# find the largest in the left subtree as successor
tmp = self._find_extremum(node.left) # default by max
# Copy the inorder successor's content to this node
node.d... | 个或零个节点
### 所以转化成了前边 Node with on | identifier_body |
binary_search_tree1.py | time
logging.basicConfig(
level=logging.ERROR,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class Node():
def __init__(self, data=None):
self._data = data
self._left, self._right = None, None
def __str__(self):
return 'N... | an the root's key
# then it lies in right subtree
elif value > node.data:
node.right = self._delete(value, node.right)
# If key is same as root's key, then this is the node
# to be deleted
else: # step2
# Node with two childr... | ter th | identifier_name |
binary_search_tree1.py | time
logging.basicConfig(
level=logging.ERROR,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class Node():
def __init__(self, data=None):
self._data = data
self._left, self._right = None, None
def __str__(self):
return 'N... | # is_left 作用跟踪是否为左子节点
is_left = True
elif value > node.data:
node = node.right
is_left = False
# while 循环完没找到,则node is None
# while 循环完找到的话,则node is not None 跳过if,return 找到的node
if alert and node is None: # alert and (node is None)... | and value != node.data:
# _pre_node 作用跟踪父节点
_pre_node = node
if value < node.data:
node = node.left
| conditional_block |
binary_search_tree1.py | 那么左子树的所有节点都小于根节点,右子树的所有节点都大于根节点,数为二叉搜索树。
左右子树都为二叉搜索树。
"""
def __init__(self):
self._root = None
def __str__(self):
""" yield 迭代器 """
tree2list = [x.data for x in self._generate_node()]
return 'the BinarySearchTree is %s' % tree2list
def __bool__(self):
if s... | # 有1个或者没有
else: | random_line_split | |
new_solver_4.py | ridge = ridge_vertices[i]
partname = 'Part-' + str(i+1)
myModel.Part(dimensionality=THREE_D, name=partname, type=
DEFORMABLE_BODY)
try:
myModel.parts[partname].DatumPointByCoordinate(coords=(vertices[ridge[0]][0],vertices[ridge[0]][1], vertices[ridge[0]][2]))
myModel.parts[partname].DatumPointBy... |
#list_vertices_left = []
for k in network.boundary_nodes_left:
ridge=list_nodes_ridges[k]
#print(ridge)
instancename = 'Part-' + str(ridge[0]+1) + '-1'
try:
coords = (vertices[k][0],vertices[k][1],vertices[k][2])
except IndexError:
coords = (verti... | myModel.DisplacementBC(amplitude=UNSET, createStepName='Step-1', distributionType=UNIFORM, fieldName='', fixed=OFF, localCsys=None, name='BC-'+str(ridge[0]+1), region=Region(vertices=mdb.models['Model-1'].rootAssembly.instances[instancename].vertices[1:]), u1=traction_distance, u2=0.0,u3=0.0,ur3=UNSET)
... | conditional_block |
new_solver_4.py | ridge = ridge_vertices[i]
partname = 'Part-' + str(i+1)
myModel.Part(dimensionality=THREE_D, name=partname, type=
DEFORMABLE_BODY)
try:
myModel.parts[partname].DatumPointByCoordinate(coords=(vertices[ridge[0]][0],vertices[ridge[0]][1], vertices[ridge[0]][2]))
myModel.parts[partname].DatumPointBy... | (network): ## can be changed with the node label list
#list_vertices_right = []
for k in network.boundary_nodes_right:
ridge=list_nodes_ridges[k]
#print(ridge)
instancename = 'Part-' + str(ridge[0]+1) + '-1'
try:
coords = (vertices[k][0],vertices[k][1],vertices[k][2])... | set_boundary_conditions | identifier_name |
new_solver_4.py | range(len(ridge_vertices)):
partname = 'Part-' + str(i+1)
myModel.parts[partname].assignBeamSectionOrientation(method=
N1_COSINES, n1=(0.0, 0.0, -1.0), region=Region(
edges=myModel.parts[partname].edges.getSequenceFromMask(mask=('[#1 ]', ), )))
mdb.models['Model-1'].rootAssembly.DatumCsysByDefault(CARTESIAN... | for i in range(len(list_ridge)-1):
instancename1='Part-'+str(list_ridge[i]+1)+'-1'
instancename2='Part-'+str(list_ridge[i+1]+1)+'-1' | random_line_split | |
new_solver_4.py | .parts[partname].WirePolyLine(mergeType=IMPRINT, meshable=
ON, points=((myModel.parts[partname].datums[1],
myModel.parts[partname].datums[2]), ))
#### MATERIAL AND SECTION DEFINITION ####
# Truss section
def define_material(network):
myModel.Material(name='Material-2')
myModel.materials['Material-2'].Elas... | number_elements = []
for i in range(len(ridge_vertices)):
instancename = 'Part-' + str(i+1) + '-1'
#myModel.rootAssembly.setElementType(elemTypes=(ElemType(
# elemCode=B21, elemLibrary=STANDARD), ), regions=(
# myModel.rootAssembly.instances[instancename].edges.getSequenceFromMask(
# mask=('[#1 ]', ), ), ))
... | identifier_body | |
analysis.py | """
# Extract data
data = util.extract_data(datasets, axis)
titles = util.extract_title(datasets)
xmin, xmax = util.set_limits(data, xmin, xmax, xrange_, axis)
if bins is None:
bins = util.bin_default(axis, xmin, xmax)
fig, ax = util.fig_ax(axes)
fig._flowml_axis... |
else:
ax.set_title(titles[0])
return fig
def hist2(datasets, axis1, axis2, bins = None,
xmin = None, xmax = None, ymin = None, ymax = None, range_ = None,
axes = None, transform = None):
datax = util.extract_data(datasets, axis1)
datay = util.extract_data(datasets, a... | ax.legend() | conditional_block |
analysis.py | ) == 1:
ax.set_title(titles[0])
elif len(datax) > 1:
ax.legend(proxy, titles)
ax.set_xlabel(axis1)
ax.set_ylabel(axis2)
ax.set_xscale(scaling[0])
ax.set_yscale(scaling[1])
return fig
def make_cmap(target, background = None):
if background is None:
background ... | # Randomly sample to reduce the number of points
sample_masks = [] | random_line_split | |
analysis.py | interpolation = 'none',
aspect = 'auto')
line_collections.append(ln)
proxy.append( plt.Rectangle((0,0),1,1,fc = line.get_color(),alpha = alpha))
line.remove()
ax.legend(proxy, titles)
ax.set_xlabel(axis1)
ax.set_ylabel(axis2)
if ... | heatmap | identifier_name | |
analysis.py | , bins = bins, range = (xmin, xmax))
left = np.array(bin_edges[:-1])
right = np.array(bin_edges[1:])
# FIXES a bug in MPLD3 0.3 regarding NaNs in coordinates
bottom = 1e-6*np.ones(len(left))
top = bottom + hist
XY = np.array([[left,left,right,right], [bottom, top, top, bo... | """Counts the events in the given label.
Args:
dataset (list): List of FlowData objects
label (list or string): name(s) of boolean columns in datasets
"""
fn = lambda fd, axis: fd.shape[0]
return fn_matrix(datasets, fn, axes = None, label = labels) | identifier_body | |
main.rs | data to disk
let mut cert_file = File::create(certs_path.join(format!(
"{}/{}",
domain,
certificates::CERT_FILE_NAME
)))?;
cert_file.write_all(&cert.serialize_der()?)?;
// write key data to disk
... | // no userinfo and no fragment
if url.password().is_some() || !url.username().is_empty() || url.fragment().is_some() {
return Err((BAD_REQUEST, "URL contains fragment or userinfo"));
} | random_line_split | |
main.rs | else {
// already listening on the other unspecified address
log::warn!("Could not start listener on {}, but already listening on another unspecified address. Probably your system automatically listens in dual stack?", addr);
continue;... | {
panic!("Failed to listen on {addr}: {e}")
} | conditional_block | |
main.rs | .optopt(
"",
"certs",
"Root of the certificate directory (default ./.certificates/)",
"DIR",
);
opts.optmulti(
"",
"addr",
&format!("Address to listen on (default 0.0.0.0:{DEFAULT_PORT} and [::]:{DEFAULT_PORT}; multiple occurences means listening on multip... | <T> {
stream: TlsStream<T>,
local_port_check: Option<u16>,
log_line: String,
metadata: Arc<Mutex<FileOptions>>,
}
impl RequestHandle<TcpStream> {
/// Creates a new request handle for the given stream. If establishing the TLS
/// session fails, returns a corresponding log line.
async fn new(... | RequestHandle | identifier_name |
certificate_manager.rs | use edgelet_core::CertificateProperties;
use failure::ResultExt;
pub use crate::error::{Error, ErrorKind};
pub struct CertificateManager<C: CreateCertificate + Clone> {
certificate: Arc<RwLock<Option<Certificate>>>,
crypto: C,
props: CertificateProperties,
creation_time: Instant,
}
#[derive(Clone)]
s... |
use edgelet_core::crypto::{
Certificate as CryptoCertificate, CreateCertificate, KeyBytes, PrivateKey, Signature,
}; | random_line_split | |
certificate_manager.rs | Certificate, CreateCertificate, KeyBytes, PrivateKey, Signature,
};
use edgelet_core::CertificateProperties;
use failure::ResultExt;
pub use crate::error::{Error, ErrorKind};
pub struct CertificateManager<C: CreateCertificate + Clone> {
certificate: Arc<RwLock<Option<Certificate>>>,
crypto: C,
props: Cert... |
}
}
#[derive(Clone)]
struct TestCrypto {
created: bool,
}
impl TestCrypto {
pub fn new() -> Result<Self, CoreError> {
Ok(Self { created: true })
}
}
impl CoreCreateCertificate for TestCrypto {
type Certificate = TestCertificate;
... | {
if let ErrorKind::CertificateTimerCreationError = err.kind() {
assert_eq!(true, true);
} else {
panic!(
"Expected a CertificteTimerCreationError type, but got {:?}",
err
);
... | conditional_block |
certificate_manager.rs | (Clone)]
struct Certificate {
cert: String,
private_key: String,
}
impl<C: CreateCertificate + Clone> CertificateManager<C> {
pub fn new(crypto: C, props: CertificateProperties) -> Result<Self, Error> {
let cert_manager = Self {
certificate: Arc::new(RwLock::new(None)),
cryp... | TestCertificate | identifier_name | |
certificate_manager.rs | {
let cert_manager = Self {
certificate: Arc::new(RwLock::new(None)),
crypto,
props,
creation_time: Instant::now(),
};
{
let mut cert = cert_manager
.certificate
.write()
.expect("Lockin... | {
Ok("test".to_string())
} | identifier_body | |
huifushishichang.js | HttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
function insertHFSSCTable(){
var table = doc.getElementById("HFSSC_table");
var thead = doc.getElementById("HFSSC_table_head");
table.innerHTML = '';
thead.innerHTML = '';
//add table head
var top = doc.getElementById('HFSSC_... | ******before detail a, now with td
// add data rows
for(var i=0;i<HFSSCdataSource.length;i++){
var tr = doc.createElement("tr");
var td = doc.createElement('td'),
span = doc.createElement('span');
span.innerHTML = '🔝';
td.appendChild(span);
td.style.width = '2%';
tr.appendChild(td);
tr.o... | Child(tr);
}
// ********* | conditional_block |
huifushishichang.js | , textStatus, errorThrown) {
alert(errorThrown);
}
});
function insertHFSSCTable() | var thData;
if(rows == 0){
if(t == 0){
var pp = doc.createElement('div');
//span.innerHTML = '🔝';
th.appendChild(pp);
pp.style.width = '10%';
pp.style.float = 'left';
pp.style.padding = '8px';
//trHead.appendChild(th);
thData = doc.createTextNode(HFSSCdataT... | {
var table = doc.getElementById("HFSSC_table");
var thead = doc.getElementById("HFSSC_table_head");
table.innerHTML = '';
thead.innerHTML = '';
//add table head
var top = doc.getElementById('HFSSC_table_top');
if(HFSSCloadpage != 1){
top.style.display = 'none';
}else{
top.style.display = 'block... | identifier_body |
huifushishichang.js | '30%';
}
}else if(rows == 1){
thData = doc.createTextNode(HFSSCdataTitle[t+1]);
th.appendChild(thData);
th.style.width = '15%';
}
th.style.textAlign = "center";
trHead.appendChild(th);
}
thead.appendChild(trHead);
}
// add a row containing total number of operation metho... | success: function (data) {
HFSSCdataSource = data.data;
HFSSCdataTitle = data.header;
| random_line_split | |
huifushishichang.js | ++) {
var th = doc.createElement("th");
var thData;
if(rows == 0){
if(t == 0){
var pp = doc.createElement('div');
//span.innerHTML = '🔝';
th.appendChild(pp);
pp.style.width = '10%';
pp.style.float = 'left';
pp.style.padding = '8px';
//trHead.appendChild(th... |
HFSSCc | identifier_name | |
device-stats.js | = 17;
var magnetic_zId = 18;
var gyroscope_xId = 19;
var gyroscope_yId = 20;
var gyroscope_zId = 21;
var lightId = 22;
var pressureId = 23;
var proximityId = 24;
var gravity_xId = 25;
var gravity_yId = 26;
var gravity_zId = 27;
var rotation_xId = 28;
var rotation_yId = 29;
var rotation_zId = 30;
var batteryData... |
if (ws) {
ws.onmessage = function (event) {
var dataPoint = JSON.parse(event.data);
if (dataPoint) {
var time = parseInt(dataPoint[4]) / 1000;
switch (dataPoint[typeId]) {
case "battery":
graphUpdate(batteryData, time, dataPoint[batteryId]);
graphMap["battery"].updat... | {
console.log('WebSocket is not supported by this browser.');
} | conditional_block |
device-stats.js | Id = 17;
var magnetic_zId = 18;
var gyroscope_xId = 19;
var gyroscope_yId = 20;
var gyroscope_zId = 21;
var lightId = 22;
var pressureId = 23;
var proximityId = 24;
var gravity_xId = 25;
var gravity_yId = 26;
var gravity_zId = 27;
var rotation_xId = 28;
var rotation_yId = 29;
var rotation_zId = 30;
var batteryDa... |
var graphMap = {};
var graphSettingsMap = {};
var palette = new Rickshaw.Color.Palette({scheme: "munin"});
var elemTop;
$(window).load(function () {
graphMap["battery"]=lineGraph("battery", batteryData);
graphMap["light"]=lineGraph("light", lightData);
graphMap["pressure"]=lineGraph("pressure", pressureData);
... | var rotation_xData = [];
var rotation_yData = [];
var rotation_zData = []; | random_line_split |
device-stats.js | Id = 17;
var magnetic_zId = 18;
var gyroscope_xId = 19;
var gyroscope_yId = 20;
var gyroscope_zId = 21;
var lightId = 22;
var pressureId = 23;
var proximityId = 24;
var gravity_xId = 25;
var gravity_yId = 26;
var gravity_zId = 27;
var rotation_xId = 28;
var rotation_yId = 29;
var rotation_zId = 30;
var batteryDa... | element: $elem[0],
width: $elem.width() - 100,
height: 300,
renderer: "line",
interpolation: "linear",
padding: {top: 0.2, left: 0.0, right: 0.0, bottom: 0.2},
xScale: d3.time.scale(),
series: [
{'color': palette.color(), 'data': xChartData, 'name': "x - " + type},
{'color': palette.color(), 'data... | {
var tNow = new Date().getTime() / 1000;
for (var i = 0; i < 30; i++) {
xChartData.push({
x: tNow - (30 - i) * 15,
y: parseFloat(0)
});
yChartData.push({
x: tNow - (30 - i) * 15,
y: parseFloat(0)
});
zChartData.push({
x: tNow - (30 - i) * 15,
y: parseFloat(0)
});
}
var $elem = $("#ch... | identifier_body |
device-stats.js | = 25;
var gravity_yId = 26;
var gravity_zId = 27;
var rotation_xId = 28;
var rotation_yId = 29;
var rotation_zId = 30;
var batteryData = [];
var lightData = [];
var pressureData = [];
var proximityData = [];
var accelerometer_xData = [];
var accelerometer_yData = [];
var accelerometer_zData = [];
var magnetic_x... | graphUpdate | identifier_name | |
db_helpher.go | (1).FindAll()
return data
}
log.Error("mysql not connect\r\n")
return empty
}
//插入数据
func (m *Model) Insert(param map[string]interface{}) (num int, err error) {
if m.db == nil {
log.Error("mysql not connect\r\n")
return 0, errors.New("IN Insert, mysql not connect")
} | }
for key, value := range param {
keys = append(keys, key)
switch value.(type) {
case int, int64, int32:
values = append(values, strconv.FormatInt(int64(value.(int)), 10))
case uint64, uint32:
values = append(values, strconv.FormatUint(value.(uint64), 10))
case string:
values = append(values, "'" ... | var keys []string
var values []string
if len(m.pk) != 0 {
delete(param, m.pk) | random_line_split |
db_helpher.go | ([]string{"AppID = '" + appid + StatusIsZero}, "")).FindOne()
info := data[1]
if nil == info {
fmt.Println("Invalid Authentication input information")
return MSG_INVALID_INPUTINFO
}
//不能从缓存中取,否则造成eth和db的循环引用
//从数据库中读取用户信息并加密,判断解析后的公共参数是否与从数据库取出并加密后的哈希值相等,相等则鉴权成功
plaintext := strings.Join([]string{info[AppID] ... | unt
value[TXStatus] = MSG_AWAIT_CONFIRM
value["Txhash"] = txhash //add 2018-7-4 sh | identifier_body | |
db_helpher.go | //case float32, float64:
// set := fmt.Sprintf("%v = '%v'", key, strconv.FormatFloat(value.(float64), 'f', -1, 64))
// setValue = append(setValue, set)
}
}
setData := strings.Join(setValue, ",")
sql := fmt.Sprintf("UPDATE %v SET %v %v", m.tablename, setData, m.where)
fmt.Printf("update_sql :%s\n", sql)
res... | xt := string | identifier_name | |
db_helpher.go | append(setValue, set)
case string:
set := fmt.Sprintf("%v = '%v'", key, value.(string))
setValue = append(setValue, set)
//case float32, float64:
// set := fmt.Sprintf("%v = '%v'", key, strconv.FormatFloat(value.(float64), 'f', -1, 64))
// setValue = append(setValue, set)
}
}
setData := strings.Join... | n")
return MSG_INVALID_INPUTINFO
}
//不能从缓存中取,否则造成eth和db的循环引用
//从数据 | conditional_block | |
server.py | test results sent by connected clients. A ClientHandler object is created
for each new client that connects. Clients communicate with the server using a
string-based messaging protocol that is defined in client_api.py. Clients are also
tracked using sequential client ids that are assigned upon connection and sent... |
def handle_ready(self):
server_log.info(str(self.client_id) + ': Client ready, sending test request')
self.push(client_api["run_tests"] + client_api["terminator"])
def handle_start(self):
server_log.info(str(self.client_id) + ': Client started running tests')
self.stat... | server_log.info(str(self.client_id) + ': Sending client id')
self.push(client_api["set_client_id"] + client_api["delimiter"] + str(self.client_id) + client_api["terminator"]) | identifier_body |
server.py | test results sent by connected clients. A ClientHandler object is created
for each new client that connects. Clients communicate with the server using a
string-based messaging protocol that is defined in client_api.py. Clients are also
tracked using sequential client ids that are assigned upon connection and sent... |
else:
return True
def write_report(self):
"""Writes out a report that displays data for all clients that ran."""
self.end_time = time.strftime('%Y-%m-%d_%H:%M:%S')
server_log.info('')
server_log.info('=====================================================... | return False | conditional_block |
server.py |
client upon the client's request.
The server logs client connections and messages to the console and to a file saved
to ./server_logs named 'server_log_<date&time>'. Once all clients have finished
running, the server writes a report displaying statistics for each client including
how long they ran, file write ... | handle_file_rollover | identifier_name | |
server.py | test results sent by connected clients. A ClientHandler object is created
for each new client that connects. Clients communicate with the server using a
string-based messaging protocol that is defined in client_api.py. Clients are also
tracked using sequential client ids that are assigned upon connection and sent... | except KeyError as e:
server_log.info('Unhandled command received from client id {}: {}'.format(self.client_id, cmd))
except Exception as e:
server_log.info('Exception raised in server when receiving message from client: {!r}'.format(e))
raise e
finally:
... | self.msg = ''.join(self.msg_buffer)
self.msg_split = self.msg.split(client_api["delimiter"])
cmd = self.msg_split[0]
try:
self.msg_handler[cmd]()
| random_line_split |
model_new2_plot.py | # ##############
dt = 10
time_axis = range(0,t_final+dt,dt)
time_axis = np.array(time_axis)
def retrieve_result( filename_lin, filename_final ):
fdata = h5py.File( filename_lin, "r" )
n_f = fdata[ "n_f" ].value
n_t = fdata[ "n_t" ].value
n_u = fdata[ "n_u" ].value
n_p = fdata[ "n_p" ].value
num_... | T = FunctionSpace(mesh, "CG", 1)
t_final = 300
# ##############
# t_final = t_final/3 # only works for MPC | random_line_split | |
model_new2_plot.py | ( filename_lin, filename_final ):
fdata = h5py.File( filename_lin, "r" )
n_f = fdata[ "n_f" ].value
n_t = fdata[ "n_t" ].value
n_u = fdata[ "n_u" ].value
n_p = fdata[ "n_p" ].value
num_t = fdata[ "num_t" ].value
num_u = fdata[ "num_u" ].value
num_p = fdata[ "num_p" ].value
n_e1 = fda... | retrieve_result | identifier_name | |
model_new2_plot.py | tq_point3 = fdata[ "tq_point3" ].value
# ipdb.set_trace()
final_array = np.load( filename_final )
return ( n_f, n_t, n_u, n_p,
num_t, num_u, num_p,
n_e1, n_e2, n_e3,
t_range, v_range, p_range,
vbc_point, vbc_point2, vbc2_point, vbc2_point2,
... | fdata = h5py.File( filename_lin, "r" )
n_f = fdata[ "n_f" ].value
n_t = fdata[ "n_t" ].value
n_u = fdata[ "n_u" ].value
n_p = fdata[ "n_p" ].value
num_t = fdata[ "num_t" ].value
num_u = fdata[ "num_u" ].value
num_p = fdata[ "num_p" ].value
n_e1 = fdata[ "n_e1" ].value
n_e2 = fdata[ "... | identifier_body | |
model_new2_plot.py | 2_lin.data",
(drt + "/results1.npy") )
final_array2 = np.load( (drt2 + "/results1.npy") )
# #############
# n_f = n_f/3 # for MPC only
# #############
num_lp = 1
n_total = n_f*( num_t+1+1 ) + num_u + num_p + ( 1 + 1 )*2
n_constraint = n_f*n_e1 + n_e2 + n_e3
tidx = np.arange( 0, n_... | u_x[i] = np.sign( u_x[i] ) * abs( u_x[i] )**(0.7)
u_y[i] = np.sign( u_y[i] ) * abs( u_y[i] )**(0.7) | conditional_block | |
full_section_then_mfovs_thumbs_blobs.py | blob_detector = BlobDetector2D.create_detector(**blob_detector_args)
# threadLocal.blob_detector = blob_detector
all_kps_descs = [[], []]
for tile in mfov.tiles():
thumb_img_fname = "thumbnail_{}.jpg".format(os.path.splitext(os.path.basename(tile.img_fname))[0])
... |
@staticmethod
def match_mfovs_features(matcher_params, sec1_cache, sec2_cache, mfovs1, mfovs2):
"""
Matches the features in mfovs1 (of sec1) to the features in mfovs2 (of sec2).
This method is run by a process that loads the matcher from its local thread storage.
"""
... | mfov1_center = np.array([
(mfov1.bbox[0] + mfov1.bbox[1]) / 2,
(mfov1.bbox[2] + mfov1.bbox[3]) / 2
])
# Add the triangle points
sec1_points = PreMatch3DFullSectionThenMfovsThumbsBlobs.OVERLAP_DELTAS + mfo... | identifier_body |
full_section_then_mfovs_thumbs_blobs.py | blob_detector = BlobDetector2D.create_detector(**blob_detector_args)
# threadLocal.blob_detector = blob_detector
all_kps_descs = [[], []]
for tile in mfov.tiles():
thumb_img_fname = "thumbnail_{}.jpg".format(os.path.splitext(os.path.basename(tile.img_fname))[0])
... | (matcher_params, sec1_cache, sec2_cache, mfovs1, mfovs2):
"""
Matches the features in mfovs1 (of sec1) to the features in mfovs2 (of sec2).
This method is run by a process that loads the matcher from its local thread storage.
"""
thread_local_store = ThreadLocalStorageLR... | match_mfovs_features | identifier_name |
full_section_then_mfovs_thumbs_blobs.py | (self, sec, sec_cache, pool):
# Create nested caches is needed
if "pre_match_blobs" not in sec_cache:
#sec_cache.create_dict("pre_match_blobs")
sec_cache["pre_match_blobs"] = {}
total_features_num = 0
# create the mfovs blob computation jobs
async... | async_results = []
for mfov1 in sec1.mfovs():
# find overlapping mfovs in sec2
mfovs2 = PreMatch3DFullSectionThenMfovsThumbsBlobs.get_overlapping_mfovs(mfov1, sec2, global_model, sec2_rtree)
logger.report_event("Finding local model between section {} (mfov {}) and sec... | random_line_split | |
full_section_then_mfovs_thumbs_blobs.py | kps_pts[:, 1] *= us_y
# Apply the transformation to the points
assert(len(tile.transforms) == 1)
model = tile.transforms[0]
kps_pts = model.apply(kps_pts)
all_kps_descs[0].extend(kps_pts)
all_kps_descs[1].extend(descs)
logge... | sec2_rtree.insert(t, t.bbox) | conditional_block | |
main.rs | (&opt.file_name);
let file =
fs::File::open(file_name).with_context(|| format!("open file {:?} err", file_name))?;
// 使用 zip 创建该文件的 Archive
let mut archive = zip::ZipArchive::new(file).context("create zip archive err")?;
for i in 0..archive.len() {
let file = archive.by_index(i).unwrap(... | // cur parent 变更为 最新节点
self.cur.replace(element);
} else {
// 第一个节点
self.root.replace(Rc::clone(&element)); | random_line_split | |
main.rs | .xml")
.context("found no word/document.xml")?;
// xml parse
let mut doc_parsing = MainDocParsing::new();
let parser = EventReader::new(word_doc);
let mut depth = 0;
for e in parser {
let event = e.context("xml parser got err")?;
match event {
XmlEvent::StartElem... | pth -= 1;
// 当前父节点指向上一层的节点
let mut parent = None;
if let Some(cur) = &self.cur {
if let Some(p) = &cur.borrow().parent {
parent = p.upgrade();
}
}
self.cur = parent;
}
/// 向当前的 element 中添加text, 目前只有 w:t 类型会有
fn feed_character... | identifier_body | |
main.rs | ```sh
/// cargo run -- demo.docx
/// ```
/// 输出字体,并且带字体的颜色值.
fn main() -> Result<()> {
let opt = Opt::from_args();
let file_name = Path::new(&opt.file_name);
let file =
fs::File::open(file_name).with_context(|| format!("open file {:?} err", file_name))?;
// 使用 zip 创建该文件的 Archive
let mut a... | l的 OwnedName 中构建 ElementType
fn from_name(name: &OwnedName) -> Self {
let raw = format!(
"{}:{}",
name.prefix.as_ref().unwrap_or(&String::new()),
name.local_name
);
// 目前 只识别 `w:xxx` 格式, 且只是部分标签
if name.prefix.is_none() || name.prefix.as_ref().unw... | /// 从 xm | identifier_name |
main.rs | ```sh
/// cargo run -- demo.docx
/// ```
/// 输出字体,并且带字体的颜色值.
fn main() -> Result<()> {
let opt = Opt::from_args();
let file_name = Path::new(&opt.file_name);
let file =
fs::File::open(file_name).with_context(|| format!("open file {:?} err", file_name))?;
// 使用 zip 创建该文件的 Archive
let mut a... | // 调试信息
if opt.verbose {
println!(r#"{}Characters("{}")"#, " ".repeat(depth), data,);
}
// 当前元素添加 text data
doc_parsing.feed_characters(data);
}
XmlEvent::Whitespace(_) => {}
_ => {
... | nt_xml_owned_name(&name, depth, false);
}
// 当前元素解析完成
doc_parsing.fish_feed_element();
}
XmlEvent::Comment(_) => {}
XmlEvent::CData(_) => {}
XmlEvent::Characters(data) => {
| conditional_block |
utils.go | /go/v14/arrow/internal/debug"
"github.com/apache/arrow/go/v14/arrow/memory"
"golang.org/x/xerrors"
)
type bufferWriteSeeker struct {
buf *memory.Buffer
pos int
mem memory.Allocator
}
func (b *bufferWriteSeeker) Reserve(nbytes int) {
if b.buf == nil {
b.buf = memory.NewResizableBuffer(b.mem)
}
newCap := int(... |
}
}
func replaceNullWithOtherType(vals ...arrow.DataType) {
debug.Assert(len(vals) == 2, "should be length 2")
if vals[0].ID() == arrow.NULL {
vals[0] = vals[1]
return
}
if vals[1].ID() == arrow.NULL {
vals[1] = vals[0]
return
}
}
func commonTemporalResolution(vals ...arrow.DataType) (arrow.TimeUnit,... | {
vals[i] = v.(*arrow.DictionaryType).ValueType
} | conditional_block |
utils.go | {
debug.Assert(len(vals) == 2, "should be length 2")
if vals[0].ID() == arrow.NULL {
vals[0] = vals[1]
return
}
if vals[1].ID() == arrow.NULL {
vals[1] = vals[0]
return
}
}
func commonTemporalResolution(vals ...arrow.DataType) (arrow.TimeUnit, bool) {
isTimeUnit := false
finestUnit := arrow.Second
f... | {
var (
allUTF8, allOffset32, allFixedWidth = true, true, true
)
for _, ty := range vals {
switch ty.ID() {
case arrow.STRING:
allFixedWidth = false
case arrow.BINARY:
allFixedWidth, allUTF8 = false, false
case arrow.FIXED_SIZE_BINARY:
allUTF8 = false
case arrow.LARGE_BINARY:
allOffset32, al... | identifier_body | |
utils.go | /go/v14/arrow/internal/debug"
"github.com/apache/arrow/go/v14/arrow/memory"
"golang.org/x/xerrors"
)
type bufferWriteSeeker struct {
buf *memory.Buffer
pos int
mem memory.Allocator
}
func (b *bufferWriteSeeker) Reserve(nbytes int) {
if b.buf == nil {
b.buf = memory.NewResizableBuffer(b.mem)
}
newCap := int(... |
// decimal promotion rules compatible with amazon redshift
// https://docs.aws.amazon.com/redshift/latest/dg/r_numeric_computations201.html
var leftScaleup, rightScaleup int32
switch promote {
case decPromoteAdd:
leftScaleup = exec.Max(scale1, scale2) - scale1
rightScaleup = exec.Max(scale1, scale2) - scale2... | castedID = arrow.DECIMAL256
} | random_line_split |
utils.go | /go/v14/arrow/internal/debug"
"github.com/apache/arrow/go/v14/arrow/memory"
"golang.org/x/xerrors"
)
type bufferWriteSeeker struct {
buf *memory.Buffer
pos int
mem memory.Allocator
}
func (b *bufferWriteSeeker) Reserve(nbytes int) {
if b.buf == nil {
b.buf = memory.NewResizableBuffer(b.mem)
}
newCap := int(... | (vals ...arrow.DataType) bool {
for _, v := range vals {
if arrow.IsDecimal(v.ID()) {
return true
}
}
return false
}
type decimalPromotion uint8
const (
decPromoteNone decimalPromotion = iota
decPromoteAdd
decPromoteMultiply
decPromoteDivide
)
func castBinaryDecimalArgs(promote decimalPromotion, vals ... | hasDecimal | identifier_name |
evaluator.py | Cache:
def __init__(self):
self._cache: Dict[str, List[Optional["array.Array"]]] = {}
def merge(self, other):
self._cache = {**self._cache, **other._cache}
def add_entry(self, node_name: str, index: int, array: "array.Array"):
if node_name in self._cache:
entry = self._... | except Exception: # pragma: no cover
# dump failed model for debugging purposes
onnx.save_model(m, "failed_model.onnx")
raise
io_binding = session.io_binding()
session_input_names = [i.name for i in session.get_inputs()]
graph_node_mapping = executab... | buffer, providers=Config().get_providers(),
sess_options=session_options) | random_line_split |
evaluator.py | Cache:
def __init__(self):
self._cache: Dict[str, List[Optional["array.Array"]]] = {}
def merge(self, other):
self._cache = {**self._cache, **other._cache}
def add_entry(self, node_name: str, index: int, array: "array.Array"):
if node_name in self._cache:
entry = self._... | (self):
return self._cache
class ArrayNodeLookupTable:
def __init__(self):
self._input_table: Dict[str, Tuple["array.Array"]] = {}
self._output_table: Dict[str, Tuple["array.Array"]] = {}
def add_input(self, node_name: str, arrays: Tuple["array.Array"]):
self._input_table[node... | to_dict | identifier_name |
evaluator.py | def __init__(self):
self._cache: Dict[str, List[Optional["array.Array"]]] = {}
def merge(self, other):
self._cache = {**self._cache, **other._cache}
def add_entry(self, node_name: str, index: int, array: "array.Array"):
if node_name in self._cache:
entry = self._cache[n... | ort_value_dtype = np.longlong | conditional_block | |
evaluator.py | Cache:
def __init__(self):
self._cache: Dict[str, List[Optional["array.Array"]]] = {}
def merge(self, other):
|
def add_entry(self, node_name: str, index: int, array: "array.Array"):
if node_name in self._cache:
entry = self._cache[node_name]
if index >= len(entry):
# grow cache in order to fit the new entry
entry += [None] * (index - len(entry) + 1)
e... | self._cache = {**self._cache, **other._cache} | identifier_body |
main.js | }
// });
// 上传
var uploadBanner = function(target, callback) {
$(target).uploadify({
'auto': true,
'width': 80,
'height': 27,
'fileObjName': 'upfile',
'buttonText': '选择图片',
'swf': '/js/lib/uploadify/uploadify.swf',
'uploader': '/englishCompetition/upload?action=upload',... | random_line_split | ||
main.js | Zy') !== 1) {
$('.nav-sub > li:last > a').attr('href', Config.reportUrl + '/web/models/Login/self.php').text('退出');
clearAllCookie();
}
if (data.info.user.RoleType == 'teacher' && $.cookie('hasCp') == 1 && $.cookie('hasZy') == 1) {
$('.nav-sub > li:last > ... | p="three-level-menu"><a href="#" data-chivox-event="click:subMenuClick&xsxx&' + jd.id + '&' + jd.stage + '">' + jd.stageName + '</a></li>');
var $sj = $('<li data-chivox-group="three-level-menu"><a href="#" data-chivox-event="click:subMenuClick&fzsj&' + jd.id + '">' + jd.stageName + '<img src="/css/images... | identifier_body | |
main.js | 标题', // 中标题
// content: '正文', // 正文
// subcontent: '副文', //副文 灰色
// warnBtn: '删除', // 红
// cancelBtn: '关闭', // 白
// confirmBtn: '确认', // 绿
// isClose: true, //true有关闭 false没关闭
// timeout: true,
// timeoutConfig: {
// time: 5, // 秒
// text: '剩余{{time}}秒', // 剩余{{time}}秒
//... | anvas | identifier_name | |
dictionary.py |
interest.
:param int entry_id: The ID of the dictionary entry.
:param dict restrictions: A dictionary describing the restrictions imposed
on the possible structural ways in which the POS tags may interrelate.
Necessary in order to provide POS tag trees.
"""
def __init__(self... | r, %d, %d)>'
% (self.__class__.__name__, self.language_code, self.entry_id, self.sense_id))
def __s | identifier_body | |
dictionary.py | umber, bold_circle=True):
"""Provide a Unicode representation of the specified number.
:param int number: The positive number to convert to a string.
:param bool bold_circle: If ``True``, return a white number on a black
circle; return a black number on a white circle otherwise.
:return: A st... | rcled_number(n | identifier_name | |
dictionary.py | return chr(0x328d + number)
else:
return '(%s)' % (number,) # raise ValueError()
class Lexeme():
"""A lexeme (i.e. an entry) in the dictionary.
An entry in this context means a base meaning that may be denoted by either
element of a set of highly similar pairs of graphic and phonetic ... | A connotation may be described by multiple glosses, each of which can be a
direct translation, a description or similar.
On construction, all relevant data is loaded from the database.
| random_line_split | |
dictionary.py | .
:param bool bold_circle: If ``True``, return a white number on a black
circle; return a black number on a white circle otherwise.
:return: A string that is the specified number enclosed in a circle. For
integers that have no such representation in Unicode, return the number
enclosed... | elif bold_circle:
return '[%s]' % (number,) # raise ValueError()
elif number < 30:
return chr(0x323c + number)
elif number == 30:
return chr(0x325a)
elif number < 36:
return chr(0x323c + number)
elif number < 51:
return chr(0x328d + number)
else:
re... | turn chr(0x24e0 + number)
| conditional_block |
lib.rs | (|e| unsafe {libc::close(fd); e})?;
Ok(SerialPort{
fd: fd,
orig_settings: orig_settings,
is_raw: false,
})
}
/// Retrieve the termios structure for the serial port.
pub fn termios(&self) -> io::Result<termios::Termios> {
termios::Termios::from_f... | {
use termios::{B0, B50, B75, B110, B134, B150, B200, B300, B600,
B1200, B1800, B2400, B4800, B9600, B19200, B38400};
let s = self.termios()?;
// And the original rate
let baud = termios::cfgetospeed(&s);
let b = match baud {
B4800 => 4800,
... | identifier_body | |
lib.rs | {
fd: RawFd,
orig_settings: termios::Termios,
is_raw: bool,
}
impl SerialPort {
/// Construct a new SerialPort
///
/// Opens the a serial port at the location provided by `path` with the following
/// default settings:
///
/// - 9600,8N1 (9600 Baud, 8-bit data, no parity, 1 st... | SerialPort | identifier_name | |
lib.rs | .
let path_cstr = CString::new(path.as_ref().as_os_str().as_bytes())
.map_err(|_| io::Error::last_os_error())?;
// Attempt to open the desired path as a serial port. Set it read/write, nonblocking, and
// don't set it as the controlling terminal
let fd = uns... | /// - `Err(e)` for all other IO errors
pub fn maybe_read(&mut self, buf: &mut [u8]) -> io::Result<Option<usize>> {
match self.read(buf) {
Ok(s) => Ok(Some(s)),
Err(e) => {
if let io::ErrorKind::WouldBlock = e.kind() {
Ok(None)
... | /// # Returns
///
/// - `Ok(Some(size))` on successful reads
/// - `Ok(None)` if calling read would block. | random_line_split |
GradientBoostingClassifier.py | #amount committed to the loan
'funded_amnt_inv', #amount committed by investors for the loan
'installment', #monthly payment owed by the borrower
]
#Skip observations with missing values
loans = loans[[target] + features].dropna()
#Apply one-hot encoding to loans... | make_figure | identifier_name | |
GradientBoostingClassifier.py | for feat_name, feat_type in zip(loans.columns, loans.dtypes):
if feat_type == object:
categorical_variables.append(feat_name)
for feature in categorical_variables:
loans_one_hot_encoded = pd.get_dummies(loans[feature],prefix=feature)
loans = pd.concat([loans, loans_one_hot_encoded],axis=1)
... | plt.rcParams['figure.figsize'] = dim
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if legend is not None:
plt.legend(loc=legend, prop={'size':15})
plt.rcParams.update({'font.size': 16})
plt.tight_layout() | identifier_body | |
GradientBoostingClassifier.py | #one year or less of employment
'emp_length_num', #number of years of employment
'home_ownership', #home_ownership status: own, mortgage or rent
'dti', #debt to income ratio
'purpose', #the purpose of the loan
'payme... |
for feature in categorical_variables:
loans_one_hot_encoded = pd.get_dummies(loans[feature],prefix=feature)
loans = pd.concat([loans, loans_one_hot_encoded],axis=1)
loans = loans.drop(feature, axis=1)
#Import indices of train valid
train_idx = pd.read_json('module-8-assignment-1-train-idx.json')
... | if feat_type == object:
categorical_variables.append(feat_name) | conditional_block |
GradientBoostingClassifier.py | #interest rate of the loan
'total_rec_int', #interest received to date
'annual_inc', #annual income of borrower
'funded_amnt', #amount committed to the loan
'funded_amnt_inv', #amount committed by investors for the loan
'insta... | #model_100 has the best accuracy on the validation_data?
#it is not always true that the model with the most trees will perform best
#on test data?
#Plot the training and validation error vs. number of trees
| random_line_split | |
filterset.py | filter_name):
"""
Return a related filter_name, using the filterset relationship if present.
"""
if not filterset.relationship:
return filter_name
return LOOKUP_SEP.join([filterset.relationship, filter_name])
class FilterSetMetaclass(filterset.FilterSetMetaclass):
def __new__(cls, nam... |
@classmethod
def get_fields(cls):
fields = super(FilterSet, cls).get_fields()
for name, lookups in fields.items():
if lookups == filters.ALL_LOOKUPS:
field = get_model_field(cls._meta.model, name)
fields[name] = utils.lookups_for_field(field)
... | self.base_filters = self.get_filter_subset(data or {}, relationship)
super().__init__(data, queryset, **kwargs)
self.relationship = relationship
self.related_filtersets = self.get_related_filtersets()
self.filters = self.get_request_filters() | identifier_body |
filterset.py | .AutoFilter)]
new_class.related_filters = [
name for name, f in new_class.declared_filters.items()
if isinstance(f, filters.RelatedFilter)]
# see: :meth:`rest_framework_filters.filters.RelatedFilter.bind`
for name in new_class.related_filters:
new_class.decla... | for key, error in related_filterset.form.errors.items():
self.form.errors[related(related_filterset, key)] = error | conditional_block | |
filterset.py | filter_name):
"""
Return a related filter_name, using the filterset relationship if present.
"""
if not filterset.relationship:
return filter_name
return LOOKUP_SEP.join([filterset.relationship, filter_name])
class FilterSetMetaclass(filterset.FilterSetMetaclass):
def __new__(cls, nam... | (cls, params, rel=None):
"""
Returns the subset of filters that should be initialized by the
FilterSet, dependent on the requested `params`. This helps minimize
the cost of initialization by reducing the number of deepcopy ops.
The `rel` argument is used for related filtersets t... | get_filter_subset | identifier_name |
filterset.py | et, filter_name):
"""
Return a related filter_name, using the filterset relationship if present.
"""
if not filterset.relationship:
return filter_name
return LOOKUP_SEP.join([filterset.relationship, filter_name])
class FilterSetMetaclass(filterset.FilterSetMetaclass):
def __new__(cls, ... | new_class._meta = copy.deepcopy(new_class._meta)
new_class.declared_filters = new_class.declared_filters.copy()
for name in new_class.auto_filters:
f = new_class.declared_filters[name]
# Remove auto filters from declared_filters so that they *are* overwritten
... | orig_meta, orig_declared = new_class._meta, new_class.declared_filters
# override opts/declared filters w/ copies | random_line_split |
file.pb.go | {
return x.Permission
}
return 0
}
func (x *UploadReq) GetSubsection() bool {
if x != nil {
return x.Subsection
}
return false
}
func (x *UploadReq) GetStart() bool {
if x != nil {
return x.Start
}
return false
}
func (x *UploadReq) GetEnd() bool {
if x | oadReq) GetBody() []byte {
if x != nil {
return x.Body
}
return nil
}
func (x *UploadReq) GetReplace() bool {
if x != nil {
return x.Replace
}
return false
}
type Response struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Success bool ... | != nil {
return x.End
}
return false
}
func (x *Upl | identifier_body |
file.pb.go | nil {
return x.Permission
}
return 0
}
func (x *UploadReq) GetSubsection() bool {
if x != nil {
return x.Subsection
}
return false
}
func (x *UploadReq) GetStart() bool {
if x != nil {
return x.Start
}
return false
}
func (x *UploadReq) GetEnd() bool {
if x != nil {
return x.End
}
return false
}
... | 6, 0x69, 0x6c, 0x65, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x04, 0x66, 0x69, 0x6c, 0x65, 0x22, 0xd5, 0x01, 0x0a, 0x09,
0x55, 0x70, 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x65, 0x71, 0x12, 0x1e, 0x0a, 0x0a, 0x46, 0x69, 0x6c,
0x65, 0x4d, 0x64, 0x35, 0x73, 0x75, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x46,
0... | 75, 0x66, 0x2f, 0x6 | conditional_block |
file.pb.go | [0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UploadReq.ProtoReflect.Descriptor instead.
func (*UploadReq) Descriptor() ([]byte, []int) ... | gTypes | identifier_name | |
file.pb.go | 0x10, 0x0a, 0x03, 0x45, 0x6e, 0x64, 0x18, 0x08, 0x20, 0x01, 0x28, 0x08,
0x52, 0x03, 0x45, 0x6e, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x18, 0x09, 0x20,
0x01, 0x28, 0x0c, 0x52, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x72, 0x65, 0x70,
0x6c, 0x61, 0x63, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28... |
func NewDistributeClient(cc grpc.ClientConnInterface) DistributeClient {
return &distributeClient{cc} | random_line_split | |
psd_channel.rs | _height() * 4) as usize;
let red = self.red();
let green = self.green();
let blue = self.blue();
let alpha = self.alpha();
// TODO: We're assuming that if we only see two channels it is a 16 bit grayscale
// PSD. Instead we should just check the Psd's color mode and dep... | (
&self,
rgba: &mut Vec<u8>,
channel_kind: PsdChannelKind,
channel_bytes: &[u8],
) {
let mut cursor = PsdCursor::new(&channel_bytes[..]);
let mut idx = 0;
let offset = channel_kind.rgba_offset().unwrap();
let len = cursor.get_ref().len() as u64;
... | insert_rle_channel | identifier_name |
psd_channel.rs | _height() * 4) as usize;
let red = self.red();
let green = self.green();
let blue = self.blue();
let alpha = self.alpha();
// TODO: We're assuming that if we only see two channels it is a 16 bit grayscale
// PSD. Instead we should just check the Psd's color mode and dep... | sixteen_to_eight_rgba(red, green)
}
},
ChannelBytes::RleCompressed(red) => {
let red = &rle_decompress(red);
match self.green().unwrap() {
ChannelBytes::RawData(green) => sixteen_to_eight_rgba(red, green),
... | ChannelBytes::RawData(red) => match self.green().unwrap() {
ChannelBytes::RawData(green) => sixteen_to_eight_rgba(red, green),
ChannelBytes::RleCompressed(green) => {
let green = &rle_decompress(green);
| random_line_split |
psd_channel.rs | () * 4) as usize;
let red = self.red();
let green = self.green();
let blue = self.blue();
let alpha = self.alpha();
// TODO: We're assuming that if we only see two channels it is a 16 bit grayscale
// PSD. Instead we should just check the Psd's color mode and depth to s... |
let byte = cursor.read_1()[0];
for _ in 0..repeat as usize {
let rgba_idx = self.rgba_idx(idx);
rgba[rgba_idx * 4 + offset] = byte;
idx += 1;
}
};
}
}
}
/// Rle decompress a channel
fn ... | {
break;
} | conditional_block |
train_nn.py | , data_dir, model_dir, task_id, isInteractive=True, OOV=False,
memory_size=50, random_state=None, batch_size=32, learning_rate=0.001, epsilon=1e-8,
max_grad_norm=40.0, evaluation_interval=10, hops=3, epochs=200, embedding_size=20, save_model=10,
checkpoint_path='./mode... |
elif self.optim == 'rms':
optimizer = torch.optim.RMSprop(self.model.parameters(), lr=self.learning_rate, momentum=self.momentum)
print("RMSprop optimizer")
else:
optimizer = torch.optim.Adam(self.model.parameters(), lr=self.learning_rate)
print("Adam opt... | optimizer = torch.optim.SGD(self.model.parameters(), lr=self.learning_rate, momentum=self.momentum)
print("SGD optimizer") | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.