file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
elasticsearch_adapter.js
const MainDatabase = require('../mainDatabase.js'); const elasticsearch = require('elasticsearch'); const AgentKeepAlive = require('agentkeepalive'); const cloneObject = require('clone'); const async = require('async'); const {BuilderNode} = require('../../../utils/filterbuilder'); const NexxusError = require('../../Ne...
(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
const MainDatabase = require('../mainDatabase.js'); const elasticsearch = require('elasticsearch'); const AgentKeepAlive = require('agentkeepalive'); const cloneObject = require('clone'); const async = require('async'); const {BuilderNode} = require('../../../utils/filterbuilder'); const NexxusError = require('../../Ne...
results = results.map(dbObject => { return utils.getProperModel(dbObject); }); results.forEach(model => { const {diff, detailedDiff} = NexxusPatch.applyPatches(objectsToGet.get(model.properties.id).patches, model); let index; if (modifiedApplicationSchemas.has(model.properties.id)) { try...
random_line_split
index.js
//@ts-check /** * Utility function * * @param {Array} arrA * @param {Array} arrB * @returns {Object} */ function zipObject(arrA, arrB) { const zip = (arrX, arrY) => arrX.map((x, i) => [x, arrY[i]]); return Object.fromEntries(zip(arrA, arrB)); } /** * A basic Promise-based and queue-based Semaphore */ cons...
(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
//@ts-check /** * Utility function * * @param {Array} arrA * @param {Array} arrB * @returns {Object} */ function zipObject(arrA, arrB) { const zip = (arrX, arrY) => arrX.map((x, i) => [x, arrY[i]]); return Object.fromEntries(zip(arrA, arrB)); } /** * A basic Promise-based and queue-based Semaphore */ cons...
/** * 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
//@ts-check /** * Utility function * * @param {Array} arrA * @param {Array} arrB * @returns {Object} */ function zipObject(arrA, arrB) { const zip = (arrX, arrY) => arrX.map((x, i) => [x, arrY[i]]); return Object.fromEntries(zip(arrA, arrB)); } /** * A basic Promise-based and queue-based Semaphore */ cons...
} } 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
//@ts-check /** * Utility function * * @param {Array} arrA * @param {Array} arrB * @returns {Object} */ function zipObject(arrA, arrB) { const zip = (arrX, arrY) => arrX.map((x, i) => [x, arrY[i]]); return Object.fromEntries(zip(arrA, arrB)); } /**
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
import sys import numpy as np import copy from sklearn.preprocessing import normalize def run_ann(zeros): activations = [sigmoid_activation, sigmoid_activation, linear_activation] deriv_activations = [sigmoid_activation_deriv, sigmoid_activation_deriv, linear_activation_deriv] # widths_values = [5, 10, 25...
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
import sys import numpy as np import copy from sklearn.preprocessing import normalize def run_ann(zeros): activations = [sigmoid_activation, sigmoid_activation, linear_activation] deriv_activations = [sigmoid_activation_deriv, sigmoid_activation_deriv, linear_activation_deriv] # widths_values = [5, 10, 25...
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
import sys import numpy as np import copy from sklearn.preprocessing import normalize def run_ann(zeros): activations = [sigmoid_activation, sigmoid_activation, linear_activation] deriv_activations = [sigmoid_activation_deriv, sigmoid_activation_deriv, linear_activation_deriv] # widths_values = [5, 10, 25...
(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
import sys import numpy as np import copy from sklearn.preprocessing import normalize def run_ann(zeros): activations = [sigmoid_activation, sigmoid_activation, linear_activation] deriv_activations = [sigmoid_activation_deriv, sigmoid_activation_deriv, linear_activation_deriv] # widths_values = [5, 10, 25...
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
/* 用于全量更新[tCR0001_V2.0]表中的company信息 wrote by tzf, 2017/12/8 */ const req = require('require-yml'); const Db = require('mssql'); const Mssql = req('./lib/mssql'); const Pool = req('./lib/pool'); const config = req('./config/source.yml'); const log4js = require('log4js'); const fs = require('fs'); const writeL...
(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
/* 用于全量更新[tCR0001_V2.0]表中的company信息 wrote by tzf, 2017/12/8 */ const req = require('require-yml'); const Db = require('mssql'); const Mssql = req('./lib/mssql'); const Pool = req('./lib/pool'); const config = req('./config/source.yml'); const log4js = require('log4js'); const fs = require('fs'); const writeL...
i].CR0001_005; //注册资金,未换算的值 let currencyUnit = rows[i].CR0001_006; //货币类型 let currencyFlag = rows[i].CR0001_040; //货币种类标识 let surStatus = rows[i].CR0001_041...
tra = 0; } let fund = rows[
conditional_block
updateTotalCompany.js
/* 用于全量更新[tCR0001_V2.0]表中的company信息 wrote by tzf, 2017/12/8 */ const req = require('require-yml'); const Db = require('mssql'); const Mssql = req('./lib/mssql'); const Pool = req('./lib/pool'); const config = req('./config/source.yml'); const log4js = require('log4js'); const fs = require('fs'); const writeL...
) rateFlag = 'GY'; else if (currencyFlag == 826) rateFlag = 'YB'; else if (currencyFlag == 124) rateFlag = 'JNDY'; else if (currencyFlag == 36) rateFlag = 'ODLYY'; else if (currencyFlag == 554) rateFlag = 'XXLY'; else if (currencyFlag == 702) rateFlag = 'XJPY'; else if (currencyFlag == 756...
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
/* 用于全量更新[tCR0001_V2.0]表中的company信息 wrote by tzf, 2017/12/8 */ const req = require('require-yml'); const Db = require('mssql'); const Mssql = req('./lib/mssql'); const Pool = req('./lib/pool'); const config = req('./config/source.yml'); const log4js = require('log4js'); const fs = require('fs'); const writeL...
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
package words import "math/rand" import "strings" import "time" func BigWords() 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...
"belt", "bench", "commission", "copy", "drop", "minimum", "path", "progress", "project", "sea", "south", "status", "stuff", "ticket", "tour", "angle", "blue", "breakfast", "confidence", "daughter", "degree", "doctor", "dot", "dream", "duty", "essay", "father", "fe...
"spirit", "street", "tree", "wave",
random_line_split
words.go
package words import "math/rand" import "strings" import "time" func
() 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
package words import "math/rand" import "strings" import "time" func BigWords() 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...
{ list := []string{ "people", "history", "way", "art", "world", "information", "map", "two", "family", "government", "health", "system", "computer", "meat", "year", "thanks", "music", "person", "reading", "method", "data", "food", "understanding", "theory", "law", "b...
identifier_body
words.go
package words import "math/rand" import "strings" import "time" func BigWords() 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
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
import functools from typing import List import numpy as np import hiccup.settings as settings import hiccup.model as model import hiccup.utils as utils import hiccup.transform as transform import hiccup.huffman as huffman import hiccup.hicimage as hic """ Encoding/Decoding functionality aka Run Length encoding ...
(k, v): utils.debug_msg("Determining deficient AC matricies for: " + k) ac_length = utils.size(shapes[k]) - len(dc_comps[k]) out = decode_run_length(v, ac_length) if k == "lum": s = [str(i) for i in out] print(" ".join(s)) return out ac_mats = utils.d...
ac_mat_fun
identifier_name
codec.py
import functools from typing import List import numpy as np import hiccup.settings as settings import hiccup.model as model import hiccup.utils as utils import hiccup.transform as transform import hiccup.huffman as huffman import hiccup.hicimage as hic """ Encoding/Decoding functionality aka Run Length encoding ...
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
import functools from typing import List import numpy as np import hiccup.settings as settings import hiccup.model as model import hiccup.utils as utils import hiccup.transform as transform import hiccup.huffman as huffman import hiccup.hicimage as hic """ Encoding/Decoding functionality aka Run Length encoding ...
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
import functools from typing import List import numpy as np import hiccup.settings as settings import hiccup.model as model import hiccup.utils as utils import hiccup.transform as transform import hiccup.huffman as huffman import hiccup.hicimage as hic """ Encoding/Decoding functionality aka Run Length encoding ...
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
use std::future::Future; use anyhow::Result; use wasmtime::{Caller, FuncType, Linker, Trap, ValType}; use crate::{ api::{error::IntoTrap, get_memory}, message::Message, state::ProcessState, }; use super::{link_async2_if_match, link_if_match}; // Register the mailbox APIs to the linker pub(crate) fn regi...
//% 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
use std::future::Future; use anyhow::Result; use wasmtime::{Caller, FuncType, Linker, Trap, ValType}; use crate::{ api::{error::IntoTrap, get_memory}, message::Message, state::ProcessState, }; use super::{link_async2_if_match, link_if_match}; // Register the mailbox APIs to the linker pub(crate) fn regi...
//% 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
use std::future::Future; use anyhow::Result; use wasmtime::{Caller, FuncType, Linker, Trap, ValType}; use crate::{ api::{error::IntoTrap, get_memory}, message::Message, state::ProcessState, }; use super::{link_async2_if_match, link_if_match}; // Register the mailbox APIs to the linker pub(crate) fn regi...
( mut caller: Caller<ProcessState>, data_size_ptr: u32, res_size_ptr: u32, ) -> Box<dyn Future<Output = Result<u32, Trap>> + Send + '_> { Box::new(async move { let message = caller .data_mut() .mailbox .recv() .await .expect("a process ...
prepare_receive
identifier_name
string.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let string = "Venenatis_tellus_vel_tellus"; let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>(); assert_eq!( break_string(20, false, &graphemes[..]), SnippetState::EndOfInput("Venenatis_tellus_vel_tellus".to_string()) ); ...
nothing_to_break
identifier_name
string.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[test] fn big_whitespace() { let string = "Neque in sem. Pellentesque tellus augue."; let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>(); assert_eq!( break_string(20, false, &graphemes[..]), SnippetState::LineEnd("...
{ 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
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
/// 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
use std::{ marker::Unpin, net::SocketAddr, str::FromStr, time::Duration, }; use futures::{ future::{ BoxFuture, Either, }, select, }; use tokio::{ net::signal::ctrl_c, prelude::*, runtime::Runtime, sync::oneshot, }; use bytes::{ Bytes, BytesMut, }; ...
(max_size_bytes: usize, receive: F) -> Self { Decode { read_head: 0, discarding: false, max_size_bytes, receive, } } } impl<F> Decoder for Decode<F> where F: FnMut(Bytes) -> Result<Option<Message>, Error...
new
identifier_name
server.rs
use std::{ marker::Unpin, net::SocketAddr, str::FromStr, time::Duration, }; use futures::{ future::{ BoxFuture, Either, }, select, }; use tokio::{ net::signal::ctrl_c, prelude::*, runtime::Runtime, sync::oneshot, }; use bytes::{ Bytes, BytesMut, }; ...
} 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
use std::{ marker::Unpin, net::SocketAddr, str::FromStr, time::Duration, }; use futures::{ future::{ BoxFuture, Either, }, select, }; use tokio::{ net::signal::ctrl_c, prelude::*, runtime::Runtime, sync::oneshot, }; use bytes::{ Bytes, BytesMut, }; ...
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
use super::*; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{ReadHalf, WriteHalf}; use tokio::net::TcpStream; use tracing::debug; use tracing::{error, Instrument}; async fn direct_to_control(mut incoming: TcpStream) { let mut control_socket = match TcpStream::connect(format!("localhost:{}", ...
#[tracing::instrument(skip(sink, stream_id, queue))] async fn tunnel_to_stream( subdomain: String, stream_id: StreamId, mut sink: WriteHalf<TcpStream>, mut queue: UnboundedReceiver<StreamMessage>, ) { loop { let result = queue.next().await; let result = if let Some(message) = resu...
{ // 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
use super::*; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{ReadHalf, WriteHalf}; use tokio::net::TcpStream; use tracing::debug; use tracing::{error, Instrument}; async fn direct_to_control(mut incoming: TcpStream) { let mut control_socket = match TcpStream::connect(format!("localhost:{}", ...
// 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
use super::*; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{ReadHalf, WriteHalf}; use tokio::net::TcpStream; use tracing::debug; use tracing::{error, Instrument}; async fn direct_to_control(mut incoming: TcpStream) { let mut control_socket = match TcpStream::connect(format!("localhost:{}", ...
(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
import { getIconFromExt, SvgIcon } from './icons'; import utils from './utils'; import { RGBA, ImageThumbnail, VideoThumbnail } from './utils'; interface Dimensions { height: number; width: number; } interface Options { accept?: string; maxSize?: string; read: boolean; thumbnailSize?: number; averageCol...
(resized: ImageThumbnail | null) { if (!resized) { return; } this.urlResized = resized.url; this.image = resized.image; if (resized.image && resized.image.width && resized.image.height) { this.dimensions.width = resized.image.width; this.dimensions.height = resized.image.height; ...
imageResized
identifier_name
file-record.ts
import { getIconFromExt, SvgIcon } from './icons'; import utils from './utils'; import { RGBA, ImageThumbnail, VideoThumbnail } from './utils'; interface Dimensions { height: number; width: number; } interface Options { accept?: string; maxSize?: string; read: boolean; thumbnailSize?: number; averageCol...
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
import { getIconFromExt, SvgIcon } from './icons'; import utils from './utils'; import { RGBA, ImageThumbnail, VideoThumbnail } from './utils'; interface Dimensions { height: number; width: number; } interface Options { accept?: string; maxSize?: string; read: boolean; thumbnailSize?: number; averageCol...
public imageResized(resized: ImageThumbnail | null) { if (!resized) { return; } this.urlResized = resized.url; this.image = resized.image; if (resized.image && resized.image.width && resized.image.height) { this.dimensions.width = resized.image.width; this.dimensions.height = r...
{ 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
import { getIconFromExt, SvgIcon } from './icons'; import utils from './utils'; import { RGBA, ImageThumbnail, VideoThumbnail } from './utils'; interface Dimensions { height: number; width: number; } interface Options { accept?: string; maxSize?: string; read: boolean; thumbnailSize?: number; averageCol...
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
var mov = 0, physics, lastFrame = new Date().getTime(), beams = {obj:[], img:new Image()}, player = {obj:null, hits:0, life:3, balls:[new Image(), new Image(), new Image(), new Image()], openBall: new Image(), scores: {pt:0, mt: 0}, needScore:1000}, walls = {}, coins = {obj:[], img:[]}, destroyObj = [], btnA...
function init() { var preloader = []; var imgArray = ['images/flappy-pacman-logo.png', 'images/log.png', 'images/smily-40.png', 'images/smily-40-1.png', 'images/smily-40-2.png', 'images/smily-40-3.png', 'images/coins/c1.png', 'images/coins/c2.png', 'images/coins/c3.png', 'images/coins/c4.png', 'images/coins/c5.p...
{ 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
var mov = 0, physics, lastFrame = new Date().getTime(), beams = {obj:[], img:new Image()}, player = {obj:null, hits:0, life:3, balls:[new Image(), new Image(), new Image(), new Image()], openBall: new Image(), scores: {pt:0, mt: 0}, needScore:1000}, walls = {}, coins = {obj:[], img:[]}, destroyObj = [], btnA...
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
var mov = 0, physics, lastFrame = new Date().getTime(), beams = {obj:[], img:new Image()}, player = {obj:null, hits:0, life:3, balls:[new Image(), new Image(), new Image(), new Image()], openBall: new Image(), scores: {pt:0, mt: 0}, needScore:1000}, walls = {}, coins = {obj:[], img:[]}, destroyObj = [], btnA...
(){ var v = player.obj.GetPosition(); var posX = -v.x * physics.scale + physics.element.width / 2; var posY = -v.y * physics.scale + physics.element.height / 2; bangObj.style.display = 'block'; bangObj.style.left = -posX + (physics.element.width / 2) - 10+'px'; if(v.x < (physics.element.width/physics.scale)/2){ ...
showHiteffect
identifier_name
script.js
var mov = 0, physics, lastFrame = new Date().getTime(), beams = {obj:[], img:new Image()}, player = {obj:null, hits:0, life:3, balls:[new Image(), new Image(), new Image(), new Image()], openBall: new Image(), scores: {pt:0, mt: 0}, needScore:1000}, walls = {}, coins = {obj:[], img:[]}, destroyObj = [], btnA...
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
// Copyright (c) 2018-2020 The asimov developers // Copyright (c) 2013-2017 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package mining import ( "container/heap" "github.com/AsimovNetwork/asimov/asiutil" "github.com/AsimovNetwork/asimov/...
for k, v := range ltxs { if v.TxHash() != *rtxs[k] { return false } } return true } t.Log(i) for _, v := range txs { t.Log(v.TxHash()) } t.Log(test.wantTx) if !outTxEqual(txs[:len(txs)-1], test.wantTx) { t.Errorf("tests #%d out tx error, txlen %d, want tx: %v", i, len(txs), tes...
{ return false }
conditional_block
mining_test.go
// Copyright (c) 2018-2020 The asimov developers // Copyright (c) 2013-2017 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package mining import ( "container/heap" "github.com/AsimovNetwork/asimov/asiutil" "github.com/AsimovNetwork/asimov/...
(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
// Copyright (c) 2018-2020 The asimov developers // Copyright (c) 2013-2017 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package mining import ( "container/heap" "github.com/AsimovNetwork/asimov/asiutil" "github.com/AsimovNetwork/asimov/...
func TestNewBlockTemplate(t *testing.T) { policy := Policy{ BlockProductedTimeOut: chaincfg.DefaultBlockProductedTimeOut, TxConnectTimeOut: chaincfg.DefaultTxConnectTimeOut, UtxoValidateTimeOut: chaincfg.DefaultUtxoValidateTimeOut, } chain, teardownFunc, err := newFakeChain(&chaincfg.MainNetParams) if err !...
{ 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
// Copyright (c) 2018-2020 The asimov developers // Copyright (c) 2013-2017 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package mining import ( "container/heap" "github.com/AsimovNetwork/asimov/asiutil" "github.com/AsimovNetwork/asimov/...
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
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import crypten.communicator as comm import crypten.mpc # noqa: F401 import crypten.nn # noqa: F401 import torch # o...
def where(condition, input, other): """ Return a tensor of elements selected from either `input` or `other`, depending on `condition`. """ if is_encrypted_tensor(condition): return condition * input + (1 - condition) * other elif torch.is_tensor(condition): condition = conditi...
""" 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
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import crypten.communicator as comm import crypten.mpc # noqa: F401 import crypten.nn # noqa: F401 import torch # o...
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
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import crypten.communicator as comm import crypten.mpc # noqa: F401 import crypten.nn # noqa: F401 import torch # o...
(*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
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import crypten.communicator as comm
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
#!/usr/bin/python3 from dearpygui.core import * from dearpygui.simple import * from disasm import DebugDis import json, sys, random from collections import OrderedDict from vm import * import systemtime FontSize = 5 Windows = {} CharW = 1 CharH = 1 SYSTIME = systemtime.SystemTime() VMCPU = CPU(SYSTIME) PREFS_FILE_NA...
(self): wl = self.CPU.getMemWriteList() if len(wl): for addr, writelen in wl: for byteaddr in range(addr, addr+writelen): val, sym = self.getByteAddrInfo(byteaddr) val = int(round(val)) set_value(f"{self.Name}bval_{byteaddr}", "%02X %4d" % (val, val)) set_va...
updateDisplay
identifier_name
debugvm.py
#!/usr/bin/python3 from dearpygui.core import * from dearpygui.simple import * from disasm import DebugDis import json, sys, random from collections import OrderedDict from vm import * import systemtime FontSize = 5 Windows = {} CharW = 1 CharH = 1 SYSTIME = systemtime.SystemTime() VMCPU = CPU(SYSTIME) PREFS_FILE_NA...
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
#!/usr/bin/python3 from dearpygui.core import * from dearpygui.simple import * from disasm import DebugDis import json, sys, random from collections import OrderedDict from vm import * import systemtime FontSize = 5 Windows = {} CharW = 1 CharH = 1 SYSTIME = systemtime.SystemTime() VMCPU = CPU(SYSTIME) PREFS_FILE_NA...
def add_mem(cpu, name): if does_item_exist(name): del Windows[name] delete_item(name) Windows[name] = MemoryDisplay(cpu, name) class CPUInfo: def __init__(self, cpu, name): self.Name = name self.CPU = cpu self.createDisplay() def updateDisplay(self): set_value(f"{self.Name}PC", "PC:...
if does_item_exist(name): del Windows[name] delete_item(name) Windows[name] = StackDisplay(name, stack)
identifier_body
debugvm.py
#!/usr/bin/python3 from dearpygui.core import * from dearpygui.simple import * from disasm import DebugDis import json, sys, random from collections import OrderedDict from vm import * import systemtime FontSize = 5 Windows = {} CharW = 1 CharH = 1 SYSTIME = systemtime.SystemTime() VMCPU = CPU(SYSTIME) PREFS_FILE_NA...
y = mbh+int(wp[1]) fix = True if fix: set_window_pos(i, x, y) def cb_mouse_release(sender, data): fix_window_positions() def cb_close(sender, data): set_mouse_release_callback(None) set_render_callback(None) def add_de1graph(): with window("Graphs"): add_plot("DE1", x_axis_name...
if y < mbh:
random_line_split
aug_utility.py
import numpy as np import cv2 from pixcel import * from scipy import ndimage import math from socket import * from config import * from time import time def find_bounding_boxes(fimage, lables): # initialize boxes array boxes = [] for lable in lables: # iterate all lables # filter out i...
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
import numpy as np import cv2 from pixcel import * from scipy import ndimage import math from socket import * from config import * from time import time def find_bounding_boxes(fimage, lables): # initialize boxes array boxes = [] for lable in lables: # iterate all lables # filter out i...
(self, other): return self.x == other.x and self.y == other.y and self.w == other.w and self.h == other.h @staticmethod def similarityStats(boxes): # create matrix out of boxes sim_mat = np.array(boxes).reshape((-1, 1)) sim_mat = np.tril(sim_mat.dot(sim_mat.T), -1) # ...
__eq__
identifier_name
aug_utility.py
import numpy as np import cv2 from pixcel import * from scipy import ndimage import math from socket import * from config import * from time import time def find_bounding_boxes(fimage, lables): # initialize boxes array boxes = [] for lable in lables: # iterate all lables # filter out i...
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
import numpy as np import cv2 from pixcel import * from scipy import ndimage import math from socket import * from config import * from time import time def find_bounding_boxes(fimage, lables): # initialize boxes array boxes = [] for lable in lables: # iterate all lables # filter out i...
@staticmethod def toPointBoundingBoxes(boxes): return [box.pointBoundingBox() for box in boxes] @staticmethod def toClassicBoundingBoxes(boxes): return [box.classicalBoundingBox() for box in boxes] def extractPatchFromImage(self, image, square=False): # get bounding bo...
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
import _ from 'lodash' import type { PlatformLogger, PlatformEnvData, StorageInitData, CompProps } from '@wix/thunderbolt-symbols' import { createLinkUtils, createPromise, logSdkError, logSdkWarning, createProxy } from '@wix/thunderbolt-commons' import { createDeepProxy } from '../deepProxyUtils' import { getComponents...
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
import _ from 'lodash' import type { PlatformLogger, PlatformEnvData, StorageInitData, CompProps } from '@wix/thunderbolt-symbols' import { createLinkUtils, createPromise, logSdkError, logSdkWarning, createProxy } from '@wix/thunderbolt-commons' import { createDeepProxy } from '../deepProxyUtils' import { getComponents...
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
import _ from 'lodash' import type { PlatformLogger, PlatformEnvData, StorageInitData, CompProps } from '@wix/thunderbolt-symbols' import { createLinkUtils, createPromise, logSdkError, logSdkWarning, createProxy } from '@wix/thunderbolt-commons' import { createDeepProxy } from '../deepProxyUtils' import { getComponents...
() { 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
import _ from 'lodash' import type { PlatformLogger, PlatformEnvData, StorageInitData, CompProps } from '@wix/thunderbolt-symbols' import { createLinkUtils, createPromise, logSdkError, logSdkWarning, createProxy } from '@wix/thunderbolt-commons' import { createDeepProxy } from '../deepProxyUtils' import { getComponents...
, 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
var path = 'http://bilifixer.nmzh.net/BFP/'; var i = 0; function ini() { // var flag = document.getElementById("fireaway").outerHTML.indexOf("newVersion"); // flag = true; // if (flag) { // toggle(); // } for (var i = 0; i < localStorage.length; i++) { var id = localStorage.key(i); var value = eval(localSto...
$("#openAd").html('轻抚菊花中...(' + j + '/' + ads_length + ')'); j++; changeSRC(ad_iframe, ads, j, ads_length); } else { j++; $("#openAd").html('⑨bishi菊花保护行动成功<br/> --黑洞的引力增强1%-- '); } }; } function slideUpOthers(Obj, selector) { var id = Obj.getAttribute("next"); $(selector).each(function() { if ($(...
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.hostingforfun.org/jh.png'; $("#openAd").html('⑨bishi\'s B(ju)Zhan(hua) Protection System<br/>Is Booting Up...
identifier_body
universe.js
var path = 'http://bilifixer.nmzh.net/BFP/'; var i = 0; function ini() { // var flag = document.getElementById("fireaway").outerHTML.indexOf("newVersion"); // flag = true; // if (flag) { // toggle(); // } for (var i = 0; i < localStorage.length; i++) { var id = localStorage.key(i); var value = eval(localSto...
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
var path = 'http://bilifixer.nmzh.net/BFP/'; var i = 0; function ini() { // var flag = document.getElementById("fireaway").outerHTML.indexOf("newVersion"); // flag = true; // if (flag) { // toggle(); // } for (var i = 0; i < localStorage.length; i++) { var id = localStorage.key(i); var value = eval(localSto...
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
var path = 'http://bilifixer.nmzh.net/BFP/'; var i = 0; function ini() { // var flag = document.getElementById("fireaway").outerHTML.indexOf("newVersion"); // flag = true; // if (flag) { // toggle(); // } for (var i = 0; i < localStorage.length; i++)
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
/* This file is part of trig-rs, a library for doing typesafe trigonometry with a variety of angle formats (radians, degrees, grad, turns, and so on). */ //! # `trig-rs`: Typesafe Trigonometric Primitives //! //! Leverage Rust's super-powered enums to create a typesafe system for //! trigonometry in degrees, r...
/// 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
/* This file is part of trig-rs, a library for doing typesafe trigonometry with a variety of angle formats (radians, degrees, grad, turns, and so on). */ //! # `trig-rs`: Typesafe Trigonometric Primitives //! //! Leverage Rust's super-powered enums to create a typesafe system for //! trigonometry in degrees, r...
(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
/* This file is part of trig-rs, a library for doing typesafe trigonometry with a variety of angle formats (radians, degrees, grad, turns, and so on). */ //! # `trig-rs`: Typesafe Trigonometric Primitives //! //! Leverage Rust's super-powered enums to create a typesafe system for //! trigonometry in degrees, r...
//! 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
import * as css from './ViewProjectDependence.m.css'; import ThemedMixin, { theme } from '@dojo/framework/core/mixins/Themed'; import I18nMixin from '@dojo/framework/core/mixins/I18n'; import WidgetBase from '@dojo/framework/core/WidgetBase'; import { v, w } from '@dojo/framework/core/vdom'; import * as c from '@blockl...
return v('li', { classes: [c.list_group_item] }, [ // 如果组件库未安装,则显示“使用”按钮,否则显示“已用”文本 v('div', {}, [ v('span', { classes: [c.font_weight_bold, c.mr_2] }, [ v('img', { width: 20, height: 20, classes: [c.avatar, c.mr_1], src: `${componentRepo.createUserAvatarUrl}`, }), `${...
random_line_split
ViewProjectDependence.ts
import * as css from './ViewProjectDependence.m.css'; import ThemedMixin, { theme } from '@dojo/framework/core/mixins/Themed'; import I18nMixin from '@dojo/framework/core/mixins/I18n'; import WidgetBase from '@dojo/framework/core/WidgetBase'; import { v, w } from '@dojo/framework/core/vdom'; import * as c from '@blockl...
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
import * as css from './ViewProjectDependence.m.css'; import ThemedMixin, { theme } from '@dojo/framework/core/mixins/Themed'; import I18nMixin from '@dojo/framework/core/mixins/I18n'; import WidgetBase from '@dojo/framework/core/WidgetBase'; import { v, w } from '@dojo/framework/core/vdom'; import * as c from '@blockl...
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
import * as css from './ViewProjectDependence.m.css'; import ThemedMixin, { theme } from '@dojo/framework/core/mixins/Themed'; import I18nMixin from '@dojo/framework/core/mixins/I18n'; import WidgetBase from '@dojo/framework/core/WidgetBase'; import { v, w } from '@dojo/framework/core/vdom'; import * as c from '@blockl...
// 当前只支持 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
exports.seed = function(knex, Promise) { return knex('questions') .del() .then(function() { return knex('questions').insert([ { id: 1, title: 'The Dress Code', question: 'You work in an office, performing a job that you find satisfying (and which compens...
response1: '0', response2: '0' }, { id: 20, title: 'Super Gorilla', question: 'Genetic engineers at Johns Hopkins University announce that they have developed a so-called super gorilla. Though the animal cannot speak, it has a sign-language l...
answer2: 'Dealbreaker!',
random_line_split
SgScriptEngine.py
# Copyright (c) 2013, Nathan Dunsworth - NFXPlugins # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list...
def buildSearchExpFilters(sgEntityFieldInfos, sgArgs, sgSearchExpSpans): ''' Builds the locial operator pattern from a search expression ''' ShotgunORM.LoggerScriptEngine.debug(' + Parsing spans: %(sgSearchExpSpans)s', {'sgSearchExpSpans': sgSearchExpSpans}) logicalConds = [] logicalOp = {'logica...
''' 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
# Copyright (c) 2013, Nathan Dunsworth - NFXPlugins # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list...
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
# Copyright (c) 2013, Nathan Dunsworth - NFXPlugins # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list...
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
# Copyright (c) 2013, Nathan Dunsworth - NFXPlugins # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list...
(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
# coding: utf-8 # # Purely electronic model of the Reaction Center # # Calculations of absorption spectra with a realistic lineshape theory # and with effective Gaussian lineshapes # # # # # In[1]: import os import numpy import quantarhei as qr print(qr.Manager().version) import matplotlib.pyplot as plt plt.switch_...
plt.figure(2) with qr.energy_units("1/cm"): #abss2.plot(axis=[10500, 15000, 0, 1.1], show=False) abs2.plot(axis=[10500, 15000, 0, 1.1], show=False) absexp2.plot(show=False) absexp2.savefig(os.path.join(pre_out, "abs_frac_eff.png"))
random_line_split
model_abs.py
# coding: utf-8 # # Purely electronic model of the Reaction Center # # Calculations of absorption spectra with a realistic lineshape theory # and with effective Gaussian lineshapes # # # # # In[1]: import os import numpy import quantarhei as qr print(qr.Manager().version) import matplotlib.pyplot as plt plt.switch_...
# # 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
#!/usr/bin/env python import rospy from std_msgs.msg import Int32 from geometry_msgs.msg import PoseStamped, TwistStamped from styx_msgs.msg import Lane, Waypoint import tf import math import time ''' This node will publish waypoints from the car's current position to some `x` distance ahead. As mentioned in the do...
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
#!/usr/bin/env python import rospy from std_msgs.msg import Int32 from geometry_msgs.msg import PoseStamped, TwistStamped from styx_msgs.msg import Lane, Waypoint import tf import math import time ''' This node will publish waypoints from the car's current position to some `x` distance ahead. As mentioned in the do...
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
#!/usr/bin/env python import rospy from std_msgs.msg import Int32 from geometry_msgs.msg import PoseStamped, TwistStamped from styx_msgs.msg import Lane, Waypoint import tf import math import time ''' This node will publish waypoints from the car's current position to some `x` distance ahead. As mentioned in the do...
pass def get_waypoint_velocity(self, waypoint): return waypoint.twist.twist.linear.x def set_waypoint_velocity(self, waypoints, waypoint, velocity): waypoints[waypoint].twist.twist.linear.x = velocity def distance(self, waypoints, wp1, wp2): dist = 0 dl = lambda a,...
def obstacle_cb(self, msg): # TODO: Callback for /obstacle_waypoint message. We will implement it later
random_line_split
waypoint_updater.py
#!/usr/bin/env python import rospy from std_msgs.msg import Int32 from geometry_msgs.msg import PoseStamped, TwistStamped from styx_msgs.msg import Lane, Waypoint import tf import math import time ''' This node will publish waypoints from the car's current position to some `x` distance ahead. As mentioned in the do...
(self, waypoints, wp1, wp2): dist = 0 dl = lambda a, b: math.sqrt((a.x-b.x)**2 + (a.y-b.y)**2 + (a.z-b.z)**2) for i in range(wp1, wp2+1): dist += dl(waypoints[wp1].pose.pose.position, waypoints[i].pose.pose.position) wp1 = i return dist def distance(self, po...
distance
identifier_name
lib.rs
//! # Bracket Parse //! //! A Utility for parsing Bracketed lists and sets of strings. //! //! It is a relatively lazy way of parsing items from a bracketed string, //! //! "hello(peter,dave)" is easy for it to handle, as are nested brackets. //! //! The above will result in something like //! //! >Branch[Leaf("hello...
#[test] fn test_head_tail(){ let b1 = Bracket::from_str("hello (andy dave)").unwrap(); match b1.head().match_str(){ "hello"=>{},//Where the actual code might go _=>panic!("Head is not hello leaf"), } } #[test] fn many_tails(){ ...
random_line_split
lib.rs
//! # Bracket Parse //! //! A Utility for parsing Bracketed lists and sets of strings. //! //! It is a relatively lazy way of parsing items from a bracketed string, //! //! "hello(peter,dave)" is easy for it to handle, as are nested brackets. //! //! The above will result in something like //! //! >Branch[Leaf("hello...
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
//! # Bracket Parse //! //! A Utility for parsing Bracketed lists and sets of strings. //! //! It is a relatively lazy way of parsing items from a bracketed string, //! //! "hello(peter,dave)" is easy for it to handle, as are nested brackets. //! //! The above will result in something like //! //! >Branch[Leaf("hello...
() { 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
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const color_1 = require("@oclif/color"); const command_1 = require("@oclif/command"); const cli_ux_1 = require("cli-ux"); const spawn = require("cross-spawn"); const fs = require("fs-extra"); const _ = require("lodash"); const path = require("...
// 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
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const color_1 = require("@oclif/color"); const command_1 = require("@oclif/command"); const cli_ux_1 = require("cli-ux"); const spawn = require("cross-spawn"); const fs = require("fs-extra"); const _ = require("lodash"); const path = require("...
() { 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
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const color_1 = require("@oclif/color"); const command_1 = require("@oclif/command"); const cli_ux_1 = require("cli-ux"); const spawn = require("cross-spawn"); const fs = require("fs-extra"); const _ = require("lodash"); const path = require("...
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
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const color_1 = require("@oclif/color"); const command_1 = require("@oclif/command"); const cli_ux_1 = require("cli-ux"); const spawn = require("cross-spawn"); const fs = require("fs-extra"); const _ = require("lodash"); const path = require("...
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
# Xingchen Wan 2018 | xingchen.wan@st-annes.ox.ac.uk import tensorflow as tf import numpy as np import matplotlib.pyplot as plt class RNN: """ Recurrent Neural Network """ def __init__(self, training_data, training_label, test_data, test_label, **options): ""...
(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
# Xingchen Wan 2018 | xingchen.wan@st-annes.ox.ac.uk import tensorflow as tf import numpy as np import matplotlib.pyplot as plt class RNN: """ Recurrent Neural Network """ def __init__(self, training_data, training_label, test_data, test_label, **options): ""...
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
# Xingchen Wan 2018 | xingchen.wan@st-annes.ox.ac.uk import tensorflow as tf import numpy as np import matplotlib.pyplot as plt class RNN: """ Recurrent Neural Network """ def __init__(self, training_data, training_label, test_data, test_label, **options): ""...
plt.plot(self.predict, label='Predictions') plt.plot(self.test_label, label='Test Labels') plt.title("Test label vs Prediction") plt.legend()
plt.subplot(122)
random_line_split
rnn.py
# Xingchen Wan 2018 | xingchen.wan@st-annes.ox.ac.uk import tensorflow as tf import numpy as np import matplotlib.pyplot as plt class RNN: """ Recurrent Neural Network """ def __init__(self, training_data, training_label, test_data, test_label, **options): ""...
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
package main import ( "bufio" "bytes" "crypto/sha1" "encoding/binary" "flag" "fmt" "io/ioutil" "os" "os/exec" "runtime" "runtime/debug" "strconv" "strings" "github.com/google/pprof/profile" ) var ( flagInput = flag.String("i", "perf.data", "input perf file") flagOutput = flag.String("o", "", "ou...
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
package main import ( "bufio" "bytes" "crypto/sha1" "encoding/binary" "flag" "fmt" "io/ioutil" "os" "os/exec" "runtime" "runtime/debug" "strconv" "strings" "github.com/google/pprof/profile" ) var ( flagInput = flag.String("i", "perf.data", "input perf file") flagOutput = flag.String("o", "", "ou...
(s *bufio.Scanner) []*Frame { var frames []*Frame for s.Scan() && s.Text() != "" { ln := s.Text() i := 0 for ; ln[i] == ' ' || ln[i] == '\t'; i++ { } pos := i for ; ln[i] != ' ' && ln[i] != '\t'; i++ { } pc, err := strconv.ParseUint(ln[pos:i], 16, 64) if err != nil { break } fn := ln[i+1:] ...
parseStack
identifier_name
main.go
package main import ( "bufio" "bytes" "crypto/sha1" "encoding/binary" "flag" "fmt" "io/ioutil" "os" "os/exec" "runtime" "runtime/debug" "strconv" "strings" "github.com/google/pprof/profile" ) var ( flagInput = flag.String("i", "perf.data", "input perf file") flagOutput = flag.String("o", "", "ou...
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
package main import ( "bufio" "bytes" "crypto/sha1" "encoding/binary" "flag" "fmt" "io/ioutil" "os" "os/exec" "runtime" "runtime/debug" "strconv" "strings" "github.com/google/pprof/profile" ) var ( flagInput = flag.String("i", "perf.data", "input perf file") flagOutput = flag.String("o", "", "ou...
{ fmt.Fprintf(os.Stderr, what+"\n", args...) os.Exit(1) }
identifier_body
simulation2_01.py
#Built-in Libraries import math from random import uniform from random import randrange import argparse import os import string import ctypes #external libraries import numpy import ogr import osr import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib.cm as cm import Image from matp...
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