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 |
|---|---|---|---|---|
zplsc_c_echogram.py | 35
TVR = []
VTX = []
BP = []
EL = []
DS = []
# Freq 38kHz
TVR.append(1.691999969482e2)
VTX.append(1.533999938965e2)
BP.append(8.609999902546e-3)
EL.append(1.623000030518e2)
DS.append(2.280000038445e-2)
# Freq 125kHz
TVR.append(1.668999938965e2)
VTX.append(5.8e+... | (power_dict):
for channel in power_dict:
# Transpose array data so we have time on the x-axis and depth on the y-axis
power_dict[channel] = power_dict[channel].transpose()
# reverse the Y axis (so depth is measured from the surface (at the top) to the ZPLS (at the bottom)
... | _transpose_and_flip | identifier_name |
zplsc_c_echogram.py | (1.696000061035e2)
VTX.append(1.301000061035e2)
BP.append(8.609999902546e-3)
EL.append(1.491999969482e2)
DS.append(2.300000004470e-2)
class ZPLSCCPlot(object):
font_size_small = 14
font_size_large = 18
num_xticks = 25
num_yticks = 7
interplot_spacing = 0.1
lower_percentile = 5
... | for chan in range(profile_hdr.num_channels):
_N.append(np.array(chan_data[chan])) | conditional_block | |
zplsc_c_echogram.py | 35
TVR = []
VTX = []
BP = []
EL = []
DS = []
# Freq 38kHz
TVR.append(1.691999969482e2)
VTX.append(1.533999938965e2)
BP.append(8.609999902546e-3)
EL.append(1.623000030518e2)
DS.append(2.280000038445e-2)
# Freq 125kHz
TVR.append(1.668999938965e2)
VTX.append(5.8e+... |
@staticmethod
def _display_colorbar(fig, data_axes):
# Add a colorbar to the specified figure using the data from the given axes
ax = fig.add_axes([0.965, 0.12, 0.01, 0.775])
cb = fig.colorbar(data_axes, cax=ax, use_gridspec=True)
cb.set_label('dB', fontsize=ZPLSCCPlot.font_siz... | time_format = '%Y-%m-%d\n%H:%M:%S'
time_length = data_times.size
# X axis label
# subset the xticks so that we don't plot every one
if time_length < ZPLSCCPlot.num_xticks:
ZPLSCCPlot.num_xticks = time_length
xticks = np.linspace(0, time_length, ZPLSCCPlot.num_xticks)
... | identifier_body |
zplsc_c_echogram.py | self.fig.tight_layout(rect=[0, 0.0, 0.97, 1.0])
self._display_colorbar(self.fig, data_axes)
def write_image(self, filename):
self.fig.savefig(filename)
plt.close(self.fig)
self.fig = None
def _setup_plot(self, depth_range, max_depth):
# subset the yticks so that we... | _m.append(np.array([x for x in range(1, (profile_hdr.num_bins[chan]/self.params.Bins2Avg)+1)]))
depth_range.append(sound_speed*profile_hdr.lockout_index[0]/(2*profile_hdr.digitization_rate[0]) +
(sound_speed/4)*(((2*_m[chan]-1)*profile_hdr.range_samples[0]*self.par... | random_line_split | |
index.js | extends Component {
_isMounted = false
constructor(props) {
super(props);
this.state = {
items: {},
isDialogVisible: false,
notifyEvents: this.notify(props.navigation.state.params.events),
pushNotficationToken: '',
timeToNotify: 1,
synchronizedEvents:
this.struc... | DashboardScreen | identifier_name | |
index.js | _isMounted = false
constructor(props) {
super(props);
this.state = {
items: {},
isDialogVisible: false,
notifyEvents: this.notify(props.navigation.state.params.events),
pushNotficationToken: '',
timeToNotify: 1,
synchronizedEvents:
this.structureSynchronizedEvent... |
}
});
return notifyArray;
};
/**
* Schedules push notifications to user upon adjusting the timer
*/
sendPushNotification = () => {
Notifications.cancelAllScheduledNotificationsAsync();
this.state.notifyEvents.forEach((element) => {
const localNotification = {
... | {
notifyArray.push({
startDate: element.start.dateTime,
summary: element.summary,
});
} | conditional_block |
index.js | _isMounted = false
constructor(props) {
super(props);
this.state = {
items: {},
isDialogVisible: false,
notifyEvents: this.notify(props.navigation.state.params.events),
pushNotficationToken: '',
timeToNotify: 1,
synchronizedEvents:
this.structureSynchronizedEvent... |
/**
* @param {integer} time - time of the event
* restructure time in a certain format
*/
timeToString(time) {
const date = new Date(time);
return date.toISOString().split('T')[0];
}
/**
* @param {object} events - All the events the user has
* Structures all... | {
return r1.name !== r2.name;
} | identifier_body |
index.js | {
_isMounted = false
constructor(props) {
super(props);
this.state = {
items: {},
isDialogVisible: false,
notifyEvents: this.notify(props.navigation.state.params.events),
pushNotficationToken: '',
timeToNotify: 1,
synchronizedEvents:
this.structureSynchronizedEv... |
/**
*
* @param {object} day - information of the current day
* formats items with information of the day
*/
loadItems = (day) => {
setTimeout(() => {
const uppderBoundForSync = 85;
const lowerBoundForSync = -15;
for (let i = lowerBoundForSync; i < uppderBoundForSync; i++) {
... | { text: 'ok' }
]);
}
} | random_line_split |
browse.ts | /api';
import { SettingsProvider } from '../../../providers/settings/settings';
import { Network } from '@ionic-native/network';
import { CoursePage } from '../course/course';
/**
* Generated class for the BrowsePage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pag... | () {
this.loading = await this.loadingController.create({
content: 'Loading. Please wait...',
duration: 2000000000
});
return await this.loading.present();
}
getButtonText(): string {
return `Switch ${ this.isOn ? 'Off' : 'On' }`;
}
setState(): void {
this.isOn = !this.isOn;
... | presentLoading | identifier_name |
browse.ts | /api';
import { SettingsProvider } from '../../../providers/settings/settings';
import { Network } from '@ionic-native/network';
import { CoursePage } from '../course/course';
/**
* Generated class for the BrowsePage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pag... | handler: () => {
this.params.sort = "recent";
this.reloadCourses(1);
}
}, {
text: 'Price (Lowest)',
icon: 'cash',
handler: () => {
this.params.sort = "priceAsc";
this.reloadCourses(1);
}
},{
... | {
const actionSheet = await this.actionSheetController.create({
title: 'Sort By',
buttons: [{
text: 'Alphabetical (asc)',
icon: 'arrow-round-up',
handler: () => {
this.params.sort = "asc";
this.reloadCourses(1);
}
}, {
... | identifier_body |
browse.ts | ';
import { SettingsProvider } from '../../../providers/settings/settings';
import { Network } from '@ionic-native/network';
import { CoursePage } from '../course/course';
/**
* Generated class for the BrowsePage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages a... |
}, 3000);
});
}
search(){
this.showLoading = true;
this.loadCourses(1).subscribe(resp=>{
this.courses = resp['records'];
this.showLoading = false;
}, err => {
this.showRetry = true;
this.showLoading= false;
this.presentToast('Network error! Please check your Internet ... | {
console.log('we got a wifi connection, woohoo!');
this.networkPresent= true;
} | conditional_block |
browse.ts | /api';
import { SettingsProvider } from '../../../providers/settings/settings';
import { Network } from '@ionic-native/network';
import { CoursePage } from '../course/course';
/**
* Generated class for the BrowsePage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pag... | type:''
};
this.sortLib = {
asc : "Alphabetical (asc)",
desc: "Alphabetical (desc)",
recent : "Most Recent",
priceAsc : "Price (Lowest)",
priceDesc : "Price (Highest)",
c : "Online Courses",
"s-b" : "Training Sessions"
};
console.log(this.params);
console.log(this.sortLib... | group:'', | random_line_split |
lib.rs | coords.iter().copied().collect() }
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ConwayCube {
Void,
Inactive,
Active,
}
impl ConwayCube {
/// Construct cube from input character.
#[must_use]
pub fn from_char(cube: char) -> ConwayCube {
match cube {
'.' => C... |
#[test]
fn test_grid_indexing() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[1, 0, 1]);
assert_eq!(ConwayCube::Active, grid.cube_at(&pos));
let pos = Position::from(&[1, 1, 0]);
assert_eq!(ConwayCube::Inactive, grid.cube_at(... | {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
assert_eq!(3, grid.edge);
assert_eq!(5, grid.active_cubes());
} | identifier_body |
lib.rs | : coords.iter().copied().collect() }
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ConwayCube {
Void,
Inactive,
Active,
}
impl ConwayCube {
/// Construct cube from input character.
#[must_use]
pub fn from_char(cube: char) -> ConwayCube {
match cube {
'.' => ... | // create empty nD grid, and copy initial 2D grid plane to it
// (in the middle of each dimension beyond the first two):
let max_i = InfiniteGrid::index_size(edge, dim);
let mut cubes: Vec<ConwayCube> = vec![ConwayCube::Void; max_i];
for y in 0..edge {
for x in 0..edg... | .lines()
.flat_map(|line| line.trim().chars().map(ConwayCube::from_char))
.collect(); | random_line_split |
lib.rs | ={}", axes[d - 2], coords[self.dim - d - 1] - half_edge);
s += &label;
}
s += "\n";
}
let pos = Position::from(&coords);
s += match self.cube_at(&pos) {
ConwayCube::Void => "_",
ConwayCube::Inactive =... | test_6_rounds_4d | identifier_name | |
lib.rs | Iter {
layout: InfiniteGrid,
}
impl Iterator for InfiniteGridIter {
type Item = InfiniteGrid;
fn next(&mut self) -> Option<Self::Item> {
let prev_layout = self.layout.clone();
self.layout = prev_layout.cube_round();
Some(self.layout.clone())
}
}
impl InfiniteGrid {
/// Ret... | { 3*4 + 5 + 3*4 } | conditional_block | |
encoder.rs | om_codec_cx_pkt_kind::AOM_CODEC_CUSTOM_PKT => {
let b = to_buffer(unsafe { pkt.data.raw });
AOMPacket::Custom(b)
}
_ => panic!("No packet defined"),
}
}
}
#[cfg(target_os = "windows")]
fn map_fmt_to_img(img: &mut aom_image, fmt: &Formaton) {
img.c... | (&mut self) -> Result<()> {
if self.enc.is_none() {
self.cfg
.get_encoder()
.map(|enc| {
self.enc = Some(enc);
})
.map_err(|_err| Error::ConfigurationIncomplete)
} else {
... | configure | identifier_name |
encoder.rs | method.get_packet
pub fn flush(&mut self) -> Result<(), aom_codec_err_t::Type> {
let ret = unsafe { aom_codec_encode(&mut self.ctx, ptr::null_mut(), 0, 1, 0) };
self.iter = ptr::null();
match ret {
aom_codec_err_t::AOM_CODEC_OK => Ok(()),
_ => Err(ret),
}
... | {
use super::AV1_DESCR;
use av_codec::common::CodecList;
use av_codec::encoder::*;
use av_codec::error::*;
use std::sync::Arc;
let encoders = Codecs::from_list(&[AV1_DESCR]);
let mut ctx = Context::by_name(&encoders, "av1").unwrap();
let w = 200;
... | identifier_body | |
encoder.rs | .expect("Cannot set CPUUSED");
Ok(enc)
}
_ => Err(ret),
}
}
/// Update the encoder parameters after-creation
///
/// It calls `aom_codec_control_`
pub fn control(
&mut self,
id: aome_enc_control_id::Type,
val: i32,
) -> R... | random_line_split | ||
example_scenes.py | _graph_label(sin_graph, "\\sin(x)")
relu_label = axes.get_graph_label(relu_graph, Text("ReLU"))
step_label = axes.get_graph_label(step_graph, Text("Step"), x=4)
self.play(
ShowCreation(sin_graph),
FadeIn(sin_label, RIGHT),
)
self.wait(2)
self.play... | def setup(self): | random_line_split | |
example_scenes.py | )
fonts.set_width(FRAME_WIDTH - 1)
slant = Text(
"And the same as slant and weight",
font="Consolas",
t2s={"slant": ITALIC},
t2w={"weight": BOLD},
t2c={"slant": ORANGE, "weight": RED}
)
VGroup(fonts, slant).arrange(DOWN,... | text = Text("Here is a text", font="Consolas", font_size=90)
difference = Text(
"""
The most important difference between Text and TexText is that\n
you can change the font more easily, but can't use the LaTeX grammar
""",
font="Arial", font_size=24,
... | identifier_body | |
example_scenes.py | _point, abbreviated
# to axes.i2gp, to find a particular point on a graph
dot = Dot(color=RED)
dot.move_to(axes.i2gp(2, parabola))
self.play(FadeIn(dot, scale=0.5))
# A value tracker lets us animate a parameter, usually
# with the intent of having other mobjects update b... | new_text.set_fill(
color=self.color_picker.get_picked_color(),
opacity=self.color_picker.get_picked_opacity()
) | conditional_block | |
example_scenes.py | , label)
# Notice that the brace and label track with the square
self.play(
square.animate.scale(2),
rate_func=there_and_back,
run_time=2,
)
self.wait()
self.play(
square.animate.set_width(5, stretch=True),
run_time=3,
... | func | identifier_name | |
Skycam.py | (tuple of floats) coordinates of node0, node1, node2
'''
# Project lengths into xy plane
a_eff = ((zC-zB)**2 + c**2)**.5
b_eff = (zC**2 + b**2)**.5
c_eff = (zB**2 + c**2)**.5
# Law of cosines
numer = b_eff**2 + c_eff**2 - a_eff**2
denom = 2*b_eff*c_eff
... | (self, ustart, s, dl, tol=.01):
''' Perform a binary search to find parametrized location of point.
Inputs:
ustart: (float)
s: (spline object)
dl: (float)
tol: (float)
Returns:
Reassigns middle and endpoint... | binary_search | identifier_name |
Skycam.py | (tuple of floats) coordinates of node0, node1, node2
'''
# Project lengths into xy plane
a_eff = ((zC-zB)**2 + c**2)**.5
b_eff = (zC**2 + b**2)**.5
c_eff = (zB**2 + c**2)**.5
# Law of cosines
numer = b_eff**2 + c_eff**2 - a_eff**2
denom = 2*b_eff*c_eff
... | # create spline and calculate length
s, us = splprep([xpoints, ypoints, zpoints], s=s, k=k, nest=nest)
totl = self.splineLen(s)
dl = totl/steps
if dl > 1:
print "dl greater than 1!"
i = 0
u = 0
upath = [u]
# Divide path into equidis... | ''' Generate a new list of points based on waypoints.
Inputs:
waypoints: (list of tuples of floats): points the path should
bring the camera to
steps: (int) number of steps in which to complete the path
Returns:
Calls ... | identifier_body |
Skycam.py | (tuple of floats) coordinates of node0, node1, node2
'''
# Project lengths into xy plane
a_eff = ((zC-zB)**2 + c**2)**.5
b_eff = (zC**2 + b**2)**.5
c_eff = (zB**2 + c**2)**.5
# Law of cosines
numer = b_eff**2 + c_eff**2 - a_eff**2
denom = 2*b_eff*c_eff
... |
return totl
def tighten(self):
''' Calibrate node lengths to current position of camera.
Enter ' ' to tighten
Enter 's' to accept node length
'''
while True:
input = raw_input('Tightening Node A')
if input == ' ':
s... | totl += distance(point, ipoint)
ipoint = point | conditional_block |
Skycam.py | (tuple of floats) coordinates of node0, node1, node2
'''
# Project lengths into xy plane
a_eff = ((zC-zB)**2 + c**2)**.5
b_eff = (zC**2 + b**2)**.5
c_eff = (zB**2 + c**2)**.5
# Law of cosines
numer = b_eff**2 + c_eff**2 - a_eff**2
denom = 2*b_eff*c_eff
... | Calls load_path method on list of generated spline points
'''
xpoints = [point[0] for point in waypoints]
ypoints = [point[1] for point in waypoints]
zpoints = [point[2] for point in waypoints]
# spline parameters
s = 2.0 # smoothness
k = 1 # spl... | steps: (int) number of steps in which to complete the path
Returns: | random_line_split |
kafka.go | if publishBuilderEntry.encoded == nil && publishBuilderEntry.err == nil {
if publishBuilderEntry.traceId == "" {
publishBuilderEntry.traceId = generateID()
}
if publishBuilderEntry.messageId == "" {
publishBuilderEntry.messageId = generateID()
}
publishBuilderEntry.encoded, publishBuilderEntry.err =... | else {
defer func() {
err := deleteTopic(client.broker, topic)
if err != nil {
logrus.Error("unable to delete topic in kafka : ", err)
return
}
}()
err := createTopic(client.broker, topic)
if err != nil {
logrus.Error("unable to create topic in kafka : ", err)
return
}
// listening... | {
logrus.Warn("topic and message type already registered")
} | conditional_block |
kafka.go | if publishBuilderEntry.encoded == nil && publishBuilderEntry.err == nil {
if publishBuilderEntry.traceId == "" {
publishBuilderEntry.traceId = generateID()
}
if publishBuilderEntry.messageId == "" {
publishBuilderEntry.messageId = generateID()
}
publishBuilderEntry.encoded, publishBuilderEntry.err =... |
// PublishSync push a message to message broker topic synchronously
func (client *KafkaClient) PublishSync(publishBuilder *PublishBuilder) error {
// send message
_, _, err := client.syncProducer.SendMessage(&sarama.ProducerMessage{
Timestamp: time.Now().UTC(),
Value: &PublishBuilderEntry{
PublishBuilder: *p... | Topic: constructTopic(client.realm, publishBuilder.topic),
}
} | random_line_split |
kafka.go | publishBuilderEntry.ensureEncoded()
return publishBuilderEntry.encoded, publishBuilderEntry.err
}
// Length returns size of encoded value
func (publishBuilderEntry *PublishBuilderEntry) Length() int {
publishBuilderEntry.ensureEncoded()
return len(publishBuilderEntry.encoded)
}
// NewKafkaClient create a new inst... | deleteTopic | identifier_name | |
kafka.go | logrus.Error("unable to open kafka")
return nil, err
}
if connected, err := broker.Connected(); !connected {
logrus.Error("unable connect to kafka")
return nil, err
}
configAsync := sarama.NewConfig()
if securityConfig != nil && securityConfig.AuthenticationType == saslScramAuth {
configureSASLScramAuth... | {
if subscribeMap == nil {
subscribeMap = make(map[string]map[string]func(message *Message, err error))
}
if callbackMap, isTopic := subscribeMap[topic]; isTopic {
if _, isMsgType := callbackMap[messageType]; isMsgType {
return true
}
}
newCallbackMap := make(map[string]func(message *Message, err error)... | identifier_body | |
pathfinding.py | range(0, layer.GetFeatureCount()):
feat = layer.GetFeature(i)
geom = feat.geometry()
if geom is None:
continue
line = []
if geom.GetGeometryCount() > 0:
for j in range(0, geom.GetGeometryCount()):
g = feat.geometry().GetGeometryRef(j)
... | = 30 # 240
else:
length_part = 5
degree_delta = 90 # 20
print("读取TIFF文件中...")
try:
tif = TIFF.open(args.gridMap, mode='r') # 打開tiff文件進行讀取
except:
print("输入的路径有误!")
im = tif.read_image()
print("正在分析各类地块...")
class4 = cv2.inRange(im, 3.9, 4.1)
class1 | :
length_part = 20
degree_delta | conditional_block |
pathfinding.py | range(0, layer.GetFeatureCount()):
feat = layer.GetFeature(i)
geom = feat.geometry()
if geom is None:
continue
line = []
if geom.GetGeometryCount() > 0:
for j in range(0, geom.GetGeometryCount()):
g = feat.geometry().GetGeometryRef(j)
... | , gridMap, background, openset_size, length_part, degree_delta,
roads=None):
# time1 = time.time()
# gridMap = np.load('../res/sampled_sketch.npy')
# gridMap = np.load('map.npy')
# time2 = time.time()
# print("图片加载完毕,耗时{}".format(time2 - time1))
# maze = cv2.inRange(gridMap, 2.9, 3.1)
... | neigh_range | identifier_name |
pathfinding.py | range(0, layer.GetFeatureCount()):
feat = layer.GetFeature(i)
geom = feat.geometry()
if geom is None:
continue
line = []
if geom.GetGeometryCount() > 0:
for j in range(0, geom.GetGeometryCount()):
g = feat.geometry().GetGeometryRef(j)
... | t, end, neigh_range, gridMap, background, openset_size, length_part, degree_delta,
roads=None):
# time1 = time.time()
# gridMap = np.load('../res/sampled_sketch.npy')
# gridMap = np.load('map.npy')
# time2 = time.time()
# print("图片加载完毕,耗时{}".format(time2 - time1))
# maze = cv2.inRange(gr... | e_generator(gridMap):
s_x, s_y = point_generator(gridMap, 1)
e_x, e_y = point_generator(gridMap, 1)
return s_x, s_y, e_x, e_y
def run(_ver, _return_dict, star | identifier_body |
pathfinding.py | range(0, layer.GetFeatureCount()):
feat = layer.GetFeature(i)
geom = feat.geometry()
if geom is None:
continue
line = []
if geom.GetGeometryCount() > 0:
for j in range(0, geom.GetGeometryCount()):
g = feat.geometry().GetGeometryRef(j)
... | cv2.circle(background, p, 10, (0, 0, 255), 5)
for index, p in enumerate(path):
if index == 0:
continue
p2 = p
cv2.line(background, p1, p2, (255, 0, 0), 40)
p1 = p
for p in path:
cv2.circle(background, p, 10, (0, 0, 0), 40)
# for p in finder.close_s... | random_line_split | |
get_tips_nonlocal.py | or y for the padding:
[0... pad | pad ... width + pad | width + pad ... width + 2 * pad]
return -9999 if X is within rejection_distance of the edge,
return X if X is in [pad ... width + pad], which is if X is in the unpadded frame, which has width = width
else return X reflected onto the unpadded frame... | (mat, pad, channel_no=3):
''''''
return np.pad(array = mat, pad_width = pad, mode = 'wrap')[...,pad:pad+channel_no]
# width, height = mat.shape[:2]
# padded_width = 512 + pad #pixels
# padded_mat = np.pad(array = mat, pad_width = pad, mode = 'wrap')
# return padded_mat[...,2:5]
# @njit
def pad_... | pad_matrix | identifier_name |
get_tips_nonlocal.py | _tips[n]
y = y_tips[n]
for X, Y in zip(x, y):
X = unpad(X=X, pad=pad, width=width , rejection_distance=edge_tolerance)
if not (X == -9999):
Y = unpad(X=Y, pad=pad, width=height, rejection_distance=edge_tolerance)
if not (Y == -9999):
... | '''get the gradient direction field, N
out_Nx, out_Ny = get_grad_direction(texture)
'''
height, width = texture.shape
out_Nx = np.zeros_like(texture, dtype=np.float64)
out_Ny = np.zeros_like(texture, dtype=np.float64)
DX = 1/0.025; DY = 1/0.025;
for y in range(height):
for x in range... | identifier_body | |
get_tips_nonlocal.py | x or y for the padding:
[0... pad | pad ... width + pad | width + pad ... width + 2 * pad]
return -9999 if X is within rejection_distance of the edge,
return X if X is in [pad ... width + pad], which is if X is in the unpadded frame, which has width = width
else return X reflected onto the unpadded fra... | s1_mapped_lst.append(lst_S1)
s2_mapped_lst.append(lst_S2)
else:
#just append to the previous entry in the s1 and s2 lists if the contour isn't already there
s1_mapped_lst[min_index].append(S1)
... | lst_S1 = []#List()
lst_S1.append(S1)
lst_S2 = []#List()
lst_S2.append(S2) | random_line_split |
get_tips_nonlocal.py | X = unpad(X=X, pad=pad, width=width , rejection_distance=edge_tolerance)
if not (X == -9999):
Y = unpad(X=Y, pad=pad, width=height, rejection_distance=edge_tolerance)
if not (Y == -9999):
# find the index and distance to the nearest tip alread... | out_Nx[y,x] = Nx/norm
out_Ny[y,x] = Ny/norm | conditional_block | |
details.js | if(iLeft<0) {
// iLeft = 0;
// } else if(iLeft>iWidht) {
// iLeft = iWidht;
// }
//
// if(iTop<0) {
// iTop = 0;
// } else if(iTop>iHeight) {
// iTop = iHeight;
// }
// $(".zoomShow-pud").css({"left":iLeft,"top":iTop})
// $(".bigShow").find("img").css({"left":-iLeft/4*15,"top":-iTop/4*15})
// //不想写了就用死... | imgSrc:cl.imgSrc+"detalis-zoomdiv-zhong1.JPG",
id:cl.id,
color:cl.color,
size:cl.size,
price:cl.price,
//iNum:num
}
// var value=0
// if($.cookie("carList")){
// for(var i in JSON.parse($.cookie("carList"))){
// value +=parseInt(JSON.parse($.cookie("carList"))[i].iNum)
// }
// //value=parseInt(JSON.pa... | $(".addCart").css("cursor","pointer")
var num1=0;num2=0;
if($.cookie("carList1")){
num1=parseInt(JSON.parse($.cookie("carList1")).iNum)
}
if($.cookie("carList2")){
num2=parseInt(JSON.parse($.cookie("carList2")).iNum)
}
//判断是否存在cookie
// if($.cookie("carList")){
// for(var m in JSON.parse($.cookie("carList")... | identifier_body |
details.js | if(iLeft<0) {
// iLeft = 0;
// } else if(iLeft>iWidht) {
// iLeft = iWidht;
// }
//
// if(iTop<0) {
// iTop = 0;
// } else if(iTop>iHeight) {
// iTop = iHeight;
// }
// $(".zoomShow-pud").css({"left":iLeft,"top":iTop})
// $(".bigShow").find("img").css({"left":-iLeft/4*15,"top":-iTop/4*15})
// //不想写了就用死... | .id
$(".addCart").css("cursor","pointer")
var num1=0;num2=0;
if($.cookie("carList1")){
num1=parseInt(JSON.parse($.cookie("carList1")).iNum)
}
if($.cookie("carList2")){
num2=parseInt(JSON.parse($.cookie("carList2")).iNum)
}
//判断是否存在cookie
// if($.cookie("carList")){
// for(var m in JSON.parse($.cookie("carLi... | odid=cl | identifier_name |
details.js | if(iLeft<0) {
// iLeft = 0;
// } else if(iLeft>iWidht) {
// iLeft = iWidht;
// }
//
// if(iTop<0) {
// iTop = 0;
// } else if(iTop>iHeight) {
// iTop = iHeight;
// }
// $(".zoomShow-pud").css({"left":iLeft,"top":iTop})
// $(".bigShow").find("img").css({"left":-iLeft/4*15,"top":-iTop/4*15})
// //不想写了就用死... | num1=parseInt(JSON.parse($.cookie("carList1")).iNum)
}
if($.cookie("carList2")){
num2=parseInt(JSON.parse($.cookie("carList2")).iNum)
}
//判断是否存在cookie
// if($.cookie("carList")){
// for(var m in JSON.parse($.cookie("carList"))){
// num+=parseInt(JSON.parse($.cookie("carList"))[m].iNum)
// //这里有bug每次累加是2个加起... | $(".addCart").css("cursor","pointer")
var num1=0;num2=0;
if($.cookie("carList1")){ | random_line_split |
reduc_spec.py | )
'''
if all([((type(arg) is tuple) or (arg is None)) for arg in args]):
ts, tf = args[0], args[1]
d=in_out.read_time_range(dt_0=ts,dt_f=tf, ext=kwargs.get('ext'))
elif any(('.h5' in arg for arg in args)):
d=in_out.read_to_arrays([arg for arg in args if '.h5' ... | (self):
"""Scale by P->TRJ factor"""
# Convert to RJ temperature
#fac=planck.I2Ta(self.f*1e6,1).value
fac = planck(self.f*1e6, 1)
fac=fac/fac[0]
self.spec=self.spec*np.tile(fac,(self.spec.shape[0],1))
def _getscanind(self):
"""Identify start/stop indi... | P2T | identifier_name |
reduc_spec.py | )
'''
if all([((type(arg) is tuple) or (arg is None)) for arg in args]):
ts, tf = args[0], args[1]
d=in_out.read_time_range(dt_0=ts,dt_f=tf, ext=kwargs.get('ext'))
elif any(('.h5' in arg for arg in args)):
d=in_out.read_to_arrays([arg for arg in args if '.h5' ... | if ind.size>0:
# If it exists, append it
cblk=np.append(cblk,ind[-1])
# Find trailing cal stare
ind=np.where(cs>=se)[0]
if ind.size>0:
# If it exists, append it
cblk=np.appen... | ind=np.where(ce<=ss)[0] | random_line_split |
reduc_spec.py | )
'''
if all([((type(arg) is tuple) or (arg is None)) for arg in args]):
ts, tf = args[0], args[1]
d=in_out.read_time_range(dt_0=ts,dt_f=tf, ext=kwargs.get('ext'))
elif any(('.h5' in arg for arg in args)):
d=in_out.read_to_arrays([arg for arg in args if '.h5' ... |
return
for k in range(self.nscan):
# Each scan
ind=self.getscanind(k)
for j,val in | p=np.polyfit(x[scanind],y[scanind],deg=deg)
# Don't remove mean
p[-1]=0
self.spec[:,k]=self.spec[:,k]-np.poly1d(p)(x) | conditional_block |
reduc_spec.py | )
'''
if all([((type(arg) is tuple) or (arg is None)) for arg in args]):
ts, tf = args[0], args[1]
d=in_out.read_time_range(dt_0=ts,dt_f=tf, ext=kwargs.get('ext'))
elif any(('.h5' in arg for arg in args)):
d=in_out.read_to_arrays([arg for arg in args if '.h5' ... |
def reduc(self,zarange=[20,50]):
"""Main reduction script. Elrange is two element list or tuple over
which to perform airmass regression (inclusive)"""
# First, take out a secular gain drift for each constant elevation
# stare. Fit P(t) to each channel in a contig... | """Zenith angle in degrees to airmass"""
return 1/cosd(x) | identifier_body |
_ToolBar.ts | : (ev: CustomEvent) => void;
/// <field type="Function" locid="WinJS.UI.ToolBar.onafteropen" helpKeyword="WinJS.UI.ToolBar.onafteropen">
/// Occurs immediately after the control is opened.
/// </field>
onafteropen: (ev: CustomEvent) => void;
/// <field type="Function" locid="WinJS.UI.ToolBar.onbefor... | {
this._synchronousClose();
} | conditional_block | |
_ToolBar.ts | same stacking context pitfalls
// as any other light dismissible. https://github.com/winjs/winjs/wiki/Dismissables-and-Stacking-Contexts
// - Reposition the ToolBar element to be exactly overlaid on top of the placeholder element.
// - Render the ToolBar as opened, via t... |
/// <field type="WinJS.Binding.List" locid="WinJS.UI.ToolBar.data" helpKeyword="WinJS.UI.ToolBar.data">
/// Gets or sets the Binding List of WinJS.UI.Command for the ToolBar.
/// </field>
get data() {
return this._commandingSurface.data;
}
set data(value: BindingList.List<_Command.ICom... | {
return this._dom.root;
} | identifier_body |
_ToolBar.ts | Surface.opened;
}
set opened(value: boolean) {
this._commandingSurface.opened = value;
}
constructor(element?: HTMLElement, options: any = {}) {
/// <signature helpKeyword="WinJS.UI.ToolBar.ToolBar">
/// <summary locid="WinJS.UI.ToolBar.constructor">
/// Creates a new To... | root.setAttribute("role", "menubar");
}
var label = root.getAttribute("aria-label"); | random_line_split | |
_ToolBar.ts | private _isOpenedMode: boolean;
private _handleShowingKeyboardBound: (ev: any) => void;
private _dismissable: _LightDismissService.LightDismissableElement;
private _cachedClosedHeight: number;
private _dom: {
root: HTMLElement;
commandingSurfaceEl: HTMLElement;
placeHolder: ... | getCommandById | identifier_name | |
update.py | pragma: no cover
toml = None # type: ignore
CruftState = Dict[str, Any]
@example(skip_apply_ask=False)
@example()
def update(
project_dir: Path = Path("."),
cookiecutter_input: bool = False,
skip_apply_ask: bool = True,
skip_update: bool = False,
checkout: Optional[str] = None,
strict: ... | (diff: str, expanded_dir_path: Path):
try:
run(
["git", "apply", "-3"],
input=diff.encode(),
stderr=PIPE,
stdout=PIPE,
check=True,
cwd=expanded_dir_path,
)
except CalledProcessError as error:
typer.secho(error.stderr... | _apply_three_way_patch | identifier_name |
update.py | pragma: no cover
toml = None # type: ignore
CruftState = Dict[str, Any]
@example(skip_apply_ask=False)
@example()
def update(
project_dir: Path = Path("."),
cookiecutter_input: bool = False,
skip_apply_ask: bool = True,
skip_update: bool = False,
checkout: Optional[str] = None,
strict: ... |
def _is_git_repo(directory: Path):
# Taken from https://stackoverflow.com/a/16925062
# This works even if we are in a sub folder in a git
# repo
output = run(
["git", "rev-parse", "--is-inside-work-tree"], stdout=PIPE, stderr=DEVNULL, cwd=directory
)
if b"true" in output.stdout:
... | run(["git", "diff", "--no-index", str(old_main_directory), str(new_main_directory)]) | identifier_body |
update.py | toml = None # type: ignore
CruftState = Dict[str, Any]
@example(skip_apply_ask=False)
@example()
def update(
project_dir: Path = Path("."),
cookiecutter_input: bool = False,
skip_apply_ask: bool = True,
skip_update: bool = False,
checkout: Optional[str] = None,
strict: bool = True,
) -> ... | _apply_three_way_patch(diff, expanded_dir_path) | conditional_block | |
update.py | json_dumps,
)
try:
import toml # type: ignore
except ImportError: # pragma: no cover
toml = None # type: ignore
CruftState = Dict[str, Any]
@example(skip_apply_ask=False)
@example()
def update(
project_dir: Path = Path("."),
cookiecutter_input: bool = False,
skip_apply_ask: bool = True,
... | generate_cookiecutter_context,
get_cookiecutter_repo,
get_cruft_file,
is_project_updated, | random_line_split | |
main.rs | if reader.read_u32() != 0 {
println!("Failed to connect to igbp");
return Ok(());
}
qbo
};
println!("Allocate framebuffers");
let mut mem : Vec<BufferMemory> = Vec::with_capacity(3);
unsafe { mem.set_len(3); }
// Disables caching when talking to the g... |
GpuBuffer {
nvmap_handle: create.handle,
size: mem.len() * std::mem::size_of::<BufferMemory>(),
alignment: 0x1000,
kind: 0
}
};
let buffers = {
let mut alloc = NvMapIocAllocArgs {
handle: gpu_buffer.nvmap_handle,
h... | {
return Err(MyError::IoctlError(ret));
} | conditional_block |
main.rs | .write_u32(1); // Pixel format
parcel.write_u32(1280); // width
parcel.write_u32(720); // height
parcel.write_u32(0); // get_frame_timestamp
parcel.write_u32(0xb00); // usage
let mut parcel_out = RawParcel::default();
relay_svc.transact_parcel(bind... | deref | identifier_name | |
main.rs | , which is exactly what we're
// doing. In theory, because we never *read* the content of
// those, I believe this is, erm, "mostly OK" ? But I should
// find a better way to deal with it.
unsafe { std::slice::from_raw_parts(&create as *con... | random_line_split | ||
main.rs |
}
impl From<megaton_hammer::error::Error> for MyError {
fn from(err: megaton_hammer::error::Error) -> MyError {
MyError::MegatonError(err)
}
}
fn main() -> std::result::Result<(), MyError> {
// Let's get ferris to show up on my switch.
println!("Initialize NV");
let nvdrv = nns::nvdrv::I... | {
MyError::ImageError(err)
} | identifier_body | |
multi.rs | storage worker. Responses from the storage worker are
//! then serialized onto the session buffer.
use super::*;
use crate::poll::Poll;
use crate::QUEUE_RETRIES;
use common::signal::Signal;
use config::WorkerConfig;
use core::marker::PhantomData;
use core::time::Duration;
use entrystore::EntryStore;
use mio::event::E... | _storage: PhantomData<Storage>,
_request: PhantomData<Request>,
_response: PhantomData<Response>,
}
impl<Storage, Parser, Request, Response> MultiWorkerBuilder<Storage, Parser, Request, Response> {
/// Create a new builder from the provided config and parser.
pub fn new<T: WorkerConfig>(config: &T,... | poll: Poll,
timeout: Duration, | random_line_split |
multi.rs | worker. Responses from the storage worker are
//! then serialized onto the session buffer.
use super::*;
use crate::poll::Poll;
use crate::QUEUE_RETRIES;
use common::signal::Signal;
use config::WorkerConfig;
use core::marker::PhantomData;
use core::time::Duration;
use entrystore::EntryStore;
use mio::event::Event;
us... |
// handle write events before read events to reduce write buffer
// growth if there is also a readable event
if event.is_writable() {
WORKER_EVENT_WRITE.increment();
self.do_write(token);
}
// read events are handled last
if event.is_readable() ... | {
WORKER_EVENT_ERROR.increment();
self.handle_error(token);
} | conditional_block |
multi.rs | worker. Responses from the storage worker are
//! then serialized onto the session buffer.
use super::*;
use crate::poll::Poll;
use crate::QUEUE_RETRIES;
use common::signal::Signal;
use config::WorkerConfig;
use core::marker::PhantomData;
use core::time::Duration;
use entrystore::EntryStore;
use mio::event::Event;
us... |
}
/// Represents a finalized request/response worker which is ready to be run.
pub struct MultiWorker<Storage, Parser, Request, Response> {
nevent: usize,
parser: Parser,
poll: Poll,
timeout: Duration,
session_queue: Queues<(), Session>,
signal_queue: Queues<(), Signal>,
_storage: PhantomD... | {
MultiWorker {
nevent: self.nevent,
parser: self.parser,
poll: self.poll,
timeout: self.timeout,
signal_queue,
_storage: PhantomData,
storage_queue,
session_queue,
}
} | identifier_body |
multi.rs | storage worker. Responses from the storage worker are
//! then serialized onto the session buffer.
use super::*;
use crate::poll::Poll;
use crate::QUEUE_RETRIES;
use common::signal::Signal;
use config::WorkerConfig;
use core::marker::PhantomData;
use core::time::Duration;
use entrystore::EntryStore;
use mio::event::E... | (&mut self, sessions: &mut Vec<TrackedItem<Session>>) {
self.session_queue.try_recv_all(sessions);
for session in sessions.drain(..).map(|v| v.into_inner()) {
let pending = session.read_pending();
trace!(
"new session: {:?} with {} bytes pending in read buffer",
... | handle_new_sessions | identifier_name |
scanner.go | used if a match is returned
AddDescription(desc ServiceDescription) string
// Scan the IPv4 network for services matching given descriptions.
// Returns a map of IPs (string encoded) pointing to the IDs of those descriptions which matched
Scan() map[string][]string
// By default, after an IP is found with Scan ... | for _, a := range addrs {
switch v := a.(type) {
case *net.IPAddr:
s.log.Warn("ipv4 scanner got a *net.IPAddr, which isn't useful and maybe shoudln't happen?", "interface", intf.Name, "*net.IPAddr", v)
case *net.IPNet:
if v.IP.DefaultMask() != nil { // ignore IPs without default mask (IPv6?)
ip ... | {
if len(s.descriptionsByID) == 0 {
s.log.Debug("scanner has no descriptions, ignoring scan")
return map[string][]string{}
}
s.log.Debug("ip4v scanner beginning scan", "interfaces", s.interfaces, "target_descriptions", s.descriptionsByID)
foundServices := make(map[string][]string)
flock := sync.Mutex{} // pro... | identifier_body |
scanner.go | used if a match is returned
AddDescription(desc ServiceDescription) string
// Scan the IPv4 network for services matching given descriptions.
// Returns a map of IPs (string encoded) pointing to the IDs of those descriptions which matched
Scan() map[string][]string
// By default, after an IP is found with Scan ... |
s.interfaces = foundInterfaces
if len(newInterfaces) > 0 {
names := make([]string, len(newInterfaces))
i := 0
for name := range newInterfaces {
names[i] = | {
names := make([]string, len(s.interfaces))
i := 0
for name := range s.interfaces {
names[i] = name
}
s.log.Warn("STUB: IPv4 interfaces have disappeared, but handling logic is unimplemented! Services on the missing interfaces may still be active", "deleted_interfaces", names)
} | conditional_block |
scanner.go | // Unlock instructs the scanner to include responses for that IP address in future scans.
Unlock(ip net.IP)
}
// A ServiceFoundNotification indicates that a service was found at ip IP which
// matched all of MatchingDescriptionIDs.
type ServiceFoundNotification struct {
IP net.IP
MatchingDescri... | func incrementIP(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]++
if ip[j] > 0 { | random_line_split | |
scanner.go | [string]net.Interface),
ilock: sync.RWMutex{},
descriptionsByID: make(map[string]ServiceDescription),
dlock: sync.RWMutex{},
activeServicesByIP: make(map[string]struct{}),
slock: &sync.RWMutex{},
log: Log.New("obj", "ipv4.scanner", "id", logext.RandId(8)),
}
err := s.refre... | FoundServices | identifier_name | |
menus.py | CAUSED AND ON ANY
## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
## $QT_END_LICENSE$
##
#############################################################... | import sys
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_()) | conditional_block | |
menus.py | , are permitted provided that the following conditions are
## met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions an... | self.infoLabel.setText("Invoked <b>Help|About Qt</b>")
def createActions(self):
self.newAct = QAction("&New", self, shortcut=QKeySequence.New,
statusTip="Create a new file", triggered=self.newFile)
self.openAct = QAction("&Open...", self, shortcut=QKeySequence.Open,
... | "The <b>Menu</b> example shows how to create menu-bar menus "
"and context menus.")
def aboutQt(self): | random_line_split |
menus.py | , are permitted provided that the following conditions are
## met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions an... | (self):
self.infoLabel.setText("Invoked <b>File|Open</b>")
def save(self):
self.infoLabel.setText("Invoked <b>File|Save</b>")
def print_(self):
self.infoLabel.setText("Invoked <b>File|Print</b>")
def undo(self):
self.infoLabel.setText("Invoked <b>Edit|Undo</b>")
... | open | identifier_name |
menus.py | , are permitted provided that the following conditions are
## met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions an... | vbox.addWidget(bottomFiller)
widget.setLayout(vbox)
self.createActions()
self.createMenus()
message = "A context menu is available by right-clicking"
self.statusBar().showMessage(message)
self.setWindowTitle("Menus")
self.setMinimumSize(160,160)
... | super(MainWindow, self).__init__()
widget = QWidget()
self.setCentralWidget(widget)
topFiller = QWidget()
topFiller.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.infoLabel = QLabel(
"<i>Choose a menu option, or right-click to invoke a context... | identifier_body |
wasm.rs | }
pub fn extra_rust_options(self) -> Vec<String> {
match self {
// Profile::Production => ["-Clto=fat", "-Ccodegen-units=1", "-Cincremental=false"]
// .into_iter()
// .map(ToString::to_string)
// .collect(),
Profile::Dev | Profile::Pr... | log_level,
uncollapsed_log_level,
wasm_size_limit: _wasm_size_limit,
system_shader_tools,
} = &inner;
// NOTE: We cannot trust locally installed version of shader tools to be correct.
// Those binaries have no reliable ... | {
let Context { octocrab: _, cache, upload_artifacts: _, repo_root } = context;
let WithDestination { inner, destination } = job;
let span = info_span!("Building WASM.",
repo = %repo_root.display(),
crate = %inner.crate_path.display(),
cargo_opts = ?inner.extr... | identifier_body |
wasm.rs | }
pub fn extra_rust_options(self) -> Vec<String> {
match self {
// Profile::Production => ["-Clto=fat", "-Ccodegen-units=1", "-Cincremental=false"]
// .into_iter()
// .map(ToString::to_string)
// .collect(),
Profile::Dev | Profile::Pr... | if !self.profile.should_check_size() {
warn!("Skipping size check because profile is '{}'.", self.profile,);
} else if self.profiling_level.unwrap_or_default() != ProfilingLevel::Objective {
// TODO? additional leeway as sanity check
warn!(
... | info!("Compressed size of {} is {}.", wasm_path.as_ref().display(), compressed_size);
if let Some(wasm_size_limit) = self.wasm_size_limit {
let wasm_size_limit = wasm_size_limit.get_appropriate_unit(true); | random_line_split |
wasm.rs | .10.1")?).await?;
let BuildInput {
crate_path,
wasm_opt_options,
skip_wasm_opt,
extra_cargo_options,
profile,
profiling_level,
log_level,
uncollapsed_log_level,
wa... | check | identifier_name | |
wasm.rs | artifacts) to wait until
// all wasm build outputs are in place, so the build won't crash.
//
// In general, much neater workaround should be possible, if we stop relying on cargo-watch
// and do the WASM watch directly in the build script.
let first_build_job = self
... | {
let mut wasm_opt_command = WasmOpt.cmd()?;
let has_custom_opt_level = wasm_opt_options.iter().any(|opt| {
wasm_opt::OptimizationLevel::from_str(opt.trim_start_matches('-')).is_ok()
});
if !has_custom_opt_level {
wasm_opt_command.apply(&pr... | conditional_block | |
server.rs | state (which can be safely lost) and persistent
/// state (which must be carefully stored and kept safe).
///
/// Currently, the `Server` API is not well defined. **We are looking for feedback and suggestions.**
pub struct Server<S, M> where S: Store, M: StateMachine {
replica: Replica<S, M>,
// Channels and S... | <S, M>(&mut self, event_loop: &mut EventLoop<Server<S, M>>, replica: &mut Replica<S,M>)
-> Result<()>
where S: Store, M: StateMachine {
// Attempt to write data.
// The `current_write` buffer will be advanced based on how much we wrote.
match self.stream.write(self.curr... | writable | identifier_name |
server.rs | state (which can be safely lost) and persistent
/// state (which must be carefully stored and kept safe).
///
/// Currently, the `Server` API is not well defined. **We are looking for feedback and suggestions.**
pub struct Server<S, M> where S: Store, M: StateMachine {
replica: Replica<S, M>,
// Channels and S... | -> Result<()>
where S: Store, M: StateMachine {
let mut read = 0;
match self.stream.read(self.current_read.get_mut()) {
Ok(Some(r)) => {
// Just read `r` bytes.
read = r;
},
Ok(None) => panic!("We just got read... | fn readable<S, M>(&mut self, event_loop: &mut EventLoop<Server<S, M>>, replica: &mut Replica<S,M>) | random_line_split |
server.rs | Handler for Server<S, M> where S: Store, M: StateMachine {
type Message = RingBuf;
type Timeout = Token;
/// A registered IoHandle has available writing space.
fn writable(&mut self, reactor: &mut EventLoop<Server<S, M>>, token: Token) {
debug!("Writeable");
match token {
... | {
// Won an election!
self.broadcast(builder_message);
} | conditional_block | |
group.rs | 't contain central inversion.
fn quaternions(self, left: bool) -> Box<dyn GroupIter> {
if self.dim != 3 {
panic!("Quaternions can only be generated from 3D matrices.");
}
Box::new(
self.rotations()
.map(move |el| quat_to_mat(mat_to_quat(el), left)),
... |
/// Generates the trivial group of a certain dimension.
pub fn trivial(dim: usize) -> Self {
Self {
dim,
iter: Box::new(std::iter::once(Matrix::identity(dim, dim))),
}
}
/// Generates the group with the identity and a central inversion of a
/// certain dime... | {
let dim = self.dim;
Self {
dim,
iter: Box::new(self.map(move |x| {
let msg = "Size of matrix does not match expected dimension.";
assert_eq!(x.nrows(), dim, "{}", msg);
assert_eq!(x.ncols(), dim, "{}", msg);
x
... | identifier_body |
group.rs | mat1 * mat2))
}
/// Calculates the direct product of two groups. Pairs of matrices are then
/// mapped to their direct sum.
pub fn direct_product(g: Self, h: Self) -> Self {
let dim = g.dim + h.dim;
Self::fn_product(g, h, dim, |(mat1, mat2)| direct_sum(mat1, mat2))
}
/// Gene... | random_line_split | ||
group.rs | don't contain central inversion.
fn | (self, left: bool) -> Box<dyn GroupIter> {
if self.dim != 3 {
panic!("Quaternions can only be generated from 3D matrices.");
}
Box::new(
self.rotations()
.map(move |el| quat_to_mat(mat_to_quat(el), left)),
)
}
/// Returns the swirl symmet... | quaternions | identifier_name |
connection.py | API."""
def __init__(
self,
websession: aiohttp.ClientSession,
username,
password,
device_id,
device_name,
country,
) -> None:
"""
Initialize connection object.
Args:
websession (aiohttp.ClientSession): An instance of... | self._current_vin = None
return True
if js_resp.get("errorCode"):
_LOGGER.debug(pprint.pformat(js_resp))
error = js_resp.get("errorCode")
if error == API_ERROR_INVALID_ACCOUNT:
_LOGGER.error("Invalid account"... | """Authenticate to Subaru Remote Services API."""
if self._username and self._password and self._device_id:
post_data = {
"env": "cloudprod",
"loginUsername": self._username,
"password": self._password,
"deviceId": self._device_id,
... | identifier_body |
connection.py | API."""
def __init__(
self,
websession: aiohttp.ClientSession,
username,
password,
device_id,
device_name,
country,
) -> None:
"""
Initialize connection object.
Args:
websession (aiohttp.ClientSession): An instance of... |
async def _authenticate(self, vin=None) -> bool:
"""Authenticate to Subaru Remote Services API."""
if self._username and self._password and self._device_id:
post_data = {
"env": "cloudprod",
"loginUsername": self._username,
"password": se... | return await self.__open(url, method=POST, headers=self._head, params=params, json_data=json_data) | conditional_block |
connection.py | API."""
def __init__(
self,
websession: aiohttp.ClientSession,
username,
password,
device_id,
device_name,
country,
) -> None:
"""
Initialize connection object.
Args:
websession (aiohttp.ClientSession): An instance of... | (self):
"""Clear session cookies."""
self._websession.cookie_jar.clear()
async def get(self, url, params=None):
"""
Send HTTPS GET request to Subaru Remote Services API.
Args:
url (str): URL path that will be concatenated after `subarulink.const.MOBILE_API_BASE_... | reset_session | identifier_name |
connection.py | app API."""
def __init__(
self,
websession: aiohttp.ClientSession,
username,
password,
device_id,
device_name,
country,
) -> None:
"""
Initialize connection object.
Args:
websession (aiohttp.ClientSession): An instanc... | self._registered = False
self._current_vin = None
self._list_of_vins = []
self._session_login_time = None
self._auth_contact_options = None
async def connect(self):
"""
Connect to and establish session with Subaru Starlink mobile app API.
Returns:
... | "Accept": "*/*",
}
self._websession = websession
self._authenticated = False | random_line_split |
main.go | os.Lstat(workdir)
if err != nil {
log.Fatalf("workdir error: %s", err)
}
dbCertificate, dbCaCertPool := loadCerts(
cfg.MySQL.CertificatePath,
cfg.MySQL.PrivateKeyPath,
cfg.MySQL.PrivateKeyPassphrase,
cfg.MySQL.CACertificatePath,
)
dbURI := db.NewDSN(
cfg.MySQL.Username,
cfg.MySQL.Password,
cfg.M... | keepAliveDial | identifier_name | |
main.go | "github.com/tedsuo/ifrit/sigmon"
"cred-alert/config"
"cred-alert/crypto"
"cred-alert/db"
"cred-alert/db/migrations"
"cred-alert/gitclient"
"cred-alert/metrics"
"cred-alert/notifications"
"cred-alert/queue"
"cred-alert/revok"
"cred-alert/revok/api"
"cred-alert/revok/stats"
"cred-alert/revokpb"
"cred-alert/... |
bs, err := ioutil.ReadFile(string(flagOpts.ConfigFile))
if err != nil {
logger.Error("failed-to-open-config-file", err)
os.Exit(1)
}
cfg, err = config.LoadWorkerConfig(bs)
if err != nil {
logger.Error("failed-to-load-config-file", err)
os.Exit(1)
}
errs := cfg.Validate()
if errs != nil {
for _, er... | {
os.Exit(1)
} | conditional_block |
main.go | "github.com/tedsuo/ifrit/sigmon"
"cred-alert/config"
"cred-alert/crypto"
"cred-alert/db"
"cred-alert/db/migrations"
"cred-alert/gitclient"
"cred-alert/metrics"
"cred-alert/notifications"
"cred-alert/queue"
"cred-alert/revok"
"cred-alert/revok/api"
"cred-alert/revok/stats"
"cred-alert/revokpb"
"cred-alert/... |
cfg, err = config.LoadWorkerConfig(bs)
if err != nil {
logger.Error("failed-to-load-config-file", err)
os.Exit(1)
}
errs := cfg.Validate()
if errs != nil {
for _, err := range errs {
fmt.Println(err.Error())
}
os.Exit(1)
}
if cfg.Metrics.SentryDSN != "" {
logger.RegisterSink(revok.NewSentrySink... | {
var cfg *config.WorkerConfig
var flagOpts config.WorkerOpts
var ghClient *revok.GitHubClient
logger := lager.NewLogger("revok-worker")
logger.RegisterSink(lager.NewWriterSink(os.Stdout, lager.DEBUG))
logger.Info("starting")
_, err := flags.Parse(&flagOpts)
if err != nil {
os.Exit(1)
}
bs, err := iouti... | identifier_body |
main.go | "cred-alert/db"
"cred-alert/db/migrations"
"cred-alert/gitclient"
"cred-alert/metrics"
"cred-alert/notifications"
"cred-alert/queue"
"cred-alert/revok"
"cred-alert/revok/api"
"cred-alert/revok/stats"
"cred-alert/revokpb"
"cred-alert/search"
"cred-alert/sniff"
"rolodex/rolodexpb"
)
var info = admin.Service... | random_line_split | ||
task.rs | currently running, but has been notified that it must run again.
Notified,
/// Task has been scheduled
Scheduled,
/// Task is complete
Complete,
}
// ===== impl Task =====
impl Task {
/// Create a new task handle
pub fn new(future: BoxFuture) -> Task {
let task_fut = TaskFuture::F... | (&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Task")
.field("inner", self.inner())
.finish()
}
}
impl Clone for Task {
fn clone(&self) -> Task {
use std::isize;
const MAX_REFCOUNT: usize = (isize::MAX) as usize;
// Using a relaxed ... | fmt | identifier_name |
task.rs | drop(&mut self) {
// This drops the future
if self.1 {
let _ = self.0.take();
}
}
}
let mut g = Guard(fut, true);
let ret = g.0.as_mut().unwrap()
.poll(unpark, self.... | {
State::Idle
} | identifier_body | |
task.rs | currently running, but has been notified that it must run again.
Notified,
/// Task has been scheduled
Scheduled,
/// Task is complete
Complete,
}
// ===== impl Task =====
impl Task {
/// Create a new task handle
pub fn new(future: BoxFuture) -> Task {
let task_fut = TaskFuture::F... |
impl Inner {
fn stub() -> Inner {
Inner {
next: AtomicPtr::new(ptr::null_mut()),
state: AtomicUsize::new(State::stub().into()),
ref_count: AtomicUsize::new(0),
future: Some(TaskFuture |
// ===== impl Inner ===== | random_line_split |
process_test.py | az) * np.sin(az) * np.cos(elev))
G = sum(np.sin(az) * np.sin(elev))
D = sum(vel * np.cos(az))
E = sum(np.sin(az) * np.cos(az) * np.cos(elev))
F = sum(np.cos(az) ** 2 * np.cos(elev))
H = sum(np.cos(az) * np.sin(elev))
W = sum(vel)
X = sum(np.sin(az) * np.cos(elev... |
hgt_var[:] = hgt
time_var[:] = [(d - datetime(1970, 1, 1)).total_seconds() for d in date]
w_var[:, :] = w
intensity_var[:] = intensity
# Close the netcdf
nc.close()
def writeRHI_to_nc(filename, date, vel, rng, elev, az, intensity,up_flag):
if os.path.exists(filename):
# open th... | logging.debug(filename)
logging.debug(date)
# Create the netcdf
nc = netCDF4.Dataset(filename, 'w', format="NETCDF4")
# Create the height dimension
nc.createDimension('hgt', len(hgt))
nc.createDimension('t', None)
# Add the attributes
nc.setncattr("date", date[0].isoformat())
# C... | identifier_body |
process_test.py | attr('units', 'seconds since 1970-01-01 00:00:00 UTC')
hgt_var[:] = hgt
time_var[:] = [(d - datetime(1970, 1, 1)).total_seconds() for d in date]
w_var[:, :] = w
intensity_var[:] = intensity
# Close the netcdf
nc.close()
def writeRHI_to_nc(filename, date, vel, rng, elev, az, intensity,up_fla... | lines.append(line) | conditional_block | |
process_test.py | scans - always do the stare
# TB - I changed some things here so only the scans from the current hour are even looked at.
# - This cuts down on processing for the stare files!
path_raw = now.strftime('/Users/elizabethsmith/TORUS_DL/data/raw/dl/%Y/%Y%m/%Y%m%d/*%Y%m%d_*.hpl')
#print path_raw
raw_files = [f for f in g... | writeRHI_to_nc(filename, times, vel.transpose(), rng, elev, az, intensity.transpose(), up_flag) | random_line_split | |
process_test.py | az) * np.sin(az) * np.cos(elev))
G = sum(np.sin(az) * np.sin(elev))
D = sum(vel * np.cos(az))
E = sum(np.sin(az) * np.cos(az) * np.cos(elev))
F = sum(np.cos(az) ** 2 * np.cos(elev))
H = sum(np.cos(az) * np.sin(elev))
W = sum(vel)
X = sum(np.sin(az) * np.cos(elev... | (header):
"""
Takes in a list of lines from the raw hpl file. Separates them by
tab and removes unnecessary text
"""
new_header = {}
for item in header:
split = item.split('\t')
new_header[split[0].replace(':', '')] = split[1].replace("\r\n", "")
return new_header
def _to... | decode_header | identifier_name |
sender.go | Logic
type metricPair struct {
attributes pcommon.Map
metric pmetric.Metric
}
type sender struct {
logBuffer []plog.LogRecord
metricBuffer []metricPair
config *Config
client *http.Client
filter filter
sources sourceFormats
compressor ... |
// Add headers
switch s.config.CompressEncoding {
case GZIPCompression:
req.Header.Set(headerContentEncoding, contentEncodingGzip)
case DeflateCompression:
req.Header.Set(headerContentEncoding, contentEncodingDeflate)
case NoCompression:
default:
return fmt.Errorf("invalid content encoding: %s", s.config.... | {
return err
} | conditional_block |
sender.go | Logic
type metricPair struct {
attributes pcommon.Map
metric pmetric.Metric
}
type sender struct {
logBuffer []plog.LogRecord
metricBuffer []metricPair
config *Config
client *http.Client
filter filter
sources sourceFormats
compressor ... | (record plog.LogRecord) string {
return record.Body().AsString()
}
// logToJSON converts LogRecord to a json line, returns it and error eventually
func (s *sender) logToJSON(record plog.LogRecord) (string, error) {
data := s.filter.filterOut(record.Attributes())
record.Body().CopyTo(data.orig.PutEmpty(logKey))
ne... | logToText | identifier_name |
sender.go | o Logic
type metricPair struct {
attributes pcommon.Map
metric pmetric.Metric
}
type sender struct {
logBuffer []plog.LogRecord
metricBuffer []metricPair
config *Config
client *http.Client
filter filter
sources sourceFormats
compressor ... | func (s *sender) sendMetrics(ctx context.Context, flds fields) ([]metricPair, error) {
var (
body strings.Builder
errs error
droppedRecords []metricPair
currentRecords []metricPair
)
for _, record := range s.metricBuffer {
var formattedLine string
var err error
switch s.config.Met... |
return droppedRecords, errs
}
// sendMetrics sends metrics in right format basing on the s.config.MetricFormat | random_line_split |
sender.go | BufferSize defines size of the logBuffer (maximum number of plog.LogRecord entries)
maxBufferSize int = 1024 * 1024
headerContentType string = "Content-Type"
headerContentEncoding string = "Content-Encoding"
headerClient string = "X-Sumo-Client"
headerHost string = "X-Sumo-Host"
headerNam... | {
s.logBuffer = (s.logBuffer)[:0]
} | identifier_body | |
marketplace.js | (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function filterSearch() {
var fs = {};
fs.CompanyName = '';
fs.Products = [];
fs.ProductCategories = []
fs.ProducingCountries = [];
fs.ProducingRegions = [];
fs.StandardsCertified = []
fs.StandardsAssessed = [];
fs.Compliance = ... | isNumber | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.