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 |
|---|---|---|---|---|
elasticsearch_adapter.js | (config) {
if (typeof config !== 'object' || Object.keys(config).length === 0) {
throw new NexxusError(NexxusError.errors.ServerFailure, ['supplied empty or invalid configuration parameter']);
}
let esConfig = {
maxRetries: 10,
deadTimeout: 1e4,
pingTimeout: 3000,
keepAlive: true,
maxSockets: ... | constructor | identifier_name | |
elasticsearch_adapter.js | field])}.*`;
});
child[translationMappings[replaced]] = fieldObj;
delete child[replaced];
} else if (translationMappings[replaced] !== replaced) {
child[translationMappings[replaced]] = cloneObject(child[replaced]);
delete child[replaced];
}
}
}
});
}
Tran... | random_line_split | ||
index.js | = {};
static ctrl = null;
static lane1 = [];
static lane2 = [];
static crossing = 0;
static ui = {};
static creatorInterval = null;
static start() {
// if (Sim.ui.$sim === undefined) Sim.resetUI();
Sim.clearErrors();
Sim.loadUserInputs();
Sim.ui.$fieldset.disabled = true;
Sim.ctr... | (x) {
await this.sleep(0);
await x.acquire(this);
}
async v(x) {
await this.sleep(0);
await x.release(this);
}
async sleep(secs) {
return new Promise((resolve, _reject) => {
setTimeout(resolve, secs * 1000);
});
}
/**
* A vehicle's place in line is determined by a vector ... | p | identifier_name |
index.js | {};
static ctrl = null;
static lane1 = [];
static lane2 = [];
static crossing = 0;
static ui = {};
static creatorInterval = null;
static start() {
// if (Sim.ui.$sim === undefined) Sim.resetUI();
Sim.clearErrors();
Sim.loadUserInputs();
Sim.ui.$fieldset.disabled = true;
Sim.ctrl ... |
/**
* Update Traverser
*
* @param {Traverser} t
* @param {number} i - index
*/
static redrawTraverser(t, i) {
t.$elem.style.setProperty('--pos', i);
t.$elem.title =
`${t.name}\n\n` +
`orderVec: {${t.orderVec.join(', ')}}\n` +
`waitVec: {${t.getWaitVec().join(', ')}}`;
... | {
// Just update 'data-*' and '--pos' values, and let CSS take care of the rest.
// Traffic light
const {ui, ctrl, userVars} = Sim;
ui.$sim.dataset.light = userVars.light;
ui.$sim.dataset.ctrlQueued = ctrl.orderVec.some(sema => userVars[sema].getPosition(ctrl) > 0);
// Lanes
const {lane1, ... | identifier_body |
index.js |
}
}
class Sim {
static userVars = {};
static userAlgos = {};
static ctrl = null;
static lane1 = [];
static lane2 = [];
static crossing = 0;
static ui = {};
static creatorInterval = null;
static start() {
// if (Sim.ui.$sim === undefined) Sim.resetUI();
Sim.clearErrors();
Sim.lo... | {
const entry = this._queue.shift();
if (entry) {
this._permits--;
entry.resolve();
}
} | conditional_block | |
index.js | constructor(permits) {
this._permits = permits;
this._queue = [];
}
getPosition(acquirer) {
const idx = this._queue.findIndex(entry => entry.acquirer === acquirer);
return idx + 1; // to get rid of '-1'
}
async acquire(acquirer) {
return new Promise( (resolve, reject) => {
this._qu... | * A basic Promise-based and queue-based Semaphore
*/
const Semaphore = class SillySemaphore {
| random_line_split | |
NeuralNetworks.py | = calculate_predictions(test_data,test_y, widths, activations, weights)
test_error = calculate_error(test_y, test_predictions)
errors.append([width, train_error, test_error])
print(width, " COMPLETE")
for error in errors:
print("Width:", error[0], ", Train Error:", error[1], ", T... |
def calculate_predictions(data, y, widths, activations, weights):
predictions = copy.deepcopy(y)
for i in range(len(data)):
predictions[i] = np.sign(run_forward_pass(weights, data[i], widths, activations)[-1])
return predictions
def calculate_error(y, predictions):
return 1 - np.count_nonze... | widths = [5, 5, 5, 1]
weights = run_sgd(gamma, d, widths, activations, deriv_activations, zeros)
predictions = calculate_predictions(train_data, train_y, widths, activations, weights)
error = calculate_error(train_y, predictions)
print("GAMMA:", gamma, " D:", d, " ERROR:", error)
if error < smalle... | identifier_body |
NeuralNetworks.py | = calculate_predictions(test_data,test_y, widths, activations, weights)
test_error = calculate_error(test_y, test_predictions)
errors.append([width, train_error, test_error])
print(width, " COMPLETE")
for error in errors:
print("Width:", error[0], ", Train Error:", error[1], ", T... |
return smallest
def get_smallest_error(smallest, gamma, d, activations, deriv_activations, zeros):
# Computes the error for the given parameters and returns the error if it is the smallest, or the previous smallest.
widths = [5, 5, 5, 1]
weights = run_sgd(gamma, d, widths, activations, deriv_activati... | for d in ds: smallest = get_smallest_error(smallest, gamma, d, activations, deriv_activations, zeros)
print("----------------------") | conditional_block |
NeuralNetworks.py | = calculate_predictions(test_data,test_y, widths, activations, weights)
test_error = calculate_error(test_y, test_predictions)
errors.append([width, train_error, test_error])
print(width, " COMPLETE")
for error in errors:
print("Width:", error[0], ", Train Error:", error[1], ", T... | (weights, curr_nodes, prev_node_derivs, is_last_level):
curr_node_derivs = np.zeros(curr_nodes.shape)
for i in range(len(curr_nodes)):
product = 0
for j in range(len(weights[i])):
k = j
if not is_last_level: k += 1
product += weights[i][j] * prev_node_derivs... | compute_node_derivatives | identifier_name |
NeuralNetworks.py | = calculate_predictions(test_data,test_y, widths, activations, weights)
test_error = calculate_error(test_y, test_predictions)
errors.append([width, train_error, test_error])
print(width, " COMPLETE")
for error in errors:
print("Width:", error[0], ", Train Error:", error[1], ", T... | loss = []
for epoch in range(100):
learning_rate = update_learning_rate(initial_gamma, d, epoch)
[y, x] = shuffle_data(train_y, train_data)
l = 0
for i in range(n):
nodes = run_forward_pass(weights, x[i], widths, activations)
prediction = np.sign(nodes[-1... |
def run_sgd(initial_gamma, d, widths, activations, deriv_activations, zeros, n=872):
weights = create_weights(widths, zeros) | random_line_split |
updateTotalCompany.js | 03_009,RE9003_010 from [dbo].[tRE9003] where flag<> 1';
let res = await Mssql.connect(config.mssql_rate).query(sql);
let setRateConvertCost = Date.now() - now;
let rows = res.recordset;
let fetched = rows.length; //每次查询SQL Server的实际记录数
if (fetched > ... | (value == undefined) {
console.log('can not get the currencyRate value');
logger.info('can not get the currencyRate value');
return ({});
} else {
res = value;
console.log('the currencyRate value: ... | if | identifier_name |
updateTotalCompany.js | 03_009,RE9003_010 from [dbo].[tRE9003] where flag<> 1';
let res = await Mssql.connect(config.mssql_rate).query(sql);
let setRateConvertCost = Date.now() - now;
let rows = res.recordset;
let fetched = rows.length; //每次查询SQL Server的实际记录数
if (fetched > ... | i].CR0001_005; //注册资金,未换算的值
let currencyUnit = rows[i].CR0001_006; //货币类型
let | tra = 0;
}
let fund = rows[ | conditional_block |
updateTotalCompany.js | 03_009,RE9003_010 from [dbo].[tRE9003] where flag<> 1';
let res = await Mssql.connect(config.mssql_rate).query(sql);
let setRateConvertCost = Date.now() - now;
let rows = res.recordset;
let fetched = rows.length; //每次查询SQL Server的实际记录数
if (fetched > ... | function judgeCurrencyFlag(currencyFlag) {
let rateFlag = 'RMB';
if (currencyFlag == 840) rateFlag = 'MY';
else if (currencyFlag == 954) rateFlag = 'OY';
else if (currencyFlag == 392) rateFlag = 'RY';
else if (currencyFlag == 344
) rateFlag = 'GY';
else if (currencyFlag == 826) rateFlag = ... | alue == undefined) {
console.log('can not get the currencyRate value');
logger.info('can not get the currencyRate value');
return ({});
} else {
res = value;
console.log('the currencyRate value: ' +... | identifier_body |
updateTotalCompany.js | 03_009,RE9003_010 from [dbo].[tRE9003] where flag<> 1';
let res = await Mssql.connect(config.mssql_rate).query(sql);
let setRateConvertCost = Date.now() - now;
let rows = res.recordset;
let fetched = rows.length; //每次查询SQL Server的实际记录数
if (fetched > ... | do {
let rows = [];
let now = Date.now();
let sql = `
select top 10000 cast(tmstamp as bigint) as _ts, ITCode2,CR0001_005,CR0001_006,CR0001_040,CR0001_041 from [tCR0001_V2.0] WITH(READPAST)
... | random_line_split | |
words.go | pector",
"king",
"ladder",
"menu",
"penalty",
"piano",
"potato",
"profession",
"professor",
"quantity",
"reaction",
"requirement",
"salad",
"sister",
"supermarket",
"tongue",
"weakness",
"wedding",
"affair",
"ambition",
"analyst",
"apple",
"assignment",
"assistant",
"bath... | "spirit",
"street",
"tree",
"wave", | random_line_split | |
words.go | () string {
abuff := []string{}
total := 0
words := 0
for {
w := ranWord()
words += 1
total += len(w)
abuff = append(abuff, w)
if total >= 40 && words > 4 {
break
}
}
buff := ""
for _, x := range abuff {
first := x[0:1]
last := x[1:len(x)]
first = strings.ToUpper(first)
buff += first + la... | BigWords | identifier_name | |
words.go | "reading",
"method",
"data",
"food",
"understanding",
"theory",
"law",
"bird",
"literature",
"problem",
"software",
"control",
"knowledge",
"power",
"ability",
"economics",
"love",
"internet",
"television",
"science",
"library",
"nature",
"fact",
"product",
"idea",
"t... | {
list := []string{
"people",
"history",
"way",
"art",
"world",
"information",
"map",
"two",
"family",
"government",
"health",
"system",
"computer",
"meat",
"year",
"thanks",
"music",
"person", | identifier_body | |
words.go |
return buff
}
func ranWord() string {
list := []string{
"people",
"history",
"way",
"art",
"world",
"information",
"map",
"two",
"family",
"government",
"health",
"system",
"computer",
"meat",
"year",
"thanks",
"music",
"person",
"reading",
"method",
"data",
"food",
"un... | {
first := x[0:1]
last := x[1:len(x)]
first = strings.ToUpper(first)
buff += first + last
} | conditional_block | |
codec.py | i))) for i in range(0, levels + 1)]
return shapes
def wavelet_decoded_length(min_shape, max_shape):
shapes = wavelet_decoded_subbands_shapes(min_shape, max_shape)
length = functools.reduce(lambda agg, s: agg + (3 * (s[0] * s[1])), shapes, 0)
length += (min_shape[0] * min_shape[1])
return length
... | ac_mat_fun | identifier_name | |
codec.py |
utils.debug_msg("Going to determine RLE for %d size array" % len(arr))
rl = functools.reduce(reduction, arr, [{"zeros": 0}])
utils.debug_msg("%d long RLE created" % len(rl))
# If the last element has no value then it was 0! That is a special tuple, (0,0)
if "value" not in rl[-1]:
rl[-1] = {... |
return arr
def wavelet_encode(compressed: model.CompressedImage):
"""
In brief reading of literature, Huffman coding is still considered for wavelet image compression. There are other
more effective (and complicated schemes) that I think are out of scope of this project which is just to introduce
... | fill = length - len(arr)
arr += ([0] * fill) | conditional_block |
codec.py | l = code["zeros"]
div = l // max_len
full = {
"zeros": max_len - 1, # minus 1 because we get another for free from the value
"value": 0
}
return ([full] * div) + [{
"zeros": l - (div * max_len),
"value": code["value"]
}]
... | """
Come up with the run length encoding for a matrix
"""
def _break_up_rle(code, max_len): | random_line_split | |
codec.py |
utils.debug_msg("Going to determine RLE for %d size array" % len(arr))
rl = functools.reduce(reduction, arr, [{"zeros": 0}])
utils.debug_msg("%d long RLE created" % len(rl))
# If the last element has no value then it was 0! That is a special tuple, (0,0)
if "value" not in rl[-1]:
rl[-1] = {... |
def wavelet_decoded_subbands_shapes(min_shape, max_shape):
"""
We just do Haar or Daubechie, assume power of 2
"""
levels = int(np.sqrt(max_shape[0] // min_shape[0]))
shapes = [(min_shape[0] * (np.power(2, i)), min_shape[1] * (np.power(2, i))) for i in range(0, levels + 1)]
return shapes
d... | offset = utils.size(shapes[0])
subbands = [transform.izigzag(np.array(data[:offset]), shapes[0])]
for i in range(len(shapes)):
subbands.append(transform.izigzag(np.array(data[offset:offset + utils.size(shapes[i])]), shapes[i]))
offset += utils.size(shapes[i])
subbands.append(transform.... | identifier_body |
mailbox.rs | send,
namespace_filter,
)?;
link_async2_if_match(
linker,
"lunatic::message",
"prepare_receive",
FuncType::new([ValType::I32, ValType::I32], [ValType::I32]),
prepare_receive,
namespace_filter,
)?;
link_if_match(
linker,
"lun... |
//% lunatic::message::prepare_receive(i32_data_size_ptr: i32, i32_res_size_ptr: i32) -> i32
//%
//% Returns:
//% * 0 if it's a regular message.
//% * 1 if it's a signal turned into a message.
//%
//% For regular messages both parameters are used.
//% * **i32_data_size_ptr** - Location to write the message buffer size... | {
let message = caller
.data_mut()
.message
.take()
.or_trap("lunatic::message::send")?;
let process = caller
.data()
.resources
.processes
.get(process_id)
.or_trap("lunatic::message::send")?;
let result = match process.send_message(me... | identifier_body |
mailbox.rs | send,
namespace_filter,
)?;
link_async2_if_match(
linker,
"lunatic::message",
"prepare_receive",
FuncType::new([ValType::I32, ValType::I32], [ValType::I32]),
prepare_receive,
namespace_filter,
)?;
link_if_match(
linker,
"lun... | //% The process of sending them around needs to be explicit.
//%
//% This API was designed around the idea that most guest languages will use some serialization
//% library and turning resources into indexes is a way of serializing. The same is true for
//% deserializing them on the receiving side, when an index needs ... | //% received message into the same structure.
//%
//% This can be a bit confusing, because resources are just IDs (u64 values) themself. But we
//% still need to serialize them into different u64 values. Resources are inherently bound to a
//% process and you can't access another resource just by guessing an ID from an... | random_line_split |
mailbox.rs | _filter,
)?;
link_async2_if_match(
linker,
"lunatic::message",
"prepare_receive",
FuncType::new([ValType::I32, ValType::I32], [ValType::I32]),
prepare_receive,
namespace_filter,
)?;
link_if_match(
linker,
"lunatic::message",
"receiv... | prepare_receive | identifier_name | |
string.rs | _sub(self.opener.len() + self.line_end.len() + 1)?
+ 1,
)
}
/// Like max_chars_with_indent but the indentation is not substracted.
/// This allows to fit more graphemes from the string on a line when
/// SnippetState::Overflow.
fn max_chars_without_indent(&self) -> Option<us... | nothing_to_break | identifier_name | |
string.rs | .opener);
// Snip a line at a time from `stripped_str` until it is used up. Push the snippet
// onto result.
let mut cur_max_chars = max_chars_with_indent;
loop {
// All the input starting at cur_start fits on the current line
if graphemes.len() - cur_start <= cur_max_chars {
... | {
let string = "Neque in sem. \n Pellentesque tellus augue.";
let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
assert_eq!(
break_string(15, false, &graphemes[..]),
SnippetState::Overflow("Neque in sem. \n".to_string(),... | identifier_body | |
string.rs | a> {
StringFormat {
opener: "\"",
closer: "\"",
line_start: " ",
line_end: "\\",
shape,
trim_end: false,
config,
}
}
/// Returns the maximum number of graphemes that is possible on a line while taking the
//... | /// Like max_chars_with_indent but the indentation is not substracted.
/// This allows to fit more graphemes from the string on a line when
/// SnippetState::Overflow.
fn max_chars_without_indent(&self) -> Option<usize> {
Some(self.config.max_width().checked_sub(self.line_end.len())?)
}
}
p... | .checked_sub(self.opener.len() + self.line_end.len() + 1)?
+ 1,
)
}
| random_line_split |
server.rs | = async move {
let incoming = match config.bind.protocol {
Protocol::Udp => {
let server = udp::Server::bind(&addr).await?.build(receive);
Either::Left(server)
}
Protocol::Tcp => {
let server = tcp::Server::bind(&addr).await?.... | new | identifier_name | |
server.rs | (self) -> Result<(), Error> {
// Run the server on a fresh runtime
// We attempt to shut this runtime down cleanly to release
// any used resources
let runtime = Runtime::new().expect("failed to start new Runtime");
runtime.block_on(self.fut);
runtime.shutdown_now();
... |
}
struct Decode<F>(F);
impl<F> Decoder for Decode<F>
where
F: FnMut(Bytes) -> Result<Option<Message>, Error> + Unpin,
{
type Item = Received;
type Error = Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
// A... | {
emit("Setting up for UDP");
UdpFramed::new(self.0, Decode(receive)).map(|r| r.map(|(msg, _)| msg))
} | identifier_body |
server.rs | run(self) -> Result<(), Error> {
// Run the server on a fresh runtime
// We attempt to shut this runtime down cleanly to release
// any used resources
let runtime = Runtime::new().expect("failed to start new Runtime");
runtime.block_on(self.fut);
runtime.shutdown_now();... | match process(msg) {
Ok(()) => {
increment!(server.process_ok);
}
Err(err) => {
increment!(server.process_err);
emit... | Some(Ok(Received::Complete(msg))) => {
increment!(server.receive_ok);
// Process the received message | random_line_split |
remote.rs | io::copy(&mut incoming_r, &mut control_w);
match futures::future::join(join_1, join_2).await {
(Ok(_), Ok(_)) => {}
(Err(error), _) | (_, Err(error)) => {
tracing::error!(?error, "directing stream to control failed");
}
}
}
#[tracing::instrument(skip(socket))]
pub async fn ... | error!("failed to read from tcp socket: {:?}", e);
return;
}
};
if n == 0 {
debug!("stream ended");
let _ = tunnel_stream
.client
.tx
.send(ControlPacket::End(tunnel_stream.id.clone()))
... | {
// send initial control stream init to client
control_server::send_client_stream_init(tunnel_stream.clone()).await;
// now read from stream and forward to clients
let mut buf = [0; 1024];
loop {
// client is no longer connected
if Connections::get(&tunnel_stream.client.id).is_non... | identifier_body |
remote.rs | io::copy(&mut incoming_r, &mut control_w);
match futures::future::join(join_1, join_2).await {
(Ok(_), Ok(_)) => {}
(Err(error), _) | (_, Err(error)) => {
tracing::error!(?error, "directing stream to control failed");
}
}
}
#[tracing::instrument(skip(socket))]
pub async fn ... | // look for a host header
if let Some(Ok(host)) = req
.headers
.iter()
.filter(|h| h.name.to_lowercase() == "host".to_string())
.map(|h| std::str::from_utf8(h.value))
.next()
{
tracing::info!(host=%host, path=%req.path.unwrap_or_default(), "peek request");
... | String::default()
};
| random_line_split |
remote.rs | io::copy(&mut incoming_r, &mut control_w);
match futures::future::join(join_1, join_2).await {
(Ok(_), Ok(_)) => {}
(Err(error), _) | (_, Err(error)) => {
tracing::error!(?error, "directing stream to control failed");
}
}
}
#[tracing::instrument(skip(socket))]
pub async fn ... | (mut tunnel_stream: ActiveStream, mut tcp_stream: ReadHalf<TcpStream>) {
// send initial control stream init to client
control_server::send_client_stream_init(tunnel_stream.clone()).await;
// now read from stream and forward to clients
let mut buf = [0; 1024];
loop {
// client is no longer... | process_tcp_stream | identifier_name |
file-record.ts | DummyFile {
name: string;
size: number;
type: string;
lastModified: number;
lastModifiedDate: Date;
}
interface UploadData {
data: any;
error: string | false;
}
export { Dimensions, Options, RawFileRecord };
class FileRecord {
public static getFromRaw(
rawFileRecord: RawFileRecord,
options: ... | (resized: ImageThumbnail | | imageResized | identifier_name |
file-record.ts | DummyFile {
name: string;
size: number;
type: string;
lastModified: number;
lastModifiedDate: Date;
}
interface UploadData {
data: any;
error: string | false;
}
export { Dimensions, Options, RawFileRecord };
class FileRecord {
public static getFromRaw(
rawFileRecord: RawFileRecord,
options: ... |
public isPlayableVideo(): boolean {
return this.icon().category === 'video-playable';
}
public isAudio(): boolean {
return this.file && this.file.type.indexOf('audio') !== -1;
}
public isPlayableAudio(): boolean {
return this.icon().category === 'audio-playable';
}
public isText(): boolean... | }
public isVideo(): boolean {
return this.file && this.file.type.indexOf('video') !== -1;
} | random_line_split |
file-record.ts | File {
name: string;
size: number;
type: string;
lastModified: number;
lastModifiedDate: Date;
}
interface UploadData {
data: any;
error: string | false;
}
export { Dimensions, Options, RawFileRecord };
class FileRecord {
public static getFromRaw(
rawFileRecord: RawFileRecord,
options: Option... |
public imageResized(resized: ImageThumbnail | | {
this.urlValue = url;
return new Promise((resolve, reject) => {
if (this.isImage()) {
this.resizeImage().then(
() => {
resolve(this);
},
(err) => {
resolve(this);
}
);
return;
}
resolve(this);
});
} | identifier_body |
file-record.ts | File {
name: string;
size: number;
type: string;
lastModified: number;
lastModifiedDate: Date;
}
interface UploadData {
data: any;
error: string | false;
}
export { Dimensions, Options, RawFileRecord };
class FileRecord {
public static getFromRaw(
rawFileRecord: RawFileRecord,
options: Option... |
return this.progressInternal || 0;
}
public url(value?: string): string | undefined | Promise<this> {
if (value !== undefined) {
return this.setUrl(value);
}
return this.urlValue || undefined;
}
public src(): string {
if (this.isImage()) {
return this.urlResized || this.urlVal... | {
this.progressInternal = value;
return;
} | conditional_block |
script.js | Def.filter.maskBits = 9;*/
break;
case "polygon":
this.fixtureDef.shape = new b2PolygonShape();
this.fixtureDef.shape.SetAsArray(details.points,details.points.length);
break;
case "block":
default:
details.width = details.width || this.defaults.width;
details.height = details.height || ... | {
var x, y;
var counter = 0;
// 100 iterations
var increase = Math.PI * 2 / 100;
for (var i = 25; i <= 15000; i +=6 ) {
x = i;
y = Math.sin(counter) / 2 + 18;
counter += increase * i;
var coin = new Body(physics, { shape: 'circle2', image: coins.img[Math.floor(Math.random()*coins.img.length)], ty... | identifier_body | |
script.js | obj.GetNext();
}
this.context.restore();
}
};
Physics.prototype.click = function(callback) {
var self = this;
function handleClick(e) {
e.preventDefault();
var point = {
x: (e.offsetX || e.layerX) / self.scale,
y: (e.offsetY || e.layerY) / self.scale
};
self.world.QueryPoint(funct... | this.gaveOver = true;
}
Physics.prototype.getGaveOver = function() {
return this.gaveOver;
}
Physics.prototype.getPlayStatus = function() {
return this.isPause;
}
var Body = window.Body = function(physics,details) {
this.details = details = details || {};
// Create the definition
this.definition =... | Physics.prototype.setGaveOver = function() { | random_line_split |
script.js | .gameLoop = function() {
var tm = new Date().getTime();
requestAnimationFrame(gameLoop);
var dt = (tm - lastFrame) / 1000;
if(dt > 1/15) { dt = 1/15; }
physics.step(dt);
lastFrame = tm;
player.scores.mt = player.scores.mt+dt;
scoreMtObj.innerText = Math.round(player.scores.mt*10);
};
function createW... | showHiteffect | identifier_name | |
script.js | obj.GetNext();
}
this.context.restore();
}
};
Physics.prototype.click = function(callback) {
var self = this;
function handleClick(e) {
e.preventDefault();
var point = {
x: (e.offsetX || e.layerX) / self.scale,
y: (e.offsetY || e.layerY) / self.scale
};
self.world.QueryPoint(funct... |
context.restore();
}
window.gameLoop = function() {
var tm = new Date().getTime();
requestAnimationFrame(gameLoop);
var dt = (tm - lastFrame) / 1000;
if(dt > 1/15) { dt = 1/15; }
physics.step(dt);
lastFrame = tm;
player.scores.mt = player.scores.mt+dt;
scoreMtObj.innerText = Math.round(player.scor... | {
context.drawImage(this.details.image,
-this.details.width/2,
-this.details.height/2,
this.details.width,
this.details.height);
} | conditional_block |
mining_test.go | Asset, 1, false, 0, common.HexToHash("6"),
}, {
keys[2], 1e4, &asiutil.AsimovAsset, 2, false, 0, common.HexToHash("6"),
}, {
keys[2], 1e4, &asiutil.AsimovAsset, 2, false, 0, common.HexToHash("7"),
}, {
keys[3], 1e4, &asiutil.AsimovAsset, 4, false, 0, common.HexToHash("7"),
},
}, []*fakeOut{
... | {
return false
} | conditional_block | |
mining_test.go | (t *testing.T) {
// Create some fake priority items that exercise the expected sort
// edge conditions.
testItems := []*TxPrioItem{
{gasPrice: 5678,},
{gasPrice: 1234,},
{gasPrice: 10001,},
{gasPrice: 0,},
}
// Add random data in addition to the edge conditions already manually
// specified.
randSeed :=... | TestTxPriceHeap | identifier_name | |
mining_test.go | true,
},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
_, _, err := CreateCoinbaseTx(&chaincfg.MainNetParams, test.height, test.validater, nil)
if test.wantErr != (err != nil) {
t.Errorf("tests #%d error %v", i, err)
}
}
}
func TestNewBlockTemplate(t *testing.T) {
policy :=... | {
privKey, _ := crypto.NewPrivateKey(crypto.S256())
pkaddr, _ := address.NewAddressPubKey(privKey.PubKey().SerializeCompressed())
addr := pkaddr.AddressPubKeyHash()
tests := []struct {
validater common.IAddress
height int32
wantErr bool
}{
{
pkaddr,
1,
false,
}, {
addr,
1,
false,
... | identifier_body | |
mining_test.go | addr,
1,
false,
}, {
&common.Address{},
1,
true,
},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
_, _, err := CreateCoinbaseTx(&chaincfg.MainNetParams, test.height, test.validater, nil)
if test.wantErr != (err != nil) {
t.Errorf("tests #%d error %v", i, err)
}... | pkaddr,
1,
false,
}, { | random_line_split | |
__init__.py | Backend %s is not supported" % new_default_backend
)
__default_backend = new_default_backend
def get_default_backend():
"""Returns the default cryptensor backend (mpc, he)"""
return __default_backend
def cryptensor(*args, backend=None, **kwargs):
"""
Factory function to return encrypted tens... | """
Saves a CrypTensor or PyTorch tensor to a file.
Args:
obj: The CrypTensor or PyTorch tensor to be saved
f: a file-like object (has to implement `read()`, `readline()`,
`tell()`, and `seek()`), or a string containing a file name
src: The source party that writes data to... | identifier_body | |
__init__.py | _stats()
def reset_communication_stats():
comm.get().reset_communication_stats()
# Set backend
__SUPPORTED_BACKENDS = [crypten.mpc]
__default_backend = __SUPPORTED_BACKENDS[0]
def set_default_backend(new_default_backend):
"""Sets the default cryptensor backend (mpc, he)"""
global __default_backend
... |
except AssertionError:
valid = torch.tensor(0, dtype=torch.long)
return valid
def load(f, encrypted=False, dummy_model=None, src=0, **kwargs):
"""
Loads an object saved with `torch.save()` or `crypten.save()`.
Args:
f: a file-like object (has to implement `read()`, `readline()`,
... | loaded_module = loaded_modules.pop(0)
dummy_module = dummy_modules.pop(0)
# Assert modules have the same number of parameters
loaded_params = [param for param in loaded_module.parameters()]
dummy_params = [param for param in dummy_module.parameters()]
assert ... | conditional_block |
__init__.py | _stats()
def reset_communication_stats():
comm.get().reset_communication_stats()
# Set backend
__SUPPORTED_BACKENDS = [crypten.mpc]
__default_backend = __SUPPORTED_BACKENDS[0]
def set_default_backend(new_default_backend):
"""Sets the default cryptensor backend (mpc, he)"""
global __default_backend
... | (*args, backend=None, **kwargs):
"""
Factory function to return encrypted tensor of given backend.
"""
if backend is None:
backend = get_default_backend()
if backend == crypten.mpc:
return backend.MPCTensor(*args, **kwargs)
else:
raise TypeError("Backend %s is not support... | cryptensor | identifier_name |
__init__.py | import crypten.nn # noqa: F401
import torch
# other imports:
from . import debug
from .cryptensor import CrypTensor
from .mpc import ptype
def init():
comm._init(use_threads=False, init_ttp=crypten.mpc.ttp_required())
if comm.get().get_rank() < comm.get().get_world_size():
_setup_przs()
if c... | import crypten.mpc # noqa: F401 | random_line_split | |
debugvm.py | ")
update_cpu_views()
def cb_idle(sender, data):
VMCPU.reset()
VMCPU.moveToWord("Idle")
update_cpu_views()
def cb_halt(sender, data):
VMCPU.reset()
VMCPU.moveToWord("Halt")
update_cpu_views()
def add_controls():
if does_item_exist("Controls"):
delete_item("Controls")
with window("Controls", au... | updateDisplay | identifier_name | |
debugvm.py | point:
update_cpu_views()
def cb_out(sender, data):
if "Program" not in Windows:
return
try:
while VMCPU.getCurrentOpcodeName()!= ";":
VMCPU.step(ignorebp=VMCPU.PC)
update_cpu_views()
VMCPU.step(ignorebp=VMCPU.PC)
update_cpu_views()
except VMCPUStopped:
update_cpu_v... |
with window("Controls", autosize=True, x_pos=0, y_pos=0):
with group("Buttons1", horizontal=True):
w = charW(6)
add_button("STEP", width=w, callback=cb_step, tip="Run one instruction")
add_button("STEPL", width=w, callback=cb_lstep, tip="Run one source line of code")
add_button("NEXTL"... | delete_item("Controls") | conditional_block |
debugvm.py | print(get_item_configuration(f"SourceL{sl}"))
def updateDisplay(self):
self.selectMemAddr(VMCPU.PC)
def cb_addr_click(self, sender, data):
#print(sender, data)
VMCPU.toggleBP(data)
item = f"SourceLN{self.D.getSourceLineForAddr(data)}"
i = 4
hovercol = hsv_to_rgb(i/7.0, 0.7, 0.7, 0.3)
i... | if does_item_exist(name):
del Windows[name]
delete_item(name)
Windows[name] = StackDisplay(name, stack) | identifier_body | |
debugvm.py | 4
hovercol = hsv_to_rgb(i/7.0, 0.7, 0.7, 0.3)
for item in get_item_children(f"{name}G{count}"):
set_item_color(item, mvGuiCol_Button, [0,0,0,0])
set_item_color(item, mvGuiCol_ButtonHovered, hovercol)
set_item_color(item, mvGuiCol_ButtonActive, hsv_to_rgb(i/7.0, 0.8, 0.8, 1.0))
set_item_... |
if y < mbh: | random_line_split | |
aug_utility.py |
return boxes
def find_margined_bounding_boxes(fimage, lables, margins):
# initialize boxes array
boxes = []
for lable in lables:
# iterate all lables
# filter out image pixels with current lable
labled = (fimage == lable) + 0
# find indexes
box = find_boun... | labled = (fimage == lable) + 0
# find indexes
box = find_bounding_box(labled)
# append found bouding box
boxes.append(box) | conditional_block | |
aug_utility.py | (box, shape, default = 20):
w_pad = default
h_pad = default
# dynamic padding
if default == 0:
rbox = RBox.fromPointBoundingBox(box)
w_pad = round(0.205 * rbox.w)
h_pad = round(0.205 * rbox.h)
# extract with and height from shape
height, width = shape[0:2]
# extr... | __eq__ | identifier_name | |
aug_utility.py | np.uint8(image)
# extract contours
image, contours, hierarchy = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
final_contours = []
for cnt in contours:
if cv2.contourArea(cnt) >= weight:
# add it to final_contours
final_contours.append(cnt)
fima... | pad_x_start = h_pad
if y_start - pad_x_start < 0:
pad_x_start = y_start
pad_y_start = w_pad
if x_start - pad_y_start < 0:
pad_y_start = x_start
pad_x_end = w_pad
if y_end + pad_x_end >= height:
pad_x_end = height - y_end - 1
pad_y_end = h_pad
if x_end + pad_y_e... | # check if is it possible to add certain padding
# if not add possible padding for all 4 points | random_line_split |
aug_utility.py | return pad_x_start, pad_x_end, pad_y_start, pad_y_end
def findConnectedComponents(frame, threshold = 150, blur_radius = 1.0):
img = frame.copy() # gray-scale image
# smooth the image (to remove small objects)
imgf = ndimage.gaussian_filter(img, blur_radius)
# find connected components
labe... | similar_boxes = RBox.similarityThreshold(boxes, threshold)
while len(similar_boxes) > 0:
union = boxes[similar_boxes[0][1]] | boxes[similar_boxes[0][0]]
# remove similar boxes
del boxes[similar_boxes[0][0]]
del boxes[similar_boxes[0][1]]
boxes.appe... | identifier_body | |
index.ts | from './createWixCodeSdk'
import createSdkFactoryParams from './createSdkFactoryParams'
import setPropsFactory from './setPropsFactory'
import { ControllerEvents } from './ControllerEvents'
import { DocumentSdkFactory } from './componentsSDK/Document'
import { createPlatformApi } from './appsAPI/platformAPI'
import Co... |
const fedopsWebVitalsManager = FedopsWebVitalsManager({ platformEnvData, modelsApi, handlers })
fedopsWebVitalsManager.registerWidgets()
const ssrCacheHintsManager = SsrCacheHintsManager({ platformEnvData, modelsApi, handlers })
ssrCacheHintsManager.setSsrCacheHints()
const { createStorageApi, loadCo... | {
handlers.registerOnPropsChangedHandler(bootstrapData.currentContextId, (changes: CompProps) => {
_.map(changes, (newProps, compId) => {
modelsApi.updateProps(compId, newProps)
})
})
} | conditional_block |
index.ts | from './createWixCodeSdk'
import createSdkFactoryParams from './createSdkFactoryParams'
import setPropsFactory from './setPropsFactory'
import { ControllerEvents } from './ControllerEvents'
import { DocumentSdkFactory } from './componentsSDK/Document'
import { createPlatformApi } from './appsAPI/platformAPI'
import Co... | appsConductedExperiments: bootstrapData.essentials.appsConductedExperiments,
getAppToken(appDefId) {
return sessionService.getInstance(appDefId)
},
isSSR,
})
const biUtils = platformBiLoggerFactory({
sessionService,
factory: essentials.biLoggerFactory,
location: platformEnvData.l... | const essentials = new ViewerPlatformEssentials({
metaSiteId: platformEnvData.location.metaSiteId,
conductedExperiments: {}, | random_line_split |
index.ts | from './createWixCodeSdk'
import createSdkFactoryParams from './createSdkFactoryParams'
import setPropsFactory from './setPropsFactory'
import { ControllerEvents } from './ControllerEvents'
import { DocumentSdkFactory } from './componentsSDK/Document'
import { createPlatformApi } from './appsAPI/platformAPI'
import Co... | () {
const { promise: waitForInit, resolver: initDone } = createPromise<PlatformState>()
return {
initPlatformOnSite({ logger, platformEnvData }: { logger: PlatformLogger; platformEnvData: PlatformEnvData }) {
const siteStorageApi: CreateWixStorageAPI = createStorageAPI()
initDone({
createStorageApi: (a... | createPlatformAPI | identifier_name |
index.ts | from './createWixCodeSdk'
import createSdkFactoryParams from './createSdkFactoryParams'
import setPropsFactory from './setPropsFactory'
import { ControllerEvents } from './ControllerEvents'
import { DocumentSdkFactory } from './componentsSDK/Document'
import { createPlatformApi } from './appsAPI/platformAPI'
import Co... | ,
async runPlatformOnPage({ bootstrapData, logger, importScripts, moduleLoader, viewerAPI, fetchModels, sessionService }: InitArgs) {
logger.interactionStarted('initialisation')
const createSdkHandlers = (pageId: string) => createDeepProxy((path: Array<string>) => (...args: Array<never>) => viewerAPI.invokeSdk... | {
const siteStorageApi: CreateWixStorageAPI = createStorageAPI()
initDone({
createStorageApi: (appPrefix: string, handlers: any, storageInitData: StorageInitData): WixStorageAPI => {
return siteStorageApi(appPrefix, handlers, storageInitData)
},
loadComponentSdksPromise: getComponentsSDKLoader({... | identifier_body |
universe.js |
function toggle() {
var p_status = $('#MisakaMoe').css('left');
var position = p_status == '0px' ? '140px' : '0px';
var w_status = $('#fire_board').css('width');
var w = w_status == '45px' ? '185px' : '45px';
$('#MisakaMoe').css('left', position);
$('#fire_board').animate({
width: w
});
$('#firelist').slideT... | }
function playAuById(Id) {
document.getElementById(Id).play();
} | random_line_split | |
universe.js | 190px' : '2px -190px';
$('#fireaway').css('background-position', p2);
});
if ($('.animated_img:eq(0)').attr('src') == 'fz.png') {
addSrc();
}
changeCount();
}
function changeCount() {
var count = $('.f_count:eq(0)');
count.html(Number(count.html()) + 1); | n openAd() {
var ad_iframe = document.createElement('iframe');
ad_iframe.className = 'ad_iframe';
ad_iframe.name = 'ad_iframe';
ad_iframe.height = "0px";
ad_iframe.width = "0px";
ad_iframe.setAttribute('frameborder', '0');
// var jh_img = document.createElement('img');
// jh_img.src = 'http://fireawayh.hostingf... |
}
functio | identifier_name |
universe.js |
noticeAdjust.value = localStorage.getItem("noticeAdjust");
SGInfo.value = localStorage.getItem("SGInfo");
var fontName = localStorage.getItem("fontSelector");
var fontSelector = document.getElementById("fontSelector");
var fontSize = localStorage.getItem("fontSizer");
var fontSizer = document.getElementById("f... | {
var id = localStorage.key(i);
var value = eval(localStorage.getItem(id) == "true");
if (id == "AjaxType") {
value = localStorage.getItem("AjaxType");
id = "bfp_AjaxType_" + value;
}
var obj = document.getElementById(id);
try {
if (value) {
obj.setAttribute("checked", "");
}
} catch (e) {... | conditional_block | |
trig.rs | 64> = Angle::turns(0.5);
//!
//! // And convert between them seemlessly:
//! match angle4.to_radians() {
//! Rad(val) => println!("0.5 turns is {}!", Rad(val)),
//! _ => fail!("But I wanted radians!")
//! }
//!
//! // We can use the top-level trigonometric functions on any of them:
//! assert_eq!(sin(angle1), s... |
/// Calculate the cosine.
#[stable] #[inline] pub fn cos<S: BaseFloat, T: Trigonometry<S>>(t: T) -> S { t.cos() }
/// Calculate the tangent.
#[stable] #[inline] pub fn tan<S: BaseFloat, T: Trigonometry<S>>(t: T) -> S { t.tan() }
/// Calculate the arcsine (in radians).
#[inline] pub fn asin<S: BaseFloat>(s: S) -> An... | { t.sin() } | identifier_body |
trig.rs | 64> = Angle::turns(0.5);
//!
//! // And convert between them seemlessly:
//! match angle4.to_radians() {
//! Rad(val) => println!("0.5 turns is {}!", Rad(val)),
//! _ => fail!("But I wanted radians!")
//! }
//!
//! // We can use the top-level trigonometric functions on any of them:
//! assert_eq!(sin(angle1), s... | (s: S) -> Angle<S> { Rad(s % Float::two_pi()) }
/// Returns an angle in degrees.
pub fn degrees(s: S) -> Angle<S> { Deg(s % FromPrimitive::from_f64(360.0).unwrap()) }
/// Returns an angle in gradians.
pub fn gradians(s: S) -> Angle<S> { Grad(s % FromPrimitive::from_f64(400.0).unwrap()) }
/// ... | radians | identifier_name |
trig.rs | //! copy of the documentation should be available at
//! [Rust-CI](http://www.rust-ci.org/atheriel/trig-rs/doc/trig/).
//!
//! ## Examples
//!
//! ```rust
//! use trig::{Angle, Rad, sin, cos};
//!
//! // Angle can be constructed in both common formats:
//! let angle1: Angle<f64> = Angle::degrees(180.0);
//! let angle2:... | //!
//! The code is hosted on [GitHub](https://github.com/atheriel/trig-rs), and a | random_line_split | |
ViewProjectDependence.ts | ],
placeholder: `${componentSearchForProjectPlaceholder}`,
oninput: this._onSearchComponentRepo,
value: `${this._search}`,
}),
]),
]);
}
private _renderSearchTip() {
if (this._search === '') {
return;
}
const { pagedComponentRepos } = this.properties;
let length = 0;
if (pagedC... | random_line_split | ||
ViewProjectDependence.ts | { latestCommitInfo } = this.properties;
return v('div', { classes: [c.card, !latestCommitInfo ? c.border_top_0 : undefined] }, [
w(LatestCommitInfo, { latestCommitInfo, showBottomBorder: true }), // 最近提交信息区
this._renderDependenceEditor(),
]);
}
private _renderDependenceEditor() {
return v('div', { clas... | RepoType.PROD
);
if (buildDependences.length === 0) {
return [];
}
return [v('div', {}, [v('strong', ['构建'])]), ...this._renderComponentRepoDependences(buildDependences)];
}
private _renderComponentRepoDependences(dependences: ProjectDependenceData[]): DNode[] {
const { repository, onDeleteDependence,... | {
return [];
}
return [v('div', {}, [v('strong', ['开发'])]), ...this._renderComponentRepoDependences(devDependences)];
}
private _renderBuildComponentRepos(): DNode[] {
const { dependences = [] } = this.properties;
const buildDependences = dependences.filter(
(dependence) => dependence.componentRepo.r... | identifier_body |
ViewProjectDependence.ts | extends ThemedMixin(I18nMixin(WidgetBase))<ViewProjectDependenceProperties> {
private _localizedMessages = this.localizeBundle(messageBundle);
@watch()
private _search: string = '';
protected render() {
const { repository } = this.properties;
if (!repository) {
return v('div', { classes: [c.mt_5] }, [w(Sp... | ViewProjectDependence | identifier_name | |
ViewProjectDependence.ts | { latestCommitInfo } = this.properties;
return v('div', { classes: [c.card, !latestCommitInfo ? c.border_top_0 : undefined] }, [
w(LatestCommitInfo, { latestCommitInfo, showBottomBorder: true }), // 最近提交信息区
this._renderDependenceEditor(),
]);
}
private _renderDependenceEditor() {
return v('div', { clas... | // 当前只支持 git
w(FontAwesomeIcon, { icon: ['fab', 'git-alt'], classes: [c.text_muted], title: 'git 仓库' }),
v(
'a',
{
target: '_blank',
href: `${item.apiRepo.gitRepoUrl}`,
title: '跳转到 API 仓库',
classes: [c.ml_1],
},
[`${item.apiRepo.gitRepoOwner}/${... | , {}, [v('strong', ['API'])]),
v(
'div',
{ classes: [c.pl_4, c.border_left] },
groupedApiRepos.map((item) =>
v('div', {}, [
| conditional_block |
01_questions.js | At long last, someone invents "the dream VCR." This machine allows you to tape an entire evenings worth of your own dreams, which you can then watch at your leisure. However, the inventor of the dream VCR will only allow you to use this device if you agree to a strange caveat: When you watch your dreams, you must do so... | answer2: 'Dealbreaker!', | random_line_split | |
SgScriptEngine.py | backwardQuoteCount += 1
if backwardQuoteCount >= 2:
backwardQuoteCount = 0
curWord += c
elif c == ' ':
if len(curWord) <= 0:
continue
if curWord.endswith('(') and backwardQuoteCount <= 0:
continue
if backwardQuoteCount >= 1 or not curWord.endswith(' ')... |
for c in sgSearchExpSpan:
if c in [' ', '.', '=', '<', '>', '!']:
break
index += 1
fieldName = sgSearchExpSpan[:index]
try:
fieldInfo = sgEntityFieldInfos[fieldName]
except KeyError:
raise SgScriptError('"%s" invalid field name' % fieldName)
try:
scriptField = SCRIPT_FIELDS[fiel... | '''
Builds a logical operator from a search expression span.
'''
if len(sgSearchExpSpan) <= 0:
raise SgScriptError('search expression span empty')
ShotgunORM.LoggerScriptEngine.debug(' - Parsing sub-span: "%(sgSearchExpSpan)s"', {'sgSearchExpSpan': sgSearchExpSpan})
inverse = sgSearchExpSpan... | identifier_body |
SgScriptEngine.py | backwardQuoteCount += 1
if backwardQuoteCount >= 2:
backwardQuoteCount = 0
curWord += c
elif c == ' ':
if len(curWord) <= 0:
continue
| if curWord.endswith('(') and backwardQuoteCount <= 0:
continue
if backwardQuoteCount >= 1 or not curWord.endswith(' '):
curWord += c
else:
curWord += c
if backwardParenCount != 0:
raise SgScriptError('"%s" missing closing parentheses' % curWord)
result = curWord.strip()
... | random_line_split | |
SgScriptEngine.py | backwardQuoteCount += 1
if backwardQuoteCount >= 2:
backwardQuoteCount = 0
curWord += c
elif c == ' ':
if len(curWord) <= 0:
continue
if curWord.endswith('(') and backwardQuoteCount <= 0:
continue
if backwardQuoteCount >= 1 or not curWord.endswith(' ')... |
else:
if sgSearchExpSpan.startswith(' not '):
inverse = True
sgSearchExpSpan = sgSearchExpSpan[5:]
index = 0
for c in sgSearchExpSpan:
if c in [' ', '.', '=', '<', '>', '!']:
break
index += 1
fieldName = sgSearchExpSpan[:index]
try:
fieldInfo = sgEntityFieldInfos[field... | sgSearchExpSpan = sgSearchExpSpan[1:] | conditional_block |
SgScriptEngine.py | (exceptions.Exception):
'''
General script engine exception.
'''
pass
def cleanSearchExp(sgSearchExp):
'''
Returns the passed search expression cleaned up of extra spaces.
Also throws when closing parentheses and quotes are not present.
'''
backwardParenCount = 0
backwardQuoteCount = 0
index ... | SgScriptError | identifier_name | |
model_abs.py | :", 1.0/rrm.data[1,3])
# TEST (put here the energies and temperature)
E2 = 2.24165620051
E1 = 2.13494501445
kbT = 0.01008086552556262
print("Relaxation time ratio :", rrm.data[2,1]/rrm.data[1,2])
print("... to be compared with :", numpy.exp(-(E2-E1)/kbT))
# In[8]:
rwa = agg.get_RWA_suggestion()
with qr.energy_u... | random_line_split | ||
model_abs.py |
#
# Model from Jordanides at al. Ref. 1 is adjusted and extended by two CT states
#
#
jordanides = False
if jordanides:
offset = 0.0
offset_P = 0.0 #485.0
offset_P_M = offset_P + 0.0
h_shift = 0.0
sc_H = 1.0
sc_P = 1.0
else:
offset = 275
offset_P = 400 #485.0
offset_P_M = offset... | try:
os.makedirs(pre_out, exist_ok=True)
except:
raise Exception("Output directory name '"
+pre_out+"' does not represent a valid directory") | conditional_block | |
waypoint_updater.py | about traffic lights or obstacles.
Once you have created dbw_node, you will update this node to use the status of traffic lights too.
Please note that our simulator also provides the exact location of traffic lights and their
current status in `/vehicle/traffic_lights` message. You can use this message to build this ... |
else:
rospy.logwarn('too late to stopp the car')
self.car_distance_to_tl_when_car_started_to_slow_down = None
self.car_velocity_when_car_started_to_slow_down = None
rospy.loginfo('car_distance_to_stop_line %s v... | planned_velocity = 0.0
reached_zero_velocity = True | conditional_block |
waypoint_updater.py | about traffic lights or obstacles.
Once you have created dbw_node, you will update this node to use the status of traffic lights too.
Please note that our simulator also provides the exact location of traffic lights and their
current status in `/vehicle/traffic_lights` message. You can use this message to build this ... |
def waypoints_cb(self, waypoints):
self.waypoints = waypoints
def traffic_cb(self, traffic_waypoint):
# Callback for /traffic_waypoint message.
# Store the timestamp and the traffic light position to use them for final_waypoints in waypoints_cb
self.traffic_waypoint_timestamp ... | self.velocity = msg.twist.linear.x | identifier_body |
waypoint_updater.py | about traffic lights or obstacles.
Once you have created dbw_node, you will update this node to use the status of traffic lights too.
Please note that our simulator also provides the exact location of traffic lights and their
current status in `/vehicle/traffic_lights` message. You can use this message to build this ... | pass
def get_waypoint_velocity(self, waypoint):
return waypoint.twist.twist.linear.x
def set_waypoint_velocity(self, |
def obstacle_cb(self, msg):
# TODO: Callback for /obstacle_waypoint message. We will implement it later | random_line_split |
waypoint_updater.py | lights too.
Please note that our simulator also provides the exact location of traffic lights and their
current status in `/vehicle/traffic_lights` message. You can use this message to build this node
as well as to verify your TL classifier.
TODO (for Yousuf and Aaron): Stopline location for each traffic light.
'''
... | distance | identifier_name | |
lib.rs | att"' "and \"friends\"""#).unwrap();
//! let chn = br().sib_lf("hello").sib_lf("matt\"").sib_lf("and \"friends\"");
//! assert_eq!(bk,chn);
//!
//! ```
use std::str::FromStr;
use std::fmt;
use std::fmt::Display;
use std::iter::IntoIterator;
pub mod tail;
pub use tail::{Tail};
use tail::EMPTY_BRACKET;
pub mod iter;
... | random_line_split | ||
lib.rs | Build method
//! let basic1 = Branch(vec![Leaf("hello".to_string()),
//! Branch(vec![Leaf("peter".to_string()),
//! Leaf("dave".to_string())])]);
//!
//! //Chaining Build method
//! let chain1 = br().sib_lf("hello")
//! .sib(br().sib_lf("pe... |
pub fn br()->Bracket{
Bracket::Branch(Vec::new())
}
impl FromStr for Bracket{
type Err = String;
fn from_str(s:&str)->Result<Bracket,String>{
let mut res = Bracket::Empty;
let mut it = s.chars();
let mut curr = String::new();
while let Some(c) = it.next() {
... | {
Bracket::Leaf(s.to_string())
} | identifier_body |
lib.rs | Build method
//! let basic1 = Branch(vec![Leaf("hello".to_string()),
//! Branch(vec![Leaf("peter".to_string()),
//! Leaf("dave".to_string())])]);
//!
//! //Chaining Build method
//! let chain1 = br().sib_lf("hello")
//! .sib(br().sib_lf("pe... | () {
let b1 = Bracket::from_str("matt dave (andy steve)").unwrap();
let c1 = br().sib_lf("matt").sib_lf("dave").sib(
br().sib_lf("andy").sib_lf("steve")
);
let b2 = Bracket::from_str("matt dave( andy ste... | spaces | identifier_name |
update.js | .log(`Found versions: \n${versions.map(version => ` ${version}`).join('\n')}\n`);
const pinToVersion = await cli_ux_1.default.prompt('Enter a version to update to');
if (!versions.includes(pinToVersion))
throw new Error(`Version ${pinToVersion} not found in the locally instal... |
// removes any unused CLIs
async tidy() {
try {
const root = this.clientRoot;
if (!await fs.pathExists(root))
return;
const files = await util_1.ls(root);
const promises = files.map(async (f) => {
if (['bin', 'current', thi... | {
let output = false;
const lastrunfile = path.join(this.config.cacheDir, 'lastrun');
const m = await this.mtime(lastrunfile);
m.setHours(m.getHours() + 1);
if (m > new Date()) {
const msg = `waiting until ${m.toISOString()} to update`;
if (output) {
... | identifier_body |
update.js | .log(`Found versions: \n${versions.map(version => ` ${version}`).join('\n')}\n`);
const pinToVersion = await cli_ux_1.default.prompt('Enter a version to update to');
if (!versions.includes(pinToVersion))
throw new Error(`Version ${pinToVersion} not found in the locally instal... | () {
let output = false;
const lastrunfile = path.join(this.config.cacheDir, 'lastrun');
const m = await this.mtime(lastrunfile);
m.setHours(m.getHours() + 1);
if (m > new Date()) {
const msg = `waiting until ${m.toISOString()} to update`;
if (output) {
... | debounce | identifier_name |
update.js | this.log(`Found versions: \n${versions.map(version => ` ${version}`).join('\n')}\n`);
const pinToVersion = await cli_ux_1.default.prompt('Enter a version to update to');
if (!versions.includes(pinToVersion))
throw new Error(`Version ${pinToVersion} not found in the locally i... | const instructions = this.config.scopedEnvVar('UPDATE_INSTRUCTIONS');
if (instructions)
this.warn(instructions);
return 'not updatable';
}
if (this.currentVersion === this.updatedVersion) {
if (this.config.scopedEnvVar('HIDE_UPDATED_MESSAGE... | await this.createBin(version);
await this.touch();
}
async skipUpdate() {
if (!this.config.binPath) { | random_line_split |
update.js | .log(`Found versions: \n${versions.map(version => ` ${version}`).join('\n')}\n`);
const pinToVersion = await cli_ux_1.default.prompt('Enter a version to update to');
if (!versions.includes(pinToVersion))
throw new Error(`Version ${pinToVersion} not found in the locally instal... |
return this.config.channel || 'stable';
}
async determineCurrentVersion() {
try {
const currentVersion = await fs.readFile(this.clientBin, 'utf8');
const matches = currentVersion.match(/\.\.[/|\\](.+)[/|\\]bin/);
return matches ? matches[1] : this.config.vers... | {
const channel = await fs.readFile(channelPath, 'utf8');
return String(channel).trim();
} | conditional_block |
rnn.py | set and ground truth label tensors
:param options: (hyper)parameters of the neural network model. See method unpack_options for details on the
full list of configurable options
"""
self.training_data = np.array(training_data, dtype=np.float32)
self.training_label = np.array(tra... | (self):
"""
Set up a computation graph for TensorFlow
:return: None
"""
self.graph = tf.Graph()
model_type = self.options['model_type']
optimiser_selected = self.options['optimizer']
with self.graph.as_default():
self.tf_dataset = tf.placehold... | create_graph | identifier_name |
rnn.py | self.tf_dataset = None
self.learning_rate = None
# Two lists to store the losses and accuracies during training and testing
self.train_losses = []
self.train_accuracies = []
def create_graph(self):
"""
Set up a computation graph for TensorFlow
:retur... | if len(self.train_losses) == 0:
raise ValueError("The model session has not been run!")
plt.subplot(121)
plt.plot(self.train_losses)
plt.ylabel("Loss")
plt.xlabel('Number of batch iterations')
plt.title("Loss vs iterations")
plt.subplot(122)
plt.plot... | identifier_body | |
rnn.py | ['input_dimension']
self.graph = None
self.loss = None
self.optimizer = None
self.predict = None
self.tf_labels = None
self.tf_dataset = None
self.learning_rate = None
# Two lists to store the losses and accuracies during training and testing
sel... |
plt.subplot(122) | random_line_split | |
rnn.py | set and ground truth label tensors
:param options: (hyper)parameters of the neural network model. See method unpack_options for details on the
full list of configurable options
"""
self.training_data = np.array(training_data, dtype=np.float32)
self.training_label = np.array(tra... |
if self.options['use_customised_optimizer'] is False:
if optimiser_selected == 'adam':
self.optimizer = tf.train.AdamOptimizer(self.learning_rate)
elif optimiser_selected == 'grad':
self.optimizer = tf.train.GradientDescentOptimizer(s... | penalty = self.options['regularisation_coeff'] * sum(tf.nn.l2_loss(var)
for var in tf.trainable_variables())
self.loss += penalty | conditional_block |
main.go | output: %v", err)
}
procs := make(map[int]*Proc)
done := make(chan error)
go func() {
tids := make(map[uint64]uint64)
stacks := make(map[uint64]*Stack)
locs := make(map[uint64]*profile.Location)
funcs := make(map[string]*profile.Function)
s := bufio.NewScanner(perfOut)
getProc := func(pid int) *Proc {
... | for ; ln[i] < '0' || ln[i] > '9'; i++ {
}
pidPos := i
for ; ln[i] >= '0' && ln[i] <= '9'; i++ {
}
pid, err := strconv.ParseUint(ln[pidPos:i], 10, 32)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to parse pid 8: %v '%v'\n", ln, ln[pidPos:i])
continue
}
if ln[i] != '/' {
... | */
i := 0 | random_line_split |
main.go | 1 {
fmt.Fprintf(os.Stderr, "failed to parse pid 6: v\n", ln)
continue
}
pos += len(" next_pid=")
i = pos
for ; ln[i] != ' '; i++ {
}
ntid, err := strconv.ParseUint(ln[pos:i], 10, 32)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to parse pid 7: v\n", ln)
continue
}
... | parseStack | identifier_name | |
main.go | : %v", err)
}
procs := make(map[int]*Proc)
done := make(chan error)
go func() {
tids := make(map[uint64]uint64)
stacks := make(map[uint64]*Stack)
locs := make(map[uint64]*profile.Location)
funcs := make(map[string]*profile.Function)
s := bufio.NewScanner(perfOut)
getProc := func(pid int) *Proc {
p :=... |
sample.n++
p.n++
}
}
done <- s.Err()
}()
if err := perf.Start(); err != nil {
failf("failed to start perf: %v", err)
}
errOutput, _ := ioutil.ReadAll(perfOutErr)
if err := perf.Wait(); err != nil {
if false {
failf("perf failed: %v\n%s", err, errOutput)
}
}
if err := <-done; err != nil {... | {
fmt.Fprintf(os.Stderr, "misaccounted sample: %v -> %v\n", run, sample.run)
} | conditional_block |
main.go | intel_pmu_enable_all
ffffffff81029ca4 x86_pmu_enable
ffffffff81143487 perf_pmu_enable
ffffffff81027d8a x86_pmu_commit_txn
ffffffff81143f00 group_sched_in
ffffffff811443c2 __perf_event_enable
ffffffff81140000 remote_function
ffffffff810dcf60 g... | {
fmt.Fprintf(os.Stderr, what+"\n", args...)
os.Exit(1)
} | identifier_body | |
simulation2_01.py | 90480378
x = float(Xcoordinate)
y = float(Ycoordinate)
#Randomly select the origin point along the linear vent
rand_index = randrange(0,10)
xorigin, yorigin = (xpt[rand_index], ypt[rand_index])
distance = check_topography(dtm, xorigin, yorigin, x+xorigin, y+yorigin, distance,elevation, dev, gtinv)
if dis... | If the shapefile flag is set to true a shapefile is created by calling
the shapefile function.
Parameters:
m: A basemap mapping object
xdata: An array of x landing coordinates, ndarray
ydata: An array of y landing coordinates, ndarray
shapefile: A flag on whether or not to generate a shapefile
ppg: The number... | 100mpp, bins the input data into the grid (density) and creates a
histogram. Finally, a mesh grid is created and the histogram is
plotted in 2D over the basemap.
| random_line_split |
simulation2_01.py |
4. Compare it to the analytical trajectory heights
5. If the impact occurs before total potential travel distance,
drop the projectile there. If not, place it at the total possible
travel distance.
Parameters
----------
dtm: A digital terrain model, in 16bit, storing terrain elevation, ndarray
orig... | p = multiprocessing.Process(target=strom_multi, args=(xarr,yarr,slice(i, i+step)), )
jobs.append(p) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.