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
tools.js
lowest; }, // returns float with 2 decimals calculateAvgPlusHighThreshold: function(avg_for_period, high_threshold) { return parseFloat((avg_for_period * (1 + high_threshold)).toFixed(2)); }, // returns float calculateAvgMinusLowThreshold: function(avg_for_period, low_threshold) { return parseFloat((avg_f...
} else {
random_line_split
tools.js
this.sum - this.sum_last + data_to_be_tested[len - 1].value_avg } this.sum_last = data_to_be_tested[0].value_avg; return parseFloat((this.sum/len).toFixed(2)); }, // return highest sell price // *****IT IS USING BUY PRICE! which should it be? calculateHigh: function(data_to_be_tested) { var highest = 0...
else { return; } if (sell) { return 'sell'; } else if (buy) { return 'buy'; } else { return 'do_nothing'; } }, calculateValuesForGivenPeriod: function(hrs_in_period, interval_in_minutes) { return ((hrs_in_period * 60) / interval_in_minutes); // 144 10-min incremetns in a 24 hr period) },...
{ var high_for_period = this.calculateHigh(data_to_be_tested) // get avg for period var low_for_period = this.calculateLow(data_to_be_tested) // get avg for period var high_minus_high_threshold = (high_for_period * (1 - high_threshold)).toFixed(2); var low_plus_low_threshold = (low_for_...
conditional_block
lib.rs
pub struct Keys<'a, K, V> { inner: Iter<'a, K, V>, } impl<'a, K, V> Iterator for Keys<'a, K, V> { type Item = &'a K; #[inline] fn next(&mut self) -> Option<&'a K> { self.inner.next().map(|(k, _)| k) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_...
// use alloc::vec::Vec; /// Iterator over the keys
random_line_split
lib.rs
Map`. #[inline] pub fn new() -> Self { Map::<K, V, AHasher>::default() } /// Create a `Map` with a given capacity #[inline] pub fn with_capacity(capacity: usize) -> Self { Map { store: Vec::with_capacity(capacity), hasher: PhantomData, } } } ...
(&self) -> Keys<'_, K, V> { Keys { inner: self.iter() } } /// An iterator visiting all values in arbitrary order. /// The iterator element type is `&'a V`. pub fn values(&self) -> Values<'_, K, V> { Values { inner: self.iter() } } /// Inserts a key-value pair into the map. ...
keys
identifier_name
lib.rs
: self.store.iter_mut(), } } /// Creates a raw entry builder for the HashMap. /// /// Raw entries provide the lowest level of control for searching and /// manipulating a map. They must be manually initialized with a hash and /// then manually searched. After this, insertions into a vac...
{ IterMut { inner: [].iter_mut(), } }
identifier_body
lib.rs
Hasher::default(); // let mut hasher = rustc_hash::FxHasher::default(); let mut hasher = H::default(); key.hash(&mut hasher); hasher.finish() } /// An iterator visiting all key-value pairs in insertion order. /// The iterator element type is `(&K, &V)`. /// /// # E...
{ continue; }
conditional_block
main_api_sentence.py
:param max_seq_length: :param tokenizer: 初始化后的tokenizer :param label_list: :return: """ examples = [] for guid, content in enumerate(contents): examples.append( InputExample(guid=guid, text_a=content)) features = convert_examples_to_features(examples, label_list, ma...
def load_examples(contents, max_seq_length, tokenizer, label_list, reverse_truncate=False): """ :param contents: eg: [('苹果很好用', '苹果')] 或者 [('苹果很好用', '苹果', '积极')]
random_line_split
main_api_sentence.py
= argparse.ArgumentParser() args = parser.parse_args() args.output_encoded_layers = True args.output_attention_layers = True args.output_att_score = True args.output_att_sum = True self.learning_rate = 2e-05 #学习率 warmup的比例 self.warmup_proportion = 0.1 ...
dataset, sampler=eval_sampler, batch_size=self.predict_batch_size) model.eval() model.to(self.device) # 起始时间 start_time = time.time() # 存储预测值 pred_logits = [] for batch in tqdm(eval_dataloader, desc="评估中", disable=True): input_ids, input_mask, segment_...
val_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_
conditional_block
main_api_sentence.py
最大的概率label preds = np.argmax(pred_logits, axis=1) if self.verbose: print(f"preds: {preds}") predictids = preds.tolist() #获取最大概率的可能性,即分数 pred_logits_softmax = scipy.special.softmax(pred_logits, axis=1) probability = np.max(pred_logits_softmax, axis=1) p...
identifier_name
main_api_sentence.py
parser = argparse.ArgumentParser() args = parser.parse_args() args.output_encoded_layers = True args.output_attention_layers = True args.output_att_score = True args.output_att_sum = True self.learning_rate = 2e-05 #学习率 warmup的比例 self.warmup_proportion = ...
print( f"--- 评估{len(eval_dataset)}条数据的总耗时是 {cost_time} seconds, 每条耗时 {cost_time / len(eval
= segment_ids.to(self.device) with torch.no_grad(): logits = model(input_ids, input_mask, segment_ids) cpu_logits = logits.detach().cpu() for i in range(len(cpu_logits)): pred_logits.append(cpu_logits[i].numpy()) pred_logits = np.array(pred_lo...
identifier_body
tf_train_loop.py
df_baseline = df_baseline.combine_first(truepos) else: df_baseline['latDeg'] = df_baseline['baseLatDeg'] df_baseline['lngDeg'] = df_baseline['baseLngDeg'] df_baseline['heightAboveWgs84EllipsoidM'] = df_baseline['baseHeightAboveWgs84EllipsoidM'] baseline_times = [] baseli...
phone_glob = next(os.walk(folder+"/"+track))[1] print(folder, track, end=' ') phones = {} phone_names = [] if "train" in folder: df_baseline = pd.read_csv("data/baseline_locations_train.csv") else: df_baseline = pd.read_csv("data/baseline_locations_test.csv") df...
identifier_body
tf_train_loop.py
df_baseline = df_baseline.combine_first(truepos) else: df_baseline['latDeg'] = df_baseline['baseLatDeg'] df_baseline['lngDeg'] = df_baseline['baseLngDeg'] df_baseline['heightAboveWgs84EllipsoidM'] = df_baseline['baseHeightAboveWgs84EllipsoidM'] baseline_times = [] baseline_ecef_coo...
shift_loss = tf.reduce_mean(tf.abs(shift1-shift2)) * 0.01 accel = derivative(speed) accel = tf.squeeze(accel) accel = tf.transpose(accel) accs_loss_large = tf.reduce_mean(tf.nn.relu(tf.abs(accel) - 4)) accs_loss_small = ...
shift2 = speed*0.5
random_line_split
tf_train_loop.py
data_file = pickle.load(f) except: data_file = None for phonepath in phone_glob: phone = phonepath phones[phone] = len(phones) phone_names.append(phone) print(phone, end=' ') if False: #data_file != None: model, times = tf_phone_model.createGpsPhone...
physics = 1.
conditional_block
tf_train_loop.py
_baseline = df_baseline.combine_first(truepos) else: df_baseline['latDeg'] = df_baseline['baseLatDeg'] df_baseline['lngDeg'] = df_baseline['baseLngDeg'] df_baseline['heightAboveWgs84EllipsoidM'] = df_baseline['baseHeightAboveWgs84EllipsoidM'] baseline_times = [] baseline_ecef_coords...
(optimizer, physics): for _ in range(16): with tf.GradientTape(persistent=True) as tape: total_loss_psevdo = 0 total_loss_delta = 0 accs_loss_large = 0 accs_loss_small = 0 speed_loss_small = 0 for i in r...
train_step_gnss
identifier_name
dashboard.go
", err) return nil, err } jsonBody, err := gabs.ParseJSON(bodyBuf) if err != nil
// 'set-cookie': ['t=UpnUzNztGWO7K8A%2BCYihZz056Bk%3D; Path=/; Expires=Sat, 16 Nov 2013 06:27:19 GMT', // 'un=mgoff%40appcelerator.com; Path=/; Expires=Sat, 16 Nov 2013 06:27:19 GMT', // 'sid=33f33a6b7f8fef7b0fc649654187d467; Path=/; Expires=Sat, 16 Nov 2013 06:27:19 GMT', // 'dvid=2019bea3-9e7b-48e3-890f-00e3...
{ log.Errorf("Failed to parse response body. %v", err) return nil, err }
conditional_block
dashboard.go
:= bson.M{ "username": username, "sid_360": sid_360, "cookie": cookie, } return saveDashboardSession(db_session) } func getAndVerifyOrgInfoFrom360(username, sid string) (haveAccess bool, orgs []models.Org, err error) { // reqTimeout := 20000; //20s //curl -i -b connect.sid=s%3AaJaL7IWQ_cDvmVBeQRY997hf....
findDashboardSession
identifier_name
dashboard.go
Vary: Accept-Encoding Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE Access-Control-Allow-Headers: Content-Type, api_key Content-Type: application/json; charset=utf-8 Content-Length: 59 Set-Cookie: connect.sid=s%3AIEpzWmzs4MQJGJMEcLmjlZm_.Cyi4LlO8gP%2...
{ log.Debugf("save dashboard session for user %v", session["username"]) _, err := mongo.UpsertDocument(mongo.STRATUS_DASHBOARD_SESSIONS_COLL, bson.M{"username": session["username"]}, session) if err != nil { log.Errorf("Failed to save dashboard session. %v", err) return err } log.Debugf("Upserted %v into ...
identifier_body
dashboard.go
, err error) { // reqTimeout := 20000; //20s //curl -i -b connect.sid=s%3AaJaL7IWQ_cDvmVBeQRY997hf.vVzLV2aFvrYiEKmfdTARTuHessesQ0Xm87JvFESaus http://dashboard.appcelerator.com/api/v1/user/organizations /* response for invalid session HTTP/1.1 401 Unauthorized X-Frame-Options: SAMEORIGIN Cache-Contr...
if err != nil { log.Errorf("Failed to find dashboard session. %v", err)
random_line_split
lib.rs
(); //! //! // start some readers //! let readers: Vec<_> = (0..4).map(|_| { //! let r = book_reviews_r.clone(); //! thread::spawn(move || { //! loop { //! let l = r.len(); //! if l == 0 { //! thread::yield_now(); //! } else { //! // th...
assert_stable
identifier_name
lib.rs
is atomic. //! assert_eq!(l, 4); //! break; //! } //! } //! }) //! }).collect(); //! //! // do some writes //! book_reviews_w.insert("Adventures of Huckleberry Finn", "My favorite book."); //! book_reviews_w.insert("Grimms' Fairy Tales", "Masterp...
{ Inner::with_capacity_and_hasher(self.meta, cap, self.hasher) }
conditional_block
lib.rs
`. //! //! ``` //! use std::thread; //! let (mut book_reviews_w, book_reviews_r) = evmap::new(); //! //! // start some readers //! let readers: Vec<_> = (0..4).map(|_| { //! let r = book_reviews_r.clone(); //! thread::spawn(move || { //! loop { //! let l = r.len(); //! if l == 0 ...
/// same inputs. For keys of type `K`, the result must also be consistent between different clones
random_line_split
lib.rs
book_reviews_w.insert("Grimms' Fairy Tales", "Masterpiece."); //! book_reviews_w.insert("Pride and Prejudice", "Very enjoyable."); //! book_reviews_w.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot."); //! // expose the writes //! book_reviews_w.publish(); //! //! // you can ...
{ let inner = if let Some(cap) = self.capacity { Inner::with_capacity_and_hasher(self.meta, cap, self.hasher) } else { Inner::with_hasher(self.meta, self.hasher) }; let (mut w, r) = left_right::new_from_empty(inner); w.append(write::Operation::MarkReady);...
identifier_body
results.js
(options) { // allow jQuery object to be passed in // in case a different version of jQuery is needed from the one globally defined $ = options.jQuery || $; // Init data // remove group not needed for the following visualizations var work_ = options.work; var groups_ = options.groups.filter(function(d) {...
AlmViz
identifier_name
results.js
@return {JQueryObject} */ var addSource_ = function(source, label, results, sourceTotalValue, group, subgroup, $groupRow) { var $row, $countLabel, $count, total = sourceTotalValue; $row = $groupRow .append("div") .attr("class", "alm-source") .attr("id", "source-" + source.id + "...
viz.svg.append("g") .attr("class", "y axis");
random_line_split
results.js
.attr("class", "alert alert-info") .text("There are currently no results"); return; } // Init basic options var baseUrl_ = options.baseUrl; var minItems_ = options.minItemsToShowGraph; var formatNumber_ = d3.format(",d"); // extract publication date // Construct date object from date par...
{ // allow jQuery object to be passed in // in case a different version of jQuery is needed from the one globally defined $ = options.jQuery || $; // Init data // remove group not needed for the following visualizations var work_ = options.work; var groups_ = options.groups.filter(function(d) { return d....
identifier_body
results.js
} else
// look to make sure browser support SVG var hasSVG_ = document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"); // to track if any metrics have been found var metricsFound_; /** * Initialize the visualization. * NB: needs to be accessible from the outside for i...
{ vizDiv = d3.select("#alm"); }
conditional_block
provider.go
: true, DefaultFunc: schema.EnvDefaultFunc("ARM_ENVIRONMENT", "public"), }, "skip_provider_registration": { Type: schema.TypeBool, Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_SKIP_PROVIDER_REGISTRATION", false), }, }, DataSourcesMap: map[string]*schema.Resource{ "azurerm_client_config": dataSourceArmClientConfig(), }, ResourcesMap: map[string]*schema.Resource{ // These resources use the Azure ARM SDK "azurerm_availability_set...
random_line_split
provider.go
StorageQueue(), "azurerm_storage_table": resourceArmStorageTable(), "azurerm_subnet": resourceArmSubnet(), "azurerm_template_deployment": resourceArmTemplateDeployment(), "azurerm_traffic_manager_endpoint": resourceArmTrafficManagerEndpoint(), "azurerm_traffic_manage...
{ switch s := v.(type) { case string: s = base64Encode(s) hash := sha1.Sum([]byte(s)) return hex.EncodeToString(hash[:]) default: return "" } }
identifier_body
provider.go
: true, DefaultFunc: schema.EnvDefaultFunc("ARM_ENVIRONMENT", "public"), }, "skip_provider_registration": { Type: schema.TypeBool, Optional: true, DefaultFunc: schema.EnvDefaultFunc("ARM_SKIP_PROVIDER_REGISTRATION", false), }, }, DataSourcesMap: map[string]*schema.Resource{ ...
(providerList []resources.Provider, client resources.ProvidersClient) error { var err error providerRegistrationOnce.Do(func() { providers := map[string]struct{}{ "Microsoft.Compute": struct{}{}, "Microsoft.Cache": struct{}{}, "Microsoft.ContainerRegistry": struct{}{}, "Microsoft.C...
registerAzureResourceProvidersWithSubscription
identifier_name
provider.go
: true, DefaultFunc: schema.EnvDefaultFunc("ARM_ENVIRONMENT", "public"), }, "skip_provider_registration": { Type: schema.TypeBool, Optional: true, DefaultFunc: schema.EnvDefaultFunc("ARM_SKIP_PROVIDER_REGISTRATION", false), }, }, DataSourcesMap: map[string]*schema.Resource{ ...
client.StopContext = p.StopContext() // replaces the context between tests p.MetaReset = func() error { client.StopContext = p.StopContext() return nil } // List all the available providers and their registration state to avoid unnecessary // requests. This also lets us check if the provider crede...
{ return nil, err }
conditional_block
saver.go
time.Time // Time the connection was initiated. Sequence int // Typically zero, but increments for long running connections. Expiration time.Time // Time we will swap files and increment Sequence. Writer io.WriteCloser } func newConnection(info *inetdiag.InetDiagMsg, timestamp time.Time) *Connection { ...
MarshalChans []MarshalChan Done *sync.WaitGroup // All marshallers will call Done on this. Connections map[uint64]*Connection ClosingStats map[uint64]TcpStats // BytesReceived and BytesSent for connections that are closing. ClosingTotals TcpStats cache *cache.Cache stats stats eventSer...
// TODO - just export an interface, instead of the implementation. type Saver struct { Host string // mlabN Pod string // 3 alpha + 2 decimal FileAgeLimit time.Duration
random_line_split
saver.go
.Time // Time the connection was initiated. Sequence int // Typically zero, but increments for long running connections. Expiration time.Time // Time we will swap files and increment Sequence. Writer io.WriteCloser } func newConnection(info *inetdiag.InetDiagMsg, timestamp time.Time) *Connection
// Rotate opens the next writer for a connection. // Note that long running connections will have data in multiple directories, // because, for all segments after the first one, we choose the directory // based on the time Rotate() was called, and not on the StartTime of the // connection. Long-running connections wi...
{ conn := Connection{Inode: info.IDiagInode, ID: info.ID.GetSockID(), UID: info.IDiagUID, Slice: "", StartTime: timestamp, Sequence: 0, Expiration: time.Now()} return &conn }
identifier_body
saver.go
.StartTime, }, } // FIXME: Error handling bytes, _ := json.Marshal(msg) conn.Writer.Write(bytes) conn.Writer.Write([]byte("\n")) } type stats struct { TotalCount int64 NewCount int64 DiffCount int64 ExpiredCount int64 } func (s *stats) IncTotalCount() { atomic.AddInt64(&s.TotalCount, 1) } func (...
{ idm, err := ar.RawIDM.Parse() if err != nil { log.Println("Closed:", ar.Timestamp.Format("15:04:05.000"), cookie, "idm parse error", stats) } else { log.Println("Closed:", ar.Timestamp.Format("15:04:05.000"), cookie, tcp.State(idm.IDiagState), stats) } closeLogCount-- }
conditional_block
saver.go
.Time // Time the connection was initiated. Sequence int // Typically zero, but increments for long running connections. Expiration time.Time // Time we will swap files and increment Sequence. Writer io.WriteCloser } func newConnection(info *inetdiag.InetDiagMsg, timestamp time.Time) *Connection { conn...
(host string, pod string, numMarshaller int, srv eventsocket.Server, anon anonymize.IPAnonymizer, ex *netlink.ExcludeConfig) *Saver { m := make([]MarshalChan, 0, numMarshaller) c := cache.NewCache() // We start with capacity of 500. This will be reallocated as needed, but this // is not a performance concern. con...
NewSaver
identifier_name
physical_plan.rs
(&self) -> Arc<Schema>; /// Specifies how data is partitioned across different nodes in the cluster fn output_partitioning(&self) -> Partitioning { Partitioning::UnknownPartitioning(0) } /// Specifies the data distribution requirements of all the children for this operator fn required_chil...
pub fn memory_size(&self) -> usize { self.columns.values().map(|c| c.memory_size()).sum() } } macro_rules! build_literal_array { ($LEN:expr, $BUILDER:ident, $VALUE:expr) => {{ let mut builder = $BUILDER::new($LEN); for _ in 0..$LEN { builder.append_value($VALUE)?; ...
}
random_line_split
physical_plan.rs
_literal_array!(*n, StringBuilder, value), other => Err(ballista_error(&format!( "Unsupported literal type {:?}", other ))), }, } } pub fn memory_size(&self) -> usize { //TODO delegate to Arrow once https://issu...
compile_aggregate_expressions
identifier_name
transaction.go
once = br.ReadU32LE() t.SystemFee = int64(br.ReadU64LE()) t.NetworkFee = int64(br.ReadU64LE()) t.ValidUntilBlock = br.ReadU32LE() nsigners := br.ReadVarUint() if br.Err != nil { return } if nsigners > MaxAttributes { br.Err = errors.New("too many signers") return } else if nsigners == 0 { br.Err = error...
isValid
identifier_name
transaction.go
VarUint() if nattrs > MaxAttributes-nsigners { br.Err = errors.New("too many attributes") return } t.Attributes = make([]Attribute, nattrs) for i := 0; i < int(nattrs); i++ { t.Attributes[i].DecodeBinary(br) } t.Script = br.ReadVarBytes(MaxScriptLength) if br.Err == nil { br.Err = t.isValid() } if buf ...
{ if t.Signers[i].Account.Equals(t.Signers[j].Account) { return ErrNonUniqueSigners } }
conditional_block
transaction.go
Version uint8 // Random number to avoid hash collision. Nonce uint32 // Fee to be burned. SystemFee int64 // Fee to be distributed to consensus nodes. NetworkFee int64 // Maximum blockchain height exceeding which // transaction should fail verification. ValidUntilBlock uint32 // Code to run in NeoVM for...
// The trading version which is currently 0.
random_line_split
transaction.go
Attributes []Attribute // Transaction signers list (starts with Sender). Signers []Signer // The scripts that comes with this transaction. // Scripts exist out of the verification script // and invocation script. Scripts []Witness // size is transaction's serialized size. size int // Hash of the transactio...
// GetAttributes returns the list of transaction's attributes of the given type. // Returns nil in case if attributes not found. func (t *Transaction) GetAttributes(typ AttrType) []Attribute { var result []Attribute for _, attr := range t.Attributes { if attr.Type == typ { result = append(result, attr) } } ...
{ for i := range t.Attributes { if t.Attributes[i].Type == typ { return true } } return false }
identifier_body
time_zones.rs
Formatter) -> fmt::Result { write!(formatter, "LocalTimeConversionError") } } /// Implemented for time zones where `LocalTimeConversionError` never occurs, /// namely for `Utc` and `FixedOffsetFromUtc`. /// /// Any UTC-offset change in a time zone creates local times that either don’t occur or occur twice....
FixedOffsetFromUtc { FixedOffsetFromUtc::from_hours_and_minutes(1, 0) } fn offset_during_dst(&self) -> FixedOffsetFromUtc { FixedOffsetFromUtc::from_hours_and_minutes(2, 0) } fn is_in_dst(&self, t: UnixTimestamp) -> bool { use Month::*; let d = DateTime::from_timestamp...
ide_dst(&self) ->
identifier_name
time_zones.rs
fn to_timestamp(&self, d: &NaiveDateTime) -> Result<UnixTimestamp, LocalTimeConversionError>; } /// When a time zone makes clock jump forward or back at any instant in time /// (for example twice a year with daylight-saving time, a.k.a. summer-time period) /// This error is returned when either: /// /// * Clocks w...
pub trait TimeZone { fn from_timestamp(&self, t: UnixTimestamp) -> NaiveDateTime;
random_line_split
selector.rs
Err(io::Error::new( io::ErrorKind::InvalidInput, "Most-significant bit of token must remain unset.", )); } Ok(match reg_type { RegType::Fd => key, RegType::Handle => key | msb, }) } fn token_and_type_from_key(key: u64) -> (Token, RegType) { let msb = 1u...
.push(Event::new(epoll_event_to_ready(events), token)); Ok(false) } } } /// Register event interests for the given IO handle with the OS pub fn register_fd( &self, handle: &zircon::Handle, fd: &EventedFd, token: Token, ...
random_line_split
selector.rs
(io::Error::new( io::ErrorKind::InvalidInput, "Most-significant bit of token must remain unset.", )); } Ok(match reg_type { RegType::Fd => key, RegType::Handle => key | msb, }) } fn token_and_type_from_key(key: u64) -> (Token, RegType) { let msb = 1u64 <...
(&self) -> &Arc<zircon::Port> { &self.port } /// Reregisters all registrations pointed to by the `tokens_to_rereg` list /// if `has_tokens_to_rereg`. fn reregister_handles(&self) -> io::Result<()> { // We use `Ordering::Acquire` to make sure that we see all `tokens_to_rereg` // ...
port
identifier_name
selector.rs
(io::Error::new( io::ErrorKind::InvalidInput, "Most-significant bit of token must remain unset.", )); } Ok(match reg_type { RegType::Fd => key, RegType::Handle => key | msb, }) } fn token_and_type_from_key(key: u64) -> (Token, RegType) { let msb = 1u64 <...
None => zircon::ZX_TIME_INFINITE, }; let packet = match self.port.wait(deadline) { Ok(packet) => packet, Err(zircon::Status::ErrTimedOut) => return Ok(false), Err(e) => Err(e)?, }; let observed_signals = match packet.contents() { ...
{ let nanos = duration .as_secs() .saturating_mul(1_000_000_000) .saturating_add(duration.subsec_nanos() as u64); zircon::deadline_after(nanos) }
conditional_block
selector.rs
RegType) { let msb = 1u64 << 63; ( Token((key & !msb) as usize), if (key & msb) == 0 { RegType::Fd } else { RegType::Handle }, ) } /// Each Selector has a globally unique(ish) ID associated with it. This ID /// gets tracked by `TcpStream`, `TcpListen...
{ self.token_to_fd.lock().unwrap().remove(&token); // We ignore NotFound errors since oneshots are automatically deregistered, // but mio will attempt to deregister them manually. self.port .cancel(&*handle, token.0 as u64) .map_err(io::Error::from) ....
identifier_body
policy_distillation.py
_size, self.hidden_size), nn.ReLU(inplace=True), nn.Linear(self.hidden_size, self.output_size) ) def forward(self, input): input = input.view(-1, self.input_size) return F.softmax(self.fc(input), dim=1) ...
(self, save_path, _locals=None): assert self.model is not None, "Error: must train or load model before use" with open(save_path, "wb") as f: pickle.dump(self.__dict__, f) @classmethod def load(cls, load_path, args=None): with open(load_path, "rb") as f: class_di...
save
identifier_name
policy_distillation.py
, img_shape=img_shape) def forward(self, input): return F.softmax(self.model(input), dim=1) class PolicyDistillationModel(BaseRLObject): """ Implementation of PolicyDistillation """ def __init__(self): super(PolicyDistillationModel, self).__init__() def save(self, save_path, ...
param.requires_grad = True learnable_params += [param for param in self.srl_model.model.parameters()] learning_rate = 1e-3
random_line_split
policy_distillation.py
_size, self.hidden_size), nn.ReLU(inplace=True), nn.Linear(self.hidden_size, self.output_size) ) def forward(self, input): input = input.view(-1, self.input_size) return F.softmax(self.fc(input), dim=1) ...
def getActionProba(self, observation, dones=None, delta=0): """ returns the action probability distribution, from a given observation. :param observation: (numpy int or numpy float) :param dones: ([bool]) :param delta: (numpy float or float) The exploration noise applied to...
parser.add_argument('--nothing4instance', help='Number of population (each one has 2 threads)', type=bool, default=True) return parser
identifier_body
policy_distillation.py
_size, self.hidden_size), nn.ReLU(inplace=True), nn.Linear(self.hidden_size, self.output_size) ) def forward(self, input): input = input.view(-1, self.input_size) return F.softmax(self.fc(input), dim=1) ...
observation = th.from_numpy(observation).float().requires_grad_(False).to(self.device) if sample: proba_actions = self.model.forward(observation).detach().cpu().numpy().flatten() return np.random.choice(range(len(proba_actions)), 1, p=proba_actions) else: re...
observation = np.transpose(observation, (0, 3, 2, 1))
conditional_block
WarpController.ts
Name: 'InitialReporterRedeemed' }, { databaseName: 'InitialReportSubmitted' }, { databaseName: 'InitialReporterTransferred' }, { databaseName: 'MarketCreated' }, { databaseName: 'MarketFinalized' }, { databaseName: 'MarketMigrated' }, { databaseName: 'MarketParticipantsDisavowed' }, { databaseName: 'Marke...
{ return this.db.warpCheckpoints.getMostRecentCheckpoint(); }
identifier_body
WarpController.ts
{ Checkpoints } from './Checkpoints'; export const WARPSYNC_VERSION = '1'; const FILE_FETCH_TIMEOUT = 30000; // 10 seconds type NameOfType<T, R> = { [P in keyof T]: T[P] extends R ? P : never; }[keyof T]; type AllDBNames = NameOfType<DB, Dexie.Table<Log, unknown>>; type AllDbs = { [P in AllDBNames]: DB[P] exten...
await this.db.warpCheckpoints.createInitialCheckpoint( await this.provider.getBlock(this.uploadBlockNumber), market ); } } async destroyAndRecreateDB() { await this.db.delete(); await this.db.initializeDB(); } async createCheckpoint(endBlock: Block): Promise<IpfsInfo>...
{ console.log( `Warp sync market not initialized for current universe ${this.augur.contracts.universe.address}.` ); return; }
conditional_block
WarpController.ts
{ Checkpoints } from './Checkpoints'; export const WARPSYNC_VERSION = '1'; const FILE_FETCH_TIMEOUT = 30000; // 10 seconds type NameOfType<T, R> = { [P in keyof T]: T[P] extends R ? P : never; }[keyof T]; type AllDBNames = NameOfType<DB, Dexie.Table<Log, unknown>>; type AllDbs = { [P in AllDBNames]: DB[P] exten...
} onNewBlock = async (newBlock: Block): Promise<string | void> => { await this.createInitialCheckpoint(); /* 0. Base case: need to have created initial warp checkpoint. 1. Check if we need to create warp sync 1. This will happen if the active market endTime has elapsed 2. Check if...
async getIpfs(): Promise<IPFS> { return this.ipfs;
random_line_split
WarpController.ts
{ Checkpoints } from './Checkpoints'; export const WARPSYNC_VERSION = '1'; const FILE_FETCH_TIMEOUT = 30000; // 10 seconds type NameOfType<T, R> = { [P in keyof T]: T[P] extends R ? P : never; }[keyof T]; type AllDBNames = NameOfType<DB, Dexie.Table<Log, unknown>>; type AllDbs = { [P in AllDBNames]: DB[P] exten...
() { await this.db.delete(); await this.db.initializeDB(); } async createCheckpoint(endBlock: Block): Promise<IpfsInfo> { const logs = []; for (const { databaseName } of databasesToSync) { // Awaiting here to reduce load on db. logs.push( await this.db[databaseName] .w...
destroyAndRecreateDB
identifier_name
worker.go
if it is not, it is not clear // why, because the name is delegated to this server according to the parent zone, so we assume that this server // is broken, but there might be other reasons for this that I can't think off from the top of my head. return nil, errors.NewErrorStack(fmt.Errorf("resolveFromWith: got ...
random_line_split
worker.go
about all other records that might resides here. return nameresolver.NewAliasEntry(w.req.Name(), rr.Target), nil } } } // We now query for the AAAA records to also get the IPv6 addresses clnt = new(dns.Client) clnt.Net = proto maaaa := new(dns.Msg) maaaa.SetEdns0(4096, false) maaaa.SetQuestion(w.req....
{ err.Push(fmt.Errorf("resolve: error while getting zone cut info of %s for %s", reqName, w.req.Name())) return nil, err }
conditional_block
worker.go
// newWorker builds a new worker instance and returns it. // The worker is started and will resolve the request from a cache file. func newWorkerWithCachedResult(req *nameresolver.Request, nrHandler func(*nameresolver.Request) *errors.ErrorStack, zcHandler func(*zonecut.Request) *errors.ErrorStack, cf *nameresolver.C...
{ w := initNewWorker(req, nrHandler, zcHandler, conf) w.start() return w }
identifier_body
worker.go
to the requested topic, or an // definitive error that happened during the resolution. func (w *worker) resolveFromWith(ip net.IP, proto string) (*nameresolver.Entry, *errors.ErrorStack) { var ipList []net.IP // We first query about the IPv4 addresses associated to the request topic. clnt := new(dns.Client) clnt....
resolveFromGluelessNameSrvs
identifier_name
project_tasks.py
from ConfigParser import ConfigParser, NoSectionError # noinspection PyUnresolvedReferences from herring.herring_app import task, HerringFile # noinspection PyUnresolvedReferences from herringlib.simple_logger import info, debug # noinspection PyUnresolvedReferences from herringlib.local_shell import LocalShell #...
(): """Show all project settings with descriptions""" keys = Project.__dict__.keys() for key in sorted(keys): value = Project.__dict__[key] if key in ATTRIBUTES: attrs = ATTRIBUTES[key] required = False if 'required' in attrs: if attrs['req...
describe
identifier_name
project_tasks.py
from ConfigParser import ConfigParser, NoSectionError # noinspection PyUnresolvedReferences from herring.herring_app import task, HerringFile # noinspection PyUnresolvedReferences from herringlib.simple_logger import info, debug # noinspection PyUnresolvedReferences from herringlib.local_shell import LocalShell #...
@task(namespace='project', configured='optional') def describe(): """Show all project settings with descriptions""" keys = Project.__dict__.keys() for key in sorted(keys): value = Project.__dict__[key] if key in ATTRIBUTES: attrs = ATTRIBUTES[key] required = False ...
"""Show all project settings""" info(str(Project))
identifier_body
project_tasks.py
from ConfigParser import ConfigParser, NoSectionError # noinspection PyUnresolvedReferences from herring.herring_app import task, HerringFile # noinspection PyUnresolvedReferences from herringlib.simple_logger import info, debug # noinspection PyUnresolvedReferences from herringlib.local_shell import LocalShell #...
@task(namespace='project', configured='optional') def show(): """Show all project settings""" info(str(Project)) @task(namespace='project', configured='optional') def describe(): """Show all project settings with descriptions""" keys = Project.__dict__.keys() for key in sorted(keys): va...
defaults = _project_defaults() template = Template() for template_dir in [os.path.abspath(os.path.join(herringlib, 'herringlib', 'templates')) for herringlib in HerringFile.herringlib_paths]: info("template directory: %s" % template_dir) # noinspec...
conditional_block
project_tasks.py
except ImportError: # python2 # noinspection PyUnresolvedReferences,PyCompatibility from ConfigParser import ConfigParser, NoSectionError # noinspection PyUnresolvedReferences from herring.herring_app import task, HerringFile # noinspection PyUnresolvedReferences from herringlib.simple_logger import info,...
try: # python3 # noinspection PyUnresolvedReferences,PyCompatibility from configparser import ConfigParser, NoSectionError
random_line_split
container.go
&Container{ logger: logger, Name: name, runtime: runtime, client: client, } } // MakeContainer constructs a suitable Container object. // // The runtime used is determined by the runtime flag. // // Containers will check flags for profiling requests. func MakeContainer(ctx context.Context, logger testut...
(r RunOpts, args []string) *container.Config { ports := nat.PortSet{} for _, p := range r.Ports { port := nat.Port(fmt.Sprintf("%d", p)) ports[port] = struct{}{} } env := append(r.Env, fmt.Sprintf("RUNSC_TEST_NAME=%s", c.Name)) return &container.Config{ Image: testutil.ImageByName(r.Image), Cmd: ...
config
identifier_name
container.go
&Container{ logger: logger, Name: name, runtime: runtime, client: client, } } // MakeContainer constructs a suitable Container object. // // The runtime used is determined by the runtime flag. // // Containers will check flags for profiling requests. func MakeContainer(ctx context.Context, logger testut...
return makeContainer(ctx, logger, unsandboxedRuntime) } // Spawn is analogous to 'docker run -d'. func (c *Container) Spawn(ctx context.Context, r RunOpts, args ...string) error { if err := c.create(ctx, r.Image, c.config(r, args), c.hostConfig(r), nil); err != nil { return err } return c.Start(ctx) } // SpawnP...
func MakeNativeContainer(ctx context.Context, logger testutil.Logger) *Container { unsandboxedRuntime := "runc" if override, found := os.LookupEnv("UNSANDBOXED_RUNTIME"); found { unsandboxedRuntime = override }
random_line_split
container.go
Container{ logger: logger, Name: name, runtime: runtime, client: client, } } // MakeContainer constructs a suitable Container object. // // The runtime used is determined by the runtime flag. // // Containers will check flags for profiling requests. func MakeContainer(ctx context.Context, logger testutil...
return nil } // Stop is analogous to 'docker stop'. func (c *Container) Stop(ctx context.Context) error { return c.client.ContainerStop(ctx, c.id, container.StopOptions{}) } // Pause is analogous to'docker pause'. func (c *Container) Pause(ctx context.Context) error { return c.client.ContainerPause(ctx, c.id) } ...
{ if err := c.profile.Start(c); err != nil { c.logger.Logf("profile.Start failed: %v", err) } }
conditional_block
container.go
Container{ logger: logger, Name: name, runtime: runtime, client: client, } } // MakeContainer constructs a suitable Container object. // // The runtime used is determined by the runtime flag. // // Containers will check flags for profiling requests. func MakeContainer(ctx context.Context, logger testutil...
// RootDirectory returns an educated guess about the container's root directory. func (c *Container) RootDirectory() (string, error) { // The root directory of this container's runtime. rootDir := fmt.Sprintf("/var/run/docker/runtime-%s/moby", c.runtime) _, err := os.Stat(rootDir) if err == nil { return rootDir...
{ return c.id }
identifier_body
combine.py
# If nothing was found then don't continue, this can happen if no mp4 files are found or if only the joined file is found if( len(file_infos) <= 0 ): print( "No mp4 video files found matching '{0}'".format(args.match)) sys.exit(0) print("Found {0} files".format(len(file_infos))) # If the...
file_infos.append(m4b_fileinfo)
conditional_block
combine.py
dur'] # Do we have a proposed cut duration, if so then we must use this info # to correct the chapter locations if not cuts is None and file_name in cuts and 't' in cuts[file_name]: file_info_dur = timedelta(seconds=cuts[file_name]['t']) chapters.append({"name": Path(file_info['f...
print("Command {0} returned non-zero exit status {1}.".format(proc_cmd, ret.returncode)) print("File {0} will be skipped".format(file_name)) return None #ret.check_returncode() # Computed Duration 00:23:06.040 - Indicated Duration 00:23:06.040 match = regex_mp4box_duration.search( ret.stdout ) hrs ...
random_line_split
combine.py
error raise ValueError('Could not locate FFMPEG install, please use the --ffmpeg switch to specify the path to the ffmpeg.exe file on your system.') # # Returns an array of files matching the grep string passed in def getFileNamesFromGrepMatch(grep_match, path_out_file): in_files = glob.glob(grep_match.replace("...
path_video_file.exists(): raise ValueError("Video file {0} could not be found. Nothing was split.".format(path_video_file)) # Construct the args to mp4box prog_args = [mp4box_path] # Specify the maximum split size prog_args.append("-splits") prog_args.append(str(max_out_size_kb)) # Overwrite the def...
identifier_body
combine.py
CombinedVideoFile(video_files, chapters, cumulative_dur, cumulative_size, mp4exec, ffmpegexec, path_out_file, path_chapters_file, args.overwrite, cuts, args.videosize, args.burnsubs, max_out_size_kb, args.noaudio ) print(Colors.success("Script completed successfully, bye!")) finally: deinit() #Deinitiali...
getFileNamesFromGrepMatch
identifier_name
window.rs
new( grid_id: u64, window_type: WindowType, anchor_info: Option<AnchorInfo>, grid_position: (f64, f64), grid_size: (u64, u64), draw_command_batcher: Arc<DrawCommandBatcher>, ) -> Window { let window = Window { grid_id, grid: CharacterG...
pub fn redraw(&self) { self.send_command(WindowDrawCommand::Clear); // Draw the lines from the bottom up so that underlines don't get overwritten by the line // below. for row in (0..self.grid.height).rev() { self.redraw_line(row); } } pub fn hide(&self...
{ self.grid.clear(); self.send_command(WindowDrawCommand::Clear); }
identifier_body
window.rs
new( grid_id: u64, window_type: WindowType, anchor_info: Option<AnchorInfo>, grid_position: (f64, f64), grid_size: (u64, u64), draw_command_batcher: Arc<DrawCommandBatcher>, ) -> Window { let window = Window { grid_id, grid: CharacterG...
(&self, command: WindowDrawCommand) { self.draw_command_batcher .queue(DrawCommand::Window { grid_id: self.grid_id, command, }) .ok(); } fn send_updated_position(&self) { self.send_command(WindowDrawCommand::Position { ...
send_command
identifier_name
window.rs
new( grid_id: u64, window_type: WindowType, anchor_info: Option<AnchorInfo>, grid_position: (f64, f64), grid_size: (u64, u64), draw_command_batcher: Arc<DrawCommandBatcher>, ) -> Window { let window = Window { grid_id, grid: CharacterG...
self.redraw_line(row); if row > 0 { self.redraw_line(row - 1); } } else { warn!("Draw command out of bounds"); } } pub fn scroll_region( &mut self, top: u64, bottom: u64, left: u64, right: u...
{ self.redraw_line(row + 1); }
conditional_block
window.rs
fn new( grid_id: u64, window_type: WindowType, anchor_info: Option<AnchorInfo>, grid_position: (f64, f64), grid_size: (u64, u64), draw_command_batcher: Arc<DrawCommandBatcher>, ) -> Window { let window = Window { grid_id, grid: Charact...
} let line_fragment = LineFragment { text, window_left: start, window_top: row_index, width, style: style.clone(), }; (start + width, line_fragment) } // Redraw line by calling build_line_fragment starting at 0 //...
} // Add the grid cell to the cells to render. text.push_str(character);
random_line_split
Projeto.py
icao, s tem de ser str # de tamanho 1, e verificacao_letras_mgc tem de ser verdadeiro if not e_pos (p) or not isinstance (s, str) or len(s) != 1 or not verificacao_letras_mgc (letras, mgc): raise ValueError ('gera_chave_espiral: argumentos errados') # Transforma em lista para poder ser...
(arg): ''' para ser do tipo chave tem de ser uma lista constituida por 5 listas cada uma com 5 elementos que sejam letras maiusculas unicas''' if len (arg) !=
e_chave
identifier_name
Projeto.py
return c # RECONHECEDORES # e_chave: arg --> Boolean # e_chave(arg): devolve True se o argumento arg for do tipo chave e Falso caso contrario def e_chave (arg): ''' para ser do tipo chave tem de ser uma lista constituida por 5 listas cada uma com 5 elementos que sejam letras maiusculas unicas''' if ...
# codifica_r: posicao + posicao --> posicao + posicao # codifica_r (pos1, pos2) recebe dois argumentos, pos1, pos2, consistindo nas # posicoes das letras de um digrama numa chave. Estas posicoes encontra-se
random_line_split
Projeto.py
Verifica cada caracter dentro de mgc for i in range (len( mgc)): # Testa se o caracter nao esta ja em r e se esta em letras if not mgc[i] in r and mgc[i] in letras: # Se sim, junta-o a r r += [mgc[i]] # Remove de letras esse car...
if not ( 64 < ord(b) < 91): return False
conditional_block
Projeto.py
: return ('r',) + t # codifica_l: posicao + posicao + {-1,1} --> posicao + posicao # codifica_l (pos1, pos2, inc) recebe tres argumentos, pos1, pos2, # consistindo nas posicoes das letras de um digrama na mesma linha de uma # chave, e o inteiro inc, que podera ser 1 (encriptar) ou -1 (desencriptar...
mens = digramas (mens) r = '' # Codifica os caracteres dois a dois for i in range (0, len(mens)-1, 2): # Chama codifica_digrama que devolve dois caracteres codificados r += codifica_digrama (mens[i:i+2], chave, inc) return r
identifier_body
NEF_tester.py
") plotrange(lambda x: target(valtopair(x)),xmin,xmax,resolution,"target values") # plotrange(lambda x:Error(layer.getaverage(valtopair(x)),target(valtopair(x)),1),xmin,xmax,resolution,"error") ervals = [SQError(layer.getaverage(valtopair(x)),target(valtopair(x)),1) for x in [x/float(resolution) for x in ran...
def initplot(layer): x = -2 t = target(x) for a in range(int(0.5/deltaT)): tvals.append(a*deltaT) xhatvals.append(layer.Process(x,deltaT)) x = -1 for a in range(int(0.5/deltaT)): tvals.append(0.5+a*deltaT) xhatvals.append(layer.Process(x,deltaT)) x = 1 for a...
yvals = [neuron.a(x) for x in xvals] vallist = zip(map(pairtoval,xvals),yvals) vallist.sort(key = lambda x:x[0]) xvals = [x[0] for x in vallist] yvals = [x[1] for x in vallist] plt.plot(xvals,yvals)
identifier_body
NEF_tester.py
(p,target,deltaT): return -(target-p)**2 def sigmoid(er): return er # return (2.0/(1.0+exp(-2*er))-1.0) targetname = "target" def weight_histogram(layer,binnum=None): weights = [reduce(lambda x,synapse:x+synapse.inhibitory*synapse.Pval(),neuron.synapses,0) for neuron in layer.layer] if(binnum =...
SQError
identifier_name
NEF_tester.py
") plotrange(lambda x: target(valtopair(x)),xmin,xmax,resolution,"target values") # plotrange(lambda x:Error(layer.getaverage(valtopair(x)),target(valtopair(x)),1),xmin,xmax,resolution,"error") ervals = [SQError(layer.getaverage(valtopair(x)),target(valtopair(x)),1) for x in [x/float(resolution) for x in ran...
plt.show() if(presolve): NEF.LeastSquaresSolve(xvals,target,layer,regularization=1000) if(lstsq): weight_histogram(layer,binnum=50) plt.savefig("weight-histogram-"+str(numxvals)+"samples-"+str(layersize)+"neurons") plt.show() plotavs(layer,-400,400,1,savename = "cm-agnostic-decode-"+str(numxvals)...
if(lstsq): plt.savefig("noisytuning-"+str(numxvals)+"samples-"+str(layersize)+"neurons")
random_line_split
NEF_tester.py
plt.title("Noisy Tuning Curves") if(lstsq): plt.savefig("noisytuning-"+str(numxvals)+"samples-"+str(layersize)+"neurons") plt.show() if(presolve): NEF.LeastSquaresSolve(xvals,target,layer,regularization=1000) if(lstsq): weight_histogram(layer,binnum=50) plt.savefig("weight-histogram-"+str(numxvals)+"...
v = "0p4"
conditional_block
main.py
SPAM_DATA/trec07p/data'.format("/media/sumeet/147A710C7A70EBBC") _SPAM_EMAIL_LABELS_PATH = '{}/SPAM_DATA/trec07p/full/index'.format("/media/sumeet/147A710C7A70EBBC") _CACHED_FEATURE_INDEX_NAME_TEMPLATE = 'feature_matrix_cache/{}-{}-feature_index.json' _CACHED_FEATURES_FILE_PATH_TEMPLATE = 'feature_matrix_ca...
(min_df=0.02, max_df=0.95): min_df_value = int(min_df * len(corpus)) max_df_value = int(max_df * len(corpus)) _valid_ngrams = set() for ngram, no_of_documents in all_ngrams.items(): if min_df_value < no_of_documents < max_df_value: _val...
_get_valid_ngrams
identifier_name
main.py
SPAM_DATA/trec07p/data'.format("/media/sumeet/147A710C7A70EBBC") _SPAM_EMAIL_LABELS_PATH = '{}/SPAM_DATA/trec07p/full/index'.format("/media/sumeet/147A710C7A70EBBC") _CACHED_FEATURE_INDEX_NAME_TEMPLATE = 'feature_matrix_cache/{}-{}-feature_index.json' _CACHED_FEATURES_FILE_PATH_TEMPLATE = 'feature_matrix_ca...
else: _helper(body) return parsed_email @classmethod def _get_email_contents_and_labels(cls, email_files, labels_dict, token_filter): ix = 1 email_contents = [] labels = [] for cleaned_email in cls._get_emails(email_files): ix += 1 ...
_helper(part)
conditional_block
main.py
import random import re import string from collections import defaultdict from typing import Dict import numpy as np from bs4 import BeautifulSoup from nltk import SnowballStemmer from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from scipy.sparse import csr_matrix from sklearn.datasets import ...
import os
random_line_split
main.py
SPAM_DATA/trec07p/data'.format("/media/sumeet/147A710C7A70EBBC") _SPAM_EMAIL_LABELS_PATH = '{}/SPAM_DATA/trec07p/full/index'.format("/media/sumeet/147A710C7A70EBBC") _CACHED_FEATURE_INDEX_NAME_TEMPLATE = 'feature_matrix_cache/{}-{}-feature_index.json' _CACHED_FEATURES_FILE_PATH_TEMPLATE = 'feature_matrix_ca...
@classmethod def _clean_email(cls, raw_email: Email) -> Email: raw_email.cleaned_subject_tokens = cls._text_cleaning_helper(raw_email.subject) raw_email.cleaned_body_tokens = cls._text_cleaning_helper(raw_email.body) return raw_email @classmethod def _get_emails(cls, email_fil...
cleaned_tokens = [] tokens = word_tokenize(text_to_clean) for token in tokens: lowered_token = token.lower() stripped_token = lowered_token.translate(cls._PUNCTUATION_TABLE) if stripped_token.isalpha() and stripped_token not in cls._STOPWORDS_SET: clea...
identifier_body
func.py
def rankdata(arr, axis=None): "Slow rankdata function used for unaccelerated ndim/dtype combinations." arr = np.asarray(arr) if axis is None: arr = arr.ravel() axis = 0 elif axis < 0: axis = range(arr.ndim)[axis] y = np.empty(arr.shape) itshape = list(arr.shape) its...
"Slow nanargmax function used for unaccelerated ndim/dtype combinations." with warnings.catch_warnings(): warnings.simplefilter("ignore") return np.nanargmax(arr, axis=axis)
identifier_body
func.py
itshape): ijslice = list(ij[:axis]) + [slice(None)] + list(ij[axis:]) x1d = arr[ijslice].astype(float) mask1d = ~np.isnan(x1d) x1d[mask1d] = scipy_rankdata(x1d[mask1d]) y[ijslice] = x1d return y def ss(arr, axis=0): "Slow sum of squares used for unaccelerated ndim/dtype ...
return a_min, a_max,
var *= non_nans / d
conditional_block
func.py
_max = np.nanmin(arr), np.nanmax(arr) if weights is None: nans = np.sum(np.isnan(arr)) non_nans = len(arr) - nans mean = np.nansum(arr) / non_nans var = np.nansum((arr - mean) ** 2) / (non_nans - 1) else: tot_w = np.sum(weights) nan...
_chk_asarray
identifier_name
func.py
itshape): ijslice = list(ij[:axis]) + [slice(None)] + list(ij[axis:]) x1d = arr[ijslice].astype(float) mask1d = ~np.isnan(x1d) x1d[mask1d] = scipy_rankdata(x1d[mask1d]) y[ijslice] = x1d return y def ss(arr, axis=0): "Slow sum of squares used for unaccelerated ndim/dtype ...
d = d.sum(axis) idx = np.argmin(d) return np.sqrt(d[idx]), idx def partsort(arr, n, axis=-1): "Slow partial sort used for unaccelerated ndim/dtype combinations." return np.sort(arr, axis) def argpartsort(arr, n, axis=-1): "Slow partial argsort used for unaccelerated ndim/dtype combinations." ...
random_line_split
yintai.js
},400); animate(shangzuos[0],{width:x},400); animate(xiayous[0],{width:x},400); } zw4s.onmouseout=function(){ animate(zuoshangs[0],{height:0},400); animate(youxias[0],{height:0},400); animate(shangzuos[0],{width:0},400); animate(xiayous[0],{width:0},400); } } // 热门品牌动画 var zw4s=$('.zhengwen4') for (v...
var wxs=$('.shouji')[0]; var hys=$(".shoujji")[0];
random_line_split
yintai.js
{index=0}; // 循环遍历 for (var i = 0; i < as.length; i++) { // 先把所有照片层级调低,轮播点的颜色为空 as[i].style.zIndex=0; bodiandiv[i].style.background=''; }; as[index].style.zIndex=10; bodiandiv[index].style.background='#e5004f'; } box[0].onmouseover=function(){ clearInterval(t); lrclickbox.style...
th)
identifier_name
yintai.js
}; // 时尚名品无缝轮播模式图模式 var box=$('.shishang7'); for(var i=0;i<box.length;i++){ fengzhuang(box[i]) } function fengzhuang(box){ var n=0; var next=0; var boximg=$('.imgbox',box)[0] var img=$("a",box); img[0].style.left='0'; var anniu=$('.sh7a',box); anniu[0].style.back...
页脚的三个标志 var yj=$(".yj")[0]; var yjimg=$("a",yj); for (var i = 0; i < yjimg.length; i++) { yejiao(yjimg[i]) }; function yejiao(aa){ hover(
identifier_body
yintai.js
as[j].style.zIndex=0; } as[this.index].style.zIndex=10; bodiandiv[this.index].style.background='#e5004f';
0].onmouseover=function(){ rightclick[0].style.background='#cc477a'; } rightclick[0].onmouseout=function(){ rightclick[0].style.background=''; } leftclick[0].onmouseover=function(){ leftclick[0].style.background='#cc477a'; } leftclick[0].onmouseout=function(){ leftclick[0].style.background=''; ...
} }; rightclick[0].onclick=function(){ move(); }; rightclick[
conditional_block
manager.py
:`~budget.Note` :class:`~pandas.Series` using a connection to a SQL database using Parameters ---------- con : SQLAlchemy connectable, :class:`str`, or :mod:`sqlite3` connection SQL connection Returns ------- :class:`~pandas.Series` """ # ...
(self, id: str, note: str, drop_dups: bool = True): """Parses a string into a :class:`~budget.Note` object and adds it to the :class:`~budget.notes.NoteManager` using :class:`~pandas.Series.append` and optionally uses :class:`~pandas.Series.drop_duplicates` Parameters ---------- ...
add_note
identifier_name
manager.py
:`~budget.Note` :class:`~pandas.Series` using a connection to a SQL database using Parameters ---------- con : SQLAlchemy connectable, :class:`str`, or :mod:`sqlite3` connection SQL connection Returns ------- :class:`~pandas.Series` """ # ...
if isinstance(input, str): for nt in note_types: try: if nt._tag in input: res = nt(id, input) break except AttributeError: raise AttributeError('Notes must have a _tag attribute...
try: note_types.append(add_note_types) except: note_types.extend(add_note_types)
conditional_block
manager.py
:`~budget.Note` :class:`~pandas.Series` using a connection to a SQL database using Parameters ---------- con : SQLAlchemy connectable, :class:`str`, or :mod:`sqlite3` connection SQL connection Returns ------- :class:`~pandas.Series` """ # ...
def validate_notes(self, ids: pd.Series) -> bool: """Checks to make sure that all of the :class:`~budget.Note`s are contained in the ids Parameters ---------- ids : set or like-like :class:`list` or something that can be used in :meth:`~pandas.Series.isin` Retur...
raise TypeError(f'unknown type of note: {type(input)}')
random_line_split
manager.py
Parameters ---------- con : SQLAlchemy connectable, :class:`str`, or :mod:`sqlite3` connection SQL connection Returns ------- :class:`~pandas.Series` """ # Read the whole table of notes notes = pd.read_sql_query(sql=f'select * from {s...
"""Class to handle higher-level :class:`~budget.Note` manipulation Attributes ---------- notes : :class:`~pandas.DataFrame` :class:`~pandas.DataFrame` of the :class:`~budget.Note` objects. `Index` is the :class:`str` ID of the transaction that each :class:`~budget.Note` is linked to ""...
identifier_body
payment.component.ts
EventEmitter, NgZone } from '@angular/core'; import { Http, Response, RequestOptions, Headers } from '@angular/http'; import { Router, ActivatedRoute } from '@angular/router'; import { AppService } from '../app-service.service'; import { AlertService } from '../alert.service'; import { LoaderService } from '../loader....
}, handler: (response) => { vm.ngZone.run(() => { data.PAYMENT_ID = response.razorpay_payment_id; data.PAYMENT_SOURCE = 'RAZOR_PAY'; data.PLAN_START_DATE = vm.billingAmount.planStartDate; ...
}, theme: { color: '#3D78E0'
random_line_split
payment.component.ts
, NgZone } from '@angular/core'; import { Http, Response, RequestOptions, Headers } from '@angular/http'; import { Router, ActivatedRoute } from '@angular/router'; import { AppService } from '../app-service.service'; import { AlertService } from '../alert.service'; import { LoaderService } from '../loader.service'; imp...
implements OnInit { // @Input() tab: string; // @Input() user; @Output() renewalDateUpdated: EventEmitter<any> = new EventEmitter(); @Output() planTypeUpdated: EventEmitter<any> = new EventEmitter(); httpOptions: RequestOptions; session: any; billingAmount: any; invoices: any; envi...
PaymentComponent
identifier_name