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
dp.rs
// 我们开始学习动态规划吧 use std::cmp::min; // https://leetcode-cn.com/problems/maximum-subarray
let mut ans = nums[0]; for i in 1..nums.len() { if sum > 0 { // add positive sum means larger sum += nums[i]; } else { // start from new one means larger sum = nums[i]; } // ans always store the largest sum ans = std::cmp::...
// 最大子序各,好像看不出什么动态规则的意味,反而像滑动窗口 pub fn max_sub_array(nums: Vec<i32>) -> i32 { let mut sum = nums[0];
random_line_split
tools.js
var reporting = require('./reporting') module.exports = { timing_section_c : 0, timing_section_d : 0, timing_section_e : 0, calculateAverage: function(data_to_be_tested) { //console.log(data_to_be_tested) var sum = 0; var len = data_to_be_tested.length for (var j=0; j < len; j++) { sum += data_to...
if (print_full_debug) { reporting.debug('LIMIT NOT REACHED: <br />') reporting.debug('total_spent ('+total_spent+') - total_sold ('+total_sold+') + buy_sell_unit ('+buy_sell_unit+') = ('+(total_spent - total_sold + buy_sell_unit)+') is not greater than 2000<br />') } } // if flag set, and already o...
} else {
random_line_split
tools.js
var reporting = require('./reporting') module.exports = { timing_section_c : 0, timing_section_d : 0, timing_section_e : 0, calculateAverage: function(data_to_be_tested) { //console.log(data_to_be_tested) var sum = 0; var len = data_to_be_tested.length for (var j=0; j < len; j++) { sum += data_to...
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
//! # Ordnung //! //! Fast, vector-based map implementation that preserves insertion order. //! //! + Map is implemented as a binary tree over a `Vec` for storage, with only //! two extra words per entry for book-keeping on 64-bit architectures. //! + A fast hash function with good random distribution is used to bala...
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
//! # Ordnung //! //! Fast, vector-based map implementation that preserves insertion order. //! //! + Map is implemented as a binary tree over a `Vec` for storage, with only //! two extra words per entry for book-keeping on 64-bit architectures. //! + A fast hash function with good random distribution is used to bala...
(&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
//! # Ordnung //! //! Fast, vector-based map implementation that preserves insertion order. //! //! + Map is implemented as a binary tree over a `Vec` for storage, with only //! two extra words per entry for book-keeping on 64-bit architectures. //! + A fast hash function with good random distribution is used to bala...
} impl<'a, K, V> Iterator for IterMut<'a, K, V> { type Item = (&'a K, &'a mut V); #[inline] fn next(&mut self) -> Option<Self::Item> { while let Some(node) = self.inner.next() { let value = match node.value { Some(ref mut value) => value, None => contin...
{ IterMut { inner: [].iter_mut(), } }
identifier_body
lib.rs
//! # Ordnung //! //! Fast, vector-based map implementation that preserves insertion order. //! //! + Map is implemented as a binary tree over a `Vec` for storage, with only //! two extra words per entry for book-keeping on 64-bit architectures. //! + A fast hash function with good random distribution is used to bala...
} return false; } true } } /// An iterator over the entries of a `Map`. /// /// This struct is created by the [`iter`](./struct.Map.html#method.iter) /// method on [`Map`](./struct.Map.html). See its documentation for more. pub struct Iter<'a, K, V> { inner: slice::It...
{ continue; }
conditional_block
main_api_sentence.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020/12/23 4:56 下午 # @File : api.py # @Author: johnson # @Contact : github: johnson7788 # @Desc : ###################################################### # 使用没有蒸馏的模型预测,改造成一个flask api, 句子级情感预测 # 包括训练接口api和预测接口api # /api/train # /api/predict ######################...
: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
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020/12/23 4:56 下午 # @File : api.py # @Author: johnson # @Contact : github: johnson7788 # @Desc : ###################################################### # 使用没有蒸馏的模型预测,改造成一个flask api, 句子级情感预测 # 包括训练接口api和预测接口api # /api/train # /api/predict ######################...
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
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020/12/23 4:56 下午 # @File : api.py # @Author: johnson # @Contact : github: johnson7788 # @Desc : ###################################################### # 使用没有蒸馏的模型预测,改造成一个flask api, 句子级情感预测 # 包括训练接口api和预测接口api # /api/train # /api/predict ######################...
identifier_name
main_api_sentence.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020/12/23 4:56 下午 # @File : api.py # @Author: johnson # @Contact : github: johnson7788 # @Desc : ###################################################### # 使用没有蒸馏的模型预测,改造成一个flask api, 句子级情感预测 # 包括训练接口api和预测接口api # /api/train # /api/predict ######################...
weight_decay_rate=self.weight_decay_rate) # 优化器设置 optimizer = BERTAdam(all_trainable_params, lr=self.learning_rate, warmup=self.warmup_proportion, t_total=num_train_steps, schedule=self.schedule, s_opt1=self.s_opt1, s_opt2=self.s_opt2, s_opt3=se...
= 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
from numpy import linalg from laika.lib.coordinates import ecef2geodetic, geodetic2ecef from laika import AstroDog from laika.gps_time import GPSTime import glob import os import numpy as np import matplotlib.pyplot as plt import scipy import tensorflow as tf from tensorflow import keras from tensorflow.keras import ...
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
from numpy import linalg from laika.lib.coordinates import ecef2geodetic, geodetic2ecef from laika import AstroDog from laika.gps_time import GPSTime import glob import os import numpy as np import matplotlib.pyplot as plt import scipy import tensorflow as tf from tensorflow import keras from tensorflow.keras import ...
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
from numpy import linalg from laika.lib.coordinates import ecef2geodetic, geodetic2ecef from laika import AstroDog from laika.gps_time import GPSTime import glob import os import numpy as np import matplotlib.pyplot as plt import scipy import tensorflow as tf from tensorflow import keras from tensorflow.keras import ...
print() if True: plt.clf() plt.scatter(pred_pos[:,1], pred_pos[:,0], s=0.2) plt.scatter(gt_ecef_coords[:,1], gt_ecef_coords[:,0], s=0.2) #fig1.canvas.start_event_loop(sys.float_info.min) #workaround for Exception in Tkinter callbac...
physics = 1.
conditional_block
tf_train_loop.py
from numpy import linalg from laika.lib.coordinates import ecef2geodetic, geodetic2ecef from laika import AstroDog from laika.gps_time import GPSTime import glob import os import numpy as np import matplotlib.pyplot as plt import scipy import tensorflow as tf from tensorflow import keras from tensorflow.keras import ...
(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
package dashboard import ( "arrowcloudapi/models" "arrowcloudapi/mongo" "arrowcloudapi/utils/log" "errors" "io/ioutil" "net/http" "net/url" "regexp" "strconv" "strings" "time" "gopkg.in/mgo.v2/bson" "github.com/jeffail/gabs" ) const ( host360 = "platform.appcelerator.com" authPath = "/...
// '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
package dashboard import ( "arrowcloudapi/models" "arrowcloudapi/mongo" "arrowcloudapi/utils/log" "errors" "io/ioutil" "net/http" "net/url" "regexp" "strconv" "strings" "time" "gopkg.in/mgo.v2/bson" "github.com/jeffail/gabs" ) const ( host360 = "platform.appcelerator.com" authPath = "/...
(username string) (bson.M, error) { log.Debugf("find dashboard session for user %s", username) re, err := mongo.FindOneDocument(mongo.STRATUS_DASHBOARD_SESSIONS_COLL, bson.M{"username": username}) if err != nil { log.Errorf("Failed to find dashboard session. %v", err) return nil, err } return re, err } /...
findDashboardSession
identifier_name
dashboard.go
package dashboard import ( "arrowcloudapi/models" "arrowcloudapi/mongo" "arrowcloudapi/utils/log" "errors" "io/ioutil" "net/http" "net/url" "regexp" "strconv" "strings" "time" "gopkg.in/mgo.v2/bson" "github.com/jeffail/gabs" ) const ( host360 = "platform.appcelerator.com" authPath = "/...
/** * insert or update user information upon login to Appcelerator's sso interface */ func saveUser(user bson.M) (bson.M, error) { saved, err := mongo.UpsertDocument(mongo.STRATUS_USERS_COLL, bson.M{"guid": user["guid"]}, user) if err != nil { log.Errorf("Failed to save user. %v", err) return nil, err } ...
{ 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
package dashboard import ( "arrowcloudapi/models" "arrowcloudapi/mongo" "arrowcloudapi/utils/log" "errors" "io/ioutil" "net/http" "net/url" "regexp" "strconv" "strings" "time" "gopkg.in/mgo.v2/bson" "github.com/jeffail/gabs" ) const ( host360 = "platform.appcelerator.com" authPath = "/...
return nil, err } return re, err } /** * insert or update user's 360 session information upon login to 360 */ func saveDashboardSession(session bson.M) error { log.Debugf("save dashboard session for user %v", session["username"]) _, err := mongo.UpsertDocument(mongo.STRATUS_DASHBOARD_SESSIONS_COLL, bson.M{...
if err != nil { log.Errorf("Failed to find dashboard session. %v", err)
random_line_split
lib.rs
//! A lock-free, eventually consistent, concurrent multi-value map. //! //! This map implementation allows reads and writes to execute entirely in parallel, with no //! implicit synchronization overhead. Reads never take locks on their critical path, and neither //! do writes assuming there is a single writer (multi-wr...
<K, V>(self) -> (WriteHandle<K, V, M, S>, ReadHandle<K, V, M, S>) where K: Eq + Hash + Clone, S: BuildHasher + Clone, V: Eq + Hash, M: 'static + Clone, { let inner = if let Some(cap) = self.capacity { Inner::with_capacity_and_hasher(self.meta, cap, self.hasher...
assert_stable
identifier_name
lib.rs
//! A lock-free, eventually consistent, concurrent multi-value map. //! //! This map implementation allows reads and writes to execute entirely in parallel, with no //! implicit synchronization overhead. Reads never take locks on their critical path, and neither //! do writes assuming there is a single writer (multi-wr...
else { Inner::with_hasher(self.meta, self.hasher) }; let (mut w, r) = left_right::new_from_empty(inner); w.append(write::Operation::MarkReady); (WriteHandle::new(w), ReadHandle::new(r)) } } /// Create an empty eventually consistent map. /// /// Use the [`Options`](./s...
{ Inner::with_capacity_and_hasher(self.meta, cap, self.hasher) }
conditional_block
lib.rs
//! A lock-free, eventually consistent, concurrent multi-value map. //! //! This map implementation allows reads and writes to execute entirely in parallel, with no //! implicit synchronization overhead. Reads never take locks on their critical path, and neither //! do writes assuming there is a single writer (multi-wr...
/// of the same key. #[allow(clippy::type_complexity)] pub unsafe fn assert_stable<K, V>(self) -> (WriteHandle<K, V, M, S>, ReadHandle<K, V, M, S>) where K: Eq + Hash + Clone, S: BuildHasher + Clone, V: Eq + Hash, M: 'static + Clone, { let inner = if let Some(...
/// same inputs. For keys of type `K`, the result must also be consistent between different clones
random_line_split
lib.rs
//! A lock-free, eventually consistent, concurrent multi-value map. //! //! This map implementation allows reads and writes to execute entirely in parallel, with no //! implicit synchronization overhead. Reads never take locks on their critical path, and neither //! do writes assuming there is a single writer (multi-wr...
} /// Create an empty eventually consistent map. /// /// Use the [`Options`](./struct.Options.html) builder for more control over initialization. /// /// If you want to use arbitrary types for the keys and values, use [`new_assert_stable`]. #[allow(clippy::type_complexity)] pub fn new<K, V>() -> ( WriteHandle<K, ...
{ 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
/** * ALMViz * See https://github.com/lagotto/almviz for more details * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING. * * @brief Article level metrics visualization controller. */ /*global d3 */ var options = { baseUrl: '', minItemsToShowGraph: { minEventsForYearly: 1, ...
(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
/** * ALMViz * See https://github.com/lagotto/almviz for more details * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING. * * @brief Article level metrics visualization controller. */ /*global d3 */ var options = { baseUrl: '', minItemsToShowGraph: { minEventsForYearly: 1, ...
return viz; }; /** * Takes in the basic set up of a graph and loads the data itself * @param {Object} viz AlmViz object * @param {string} level (day|month|year) */ var loadData_ = function(viz, level) { var group = viz.group; var subgroup = viz.subgroup; var level_data = getData_(le...
viz.svg.append("g") .attr("class", "y axis");
random_line_split
results.js
/** * ALMViz * See https://github.com/lagotto/almviz for more details * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING. * * @brief Article level metrics visualization controller. */ /*global d3 */ var options = { baseUrl: '', minItemsToShowGraph: { minEventsForYearly: 1, ...
{ // 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
/** * ALMViz * See https://github.com/lagotto/almviz for more details * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING. * * @brief Article level metrics visualization controller. */ /*global d3 */ var options = { baseUrl: '', minItemsToShowGraph: { minEventsForYearly: 1, ...
// 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
package azurerm import ( "crypto/sha1" "encoding/base64" "encoding/hex" "fmt" "log" "reflect" "strings" "sync" "github.com/Azure/azure-sdk-for-go/arm/resources/resources" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/helper/mutexkv" "github.com/hashicorp/terraform/helper/resource" ...
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
package azurerm import ( "crypto/sha1" "encoding/base64" "encoding/hex" "fmt" "log" "reflect" "strings" "sync" "github.com/Azure/azure-sdk-for-go/arm/resources/resources" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/helper/mutexkv" "github.com/hashicorp/terraform/helper/resource" ...
// Base64Encode encodes data if the input isn't already encoded using // base64.StdEncoding.EncodeToString. If the input is already base64 encoded, // return the original input unchanged. func base64Encode(data string) string { // Check whether the data is already Base64 encoded; don't double-encode if isBase64Enco...
{ switch s := v.(type) { case string: s = base64Encode(s) hash := sha1.Sum([]byte(s)) return hex.EncodeToString(hash[:]) default: return "" } }
identifier_body
provider.go
package azurerm import ( "crypto/sha1" "encoding/base64" "encoding/hex" "fmt" "log" "reflect" "strings" "sync" "github.com/Azure/azure-sdk-for-go/arm/resources/resources" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/helper/mutexkv" "github.com/hashicorp/terraform/helper/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
package azurerm import ( "crypto/sha1" "encoding/base64" "encoding/hex" "fmt" "log" "reflect" "strings" "sync" "github.com/Azure/azure-sdk-for-go/arm/resources/resources" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/helper/mutexkv" "github.com/hashicorp/terraform/helper/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
// Package saver contains all logic for writing records to files. // 1. Sets up a channel that accepts slices of *netlink.ArchivalRecord // 2. Maintains a map of Connections, one for each connection. // 3. Uses several marshallers goroutines to serialize data and and write to // zstd files. // 4. Rotates Connec...
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
// Package saver contains all logic for writing records to files. // 1. Sets up a channel that accepts slices of *netlink.ArchivalRecord // 2. Maintains a map of Connections, one for each connection. // 3. Uses several marshallers goroutines to serialize data and and write to // zstd files. // 4. Rotates Connec...
// 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
// Package saver contains all logic for writing records to files. // 1. Sets up a channel that accepts slices of *netlink.ArchivalRecord // 2. Maintains a map of Connections, one for each connection. // 3. Uses several marshallers goroutines to serialize data and and write to // zstd files. // 4. Rotates Connec...
svr.endConn(cookie) svr.stats.IncExpiredCount() } // Every second, update the total throughput for the past second. if msgs.V4Time.Unix() > lastReportTime { // This is the total bytes since program start. totalSent := closed.Sent + svr.ClosingTotals.Sent + s4 + s6 totalReceived := closed.Receive...
{ 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
// Package saver contains all logic for writing records to files. // 1. Sets up a channel that accepts slices of *netlink.ArchivalRecord // 2. Maintains a map of Connections, one for each connection. // 3. Uses several marshallers goroutines to serialize data and and write to // zstd files. // 4. Rotates Connec...
(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
// Copyright 2020 Andy Grove // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writi...
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
// Copyright 2020 Andy Grove // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writi...
( expr: &[Expr], input: &Schema, ) -> Result<Vec<Arc<dyn AggregateExpr>>> { expr.iter() .map(|e| compile_aggregate_expression(e, input)) .collect() }
compile_aggregate_expressions
identifier_name
transaction.go
package transaction import ( "crypto/sha256" "encoding/json" "errors" "fmt" "math" "math/rand" "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/util" ) const ( // MaxScriptLength is the li...
() error { if t.Version > 0 && t.Version != DummyVersion { return ErrInvalidVersion } if t.SystemFee < 0 { return ErrNegativeSystemFee } if t.NetworkFee < 0 { return ErrNegativeNetworkFee } if t.NetworkFee+t.SystemFee < t.SystemFee { return ErrTooBigFees } if len(t.Signers) == 0 { return ErrEmptySign...
isValid
identifier_name
transaction.go
package transaction import ( "crypto/sha256" "encoding/json" "errors" "fmt" "math" "math/rand" "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/util" ) const ( // MaxScriptLength is the li...
} attrs := map[AttrType]bool{} for i := range t.Attributes { typ := t.Attributes[i].Type if !typ.allowMultiple() { if attrs[typ] { return fmt.Errorf("%w: multiple '%s' attributes", ErrInvalidAttribute, typ.String()) } attrs[typ] = true } } if len(t.Script) == 0 { return ErrEmptyScript } ret...
{ if t.Signers[i].Account.Equals(t.Signers[j].Account) { return ErrNonUniqueSigners } }
conditional_block
transaction.go
package transaction import ( "crypto/sha256" "encoding/json" "errors" "fmt" "math" "math/rand" "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/util" ) const ( // MaxScriptLength is the li...
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
package transaction import ( "crypto/sha256" "encoding/json" "errors" "fmt" "math" "math/rand" "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/util" ) const ( // MaxScriptLength is the li...
// 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
use core::fmt; use super::{NaiveDateTime, DateTime, UnixTimestamp, Month, DayOfTheWeek}; use num::{div_floor, positive_rem}; pub trait TimeZone { fn from_timestamp(&self, t: UnixTimestamp) -> NaiveDateTime; fn to_timestamp(&self, d: &NaiveDateTime) -> Result<UnixTimestamp, LocalTimeConversionError>; } /// Whe...
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
use core::fmt; use super::{NaiveDateTime, DateTime, UnixTimestamp, Month, DayOfTheWeek}; use num::{div_floor, positive_rem};
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
use std::collections::hash_map; use std::fmt; use std::mem; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use std::sync::{Arc, Mutex, Weak}; use std::time::Duration; use sys; use sys::fuchsia::{ assert_fuchsia_ready_repr, epoll_event_to_ready, poll_opts_to_wait_async, EventedFd, ...
.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
use std::collections::hash_map; use std::fmt; use std::mem; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use std::sync::{Arc, Mutex, Weak}; use std::time::Duration; use sys; use sys::fuchsia::{ assert_fuchsia_ready_repr, epoll_event_to_ready, poll_opts_to_wait_async, EventedFd, ...
(&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
use std::collections::hash_map; use std::fmt; use std::mem; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use std::sync::{Arc, Mutex, Weak}; use std::time::Duration; use sys; use sys::fuchsia::{ assert_fuchsia_ready_repr, epoll_event_to_ready, poll_opts_to_wait_async, EventedFd, ...
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
use std::collections::hash_map; use std::fmt; use std::mem; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use std::sync::{Arc, Mutex, Weak}; use std::time::Duration; use sys; use sys::fuchsia::{ assert_fuchsia_ready_repr, epoll_event_to_ready, poll_opts_to_wait_async, EventedFd, ...
pub fn register_handle( &self, handle: zx_handle_t, token: Token, interests: Ready, poll_opts: PollOpt, ) -> io::Result<()> { if poll_opts.is_level() && !poll_opts.is_oneshot() { return Err(io::Error::new( io::ErrorKind::InvalidInput,...
{ 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
import numpy as np import pickle import torch as th from tqdm import tqdm from torch import nn from torch.nn import functional as F from rl_baselines.base_classes import BaseRLObject from srl_zoo.models.base_models import CustomCNN from srl_zoo.preprocessing.data_loader import SupervisedDataLoader, DataLoader from s...
(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
import numpy as np import pickle import torch as th from tqdm import tqdm from torch import nn from torch.nn import functional as F from rl_baselines.base_classes import BaseRLObject from srl_zoo.models.base_models import CustomCNN from srl_zoo.preprocessing.data_loader import SupervisedDataLoader, DataLoader from sr...
self.device = th.device("cuda" if th.cuda.is_available() else "cpu") if th.cuda.is_available(): self.model.cuda() self.optimizer = th.optim.Adam(learnable_params, lr=learning_rate) best_error = np.inf best_model_path = "{}/{}_model.pkl".format(args.log_dir, args.alg...
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
import numpy as np import pickle import torch as th from tqdm import tqdm from torch import nn from torch.nn import functional as F from rl_baselines.base_classes import BaseRLObject from srl_zoo.models.base_models import CustomCNN from srl_zoo.preprocessing.data_loader import SupervisedDataLoader, DataLoader from s...
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
import numpy as np import pickle import torch as th from tqdm import tqdm from torch import nn from torch.nn import functional as F from rl_baselines.base_classes import BaseRLObject from srl_zoo.models.base_models import CustomCNN from srl_zoo.preprocessing.data_loader import SupervisedDataLoader, DataLoader from s...
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
import * as CIDTool from 'cid-tool'; import { Log, MarketReportingState, NULL_ADDRESS, SubscriptionEventName, } from '@augurproject/sdk-lite'; import { Log as SerializedLog } from '@augurproject/types'; import { IPFSEndpointInfo, IPFSHashVersion, logger } from '@augurproject/utils'; import Dexie from 'dexie'; i...
async hasMostRecentCheckpoint() { return (await this.getMostRecentCheckpoint()) !== undefined; } }
{ return this.db.warpCheckpoints.getMostRecentCheckpoint(); }
identifier_body
WarpController.ts
import * as CIDTool from 'cid-tool'; import { Log, MarketReportingState, NULL_ADDRESS, SubscriptionEventName, } from '@augurproject/sdk-lite'; import { Log as SerializedLog } from '@augurproject/types'; import { IPFSEndpointInfo, IPFSHashVersion, logger } from '@augurproject/utils'; import Dexie from 'dexie'; i...
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
import * as CIDTool from 'cid-tool'; import { Log, MarketReportingState, NULL_ADDRESS, SubscriptionEventName, } from '@augurproject/sdk-lite'; import { Log as SerializedLog } from '@augurproject/types'; import { IPFSEndpointInfo, IPFSHashVersion, logger } from '@augurproject/utils'; import Dexie from 'dexie'; i...
} 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
import * as CIDTool from 'cid-tool'; import { Log, MarketReportingState, NULL_ADDRESS, SubscriptionEventName, } from '@augurproject/sdk-lite'; import { Log as SerializedLog } from '@augurproject/types'; import { IPFSEndpointInfo, IPFSHashVersion, logger } from '@augurproject/utils'; import Dexie from 'dexie'; i...
() { 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
package nameresolver import ( "fmt" "github.com/miekg/dns" "net" "github.com/ANSSI-FR/transdep/messages/zonecut" "github.com/ANSSI-FR/transdep/tools" "github.com/ANSSI-FR/transdep/messages/nameresolver" "github.com/ANSSI-FR/transdep/errors" "strings" ) // WORKER_CHAN_CAPACITY indicates the maximum number of r...
} errList = append(errList, fmt.Sprintf("resolveFromGluelessNameSrvs: error from %s(%s): %s", ns.Name(), addr.String(), err.Error())) } } // We tried every IP address of every name server to no avail. Return an error return nil, errors.NewErrorStack(fmt.Errorf("resolveFromGluelessNameSrvs: no valid glueless ...
random_line_split
worker.go
package nameresolver import ( "fmt" "github.com/miekg/dns" "net" "github.com/ANSSI-FR/transdep/messages/zonecut" "github.com/ANSSI-FR/transdep/tools" "github.com/ANSSI-FR/transdep/messages/nameresolver" "github.com/ANSSI-FR/transdep/errors" "strings" ) // WORKER_CHAN_CAPACITY indicates the maximum number of r...
err = nil entry = nil } if entry == nil { // If no entry was provided, reqName is not the zone apex, so we remove a label and retry. pos, end := dns.NextLabel(reqName, 1) if end { reqName = "." } else { reqName = reqName[pos:] } } } // Setting apart glueless delegations and glued...
{ 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
package nameresolver import ( "fmt" "github.com/miekg/dns" "net" "github.com/ANSSI-FR/transdep/messages/zonecut" "github.com/ANSSI-FR/transdep/tools" "github.com/ANSSI-FR/transdep/messages/nameresolver" "github.com/ANSSI-FR/transdep/errors" "strings" ) // WORKER_CHAN_CAPACITY indicates the maximum number of r...
// 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
package nameresolver import ( "fmt" "github.com/miekg/dns" "net" "github.com/ANSSI-FR/transdep/messages/zonecut" "github.com/ANSSI-FR/transdep/tools" "github.com/ANSSI-FR/transdep/messages/nameresolver" "github.com/ANSSI-FR/transdep/errors" "strings" ) // WORKER_CHAN_CAPACITY indicates the maximum number of r...
(nameSrvs []*zonecut.NameSrvInfo) (*nameresolver.Entry, *errors.ErrorStack) { var errList []string Outerloop: for _, ns := range nameSrvs { var addrs []net.IP // requestedName is the nameserver name, by default. It may evolve, as aliases/CNAME are met along the resolution requestedName := ns.Name() // We limi...
resolveFromGluelessNameSrvs
identifier_name
project_tasks.py
# coding=utf-8 """ Project tasks Add the following to your *requirements.txt* file: * docutils!=0.14rc1; python_version == "[python_versions]" """ import ast import os from pprint import pformat import shutil import textwrap # noinspection PyUnresolvedReferences from herringlib.prompt import prompt # noinspection Py...
(): """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
# coding=utf-8 """ Project tasks Add the following to your *requirements.txt* file: * docutils!=0.14rc1; python_version == "[python_versions]" """ import ast import os from pprint import pformat import shutil import textwrap # noinspection PyUnresolvedReferences from herringlib.prompt import prompt # noinspection Py...
@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
# coding=utf-8 """ Project tasks Add the following to your *requirements.txt* file: * docutils!=0.14rc1; python_version == "[python_versions]" """ import ast import os from pprint import pformat import shutil import textwrap # noinspection PyUnresolvedReferences from herringlib.prompt import prompt # noinspection Py...
@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
# coding=utf-8 """ Project tasks Add the following to your *requirements.txt* file: * docutils!=0.14rc1; python_version == "[python_versions]" """ import ast import os from pprint import pformat import shutil import textwrap # noinspection PyUnresolvedReferences from herringlib.prompt import prompt # noinspection 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
// Copyright 2020 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agree...
(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
// Copyright 2020 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agree...
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
// Copyright 2020 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agree...
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
// Copyright 2020 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agree...
// 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
#!/usr/bin/env python # coding=utf-8 __version__ = "2.5.0" # When modifying remember to issue a new tag command in git before committing, then push the new tag # git tag -a v2.5.0 -m "v2.5.0" # git push origin --tags """ Python script that generates the necessary mp4box -cat commands to concatinate multiple video f...
# 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
#!/usr/bin/env python # coding=utf-8 __version__ = "2.5.0" # When modifying remember to issue a new tag command in git before committing, then push the new tag # git tag -a v2.5.0 -m "v2.5.0" # git push origin --tags """ Python script that generates the necessary mp4box -cat commands to concatinate multiple video 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
#!/usr/bin/env python # coding=utf-8 __version__ = "2.5.0" # When modifying remember to issue a new tag command in git before committing, then push the new tag # git tag -a v2.5.0 -m "v2.5.0" # git push origin --tags """ Python script that generates the necessary mp4box -cat commands to concatinate multiple video f...
uns a subprocess using the arguments passed and monitors its progress while printing out the latest # log line to the console on a single line def _runSubProcess(prog_args, path_to_wait_on=None): print( " ".join(prog_args)) # Force a UTF8 environment for the subprocess so that files with non-ascii characters are ...
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
#!/usr/bin/env python # coding=utf-8 __version__ = "2.5.0" # When modifying remember to issue a new tag command in git before committing, then push the new tag # git tag -a v2.5.0 -m "v2.5.0" # git push origin --tags """ Python script that generates the necessary mp4box -cat commands to concatinate multiple video f...
(grep_match, path_out_file): in_files = glob.glob(grep_match.replace("\\", "/")) return [f for f in sorted(in_files, key=natural_key) if '.mp4' in Path(f).suffix and not Path(f) == path_out_file] # # Cleans any invalid file name and file path characters from the given filename def sanitizeFileName(local_filename...
getFileNamesFromGrepMatch
identifier_name
window.rs
use std::{collections::HashMap, sync::Arc}; use log::warn; use unicode_segmentation::UnicodeSegmentation; use crate::{ bridge::GridLineCell, editor::{grid::CharacterGrid, style::Style, AnchorInfo, DrawCommand, DrawCommandBatcher}, renderer::{LineFragment, WindowDrawCommand}, }; pub enum WindowType { ...
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
use std::{collections::HashMap, sync::Arc}; use log::warn; use unicode_segmentation::UnicodeSegmentation; use crate::{ bridge::GridLineCell, editor::{grid::CharacterGrid, style::Style, AnchorInfo, DrawCommand, DrawCommandBatcher}, renderer::{LineFragment, WindowDrawCommand}, }; pub enum WindowType { ...
(&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
use std::{collections::HashMap, sync::Arc}; use log::warn; use unicode_segmentation::UnicodeSegmentation; use crate::{ bridge::GridLineCell, editor::{grid::CharacterGrid, style::Style, AnchorInfo, DrawCommand, DrawCommandBatcher}, renderer::{LineFragment, WindowDrawCommand}, }; pub enum WindowType { ...
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
use std::{collections::HashMap, sync::Arc}; use log::warn; use unicode_segmentation::UnicodeSegmentation; use crate::{ bridge::GridLineCell, editor::{grid::CharacterGrid, style::Style, AnchorInfo, DrawCommand, DrawCommandBatcher}, renderer::{LineFragment, WindowDrawCommand}, }; pub enum WindowType { ...
} 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
# ****************************************************** # *********** Projeto 2 ************* # *********** Fundamentos da Programacao ************* # *********** ************* # *********** Carolina Carreira ************* # *********** 8764...
(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) != 5 or not isinstance (arg, list): return False for a in arg: # Testa tipo, tamanho, e se nao ha letras repetidas em cad...
e_chave
identifier_name
Projeto.py
# ****************************************************** # *********** Projeto 2 ************* # *********** Fundamentos da Programacao ************* # *********** ************* # *********** Carolina Carreira ************* # *********** 87641...
# em linhas e colunas diferentes. # A funcao devolve (pos1_cod, pos2_cod) que correspondem as posicoes das letras # do digrama encriptado/desencriptado def codifica_r (pos1, pos2): # Retorna duas posicoes com as colunas trocadas entre si return faz_pos(linha_pos(pos1), coluna_pos(pos2),) , faz_pos(linha_...
# 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
# ****************************************************** # *********** Projeto 2 ************* # *********** Fundamentos da Programacao ************* # *********** ************* # *********** Carolina Carreira ************* # *********** 8764...
else: return True # TRANSFORMADORES # string_chave: chave --> str # string_chave(c) devolve uma cadeia de caracteres que uma vez impressa apresenta # as letras de c dispostas numa tabela 5 x 5 def string_chave (chave): c = '' for linha in chave: # Coloca espacos entra as letras ...
if not ( 64 < ord(b) < 91): return False
conditional_block
Projeto.py
# ****************************************************** # *********** Projeto 2 ************* # *********** Fundamentos da Programacao ************* # *********** ************* # *********** Carolina Carreira ************* # *********** 8764...
l = ('A','B','C','D','E','F','G','H','I','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')
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
import NEF from matplotlib import pyplot as plt from random import choice from math import log,exp,sqrt,sin from random import normalvariate,random from pickle import dump,load #from math import abs import numpy as np def Error(p,target,deltaT): Error.value = Error.value*exp(-deltaT/Error.tau) # Error.value +=...
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
import NEF from matplotlib import pyplot as plt from random import choice from math import log,exp,sqrt,sin from random import normalvariate,random from pickle import dump,load #from math import abs import numpy as np def Error(p,target,deltaT): Error.value = Error.value*exp(-deltaT/Error.tau) # Error.value +=...
(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
import NEF from matplotlib import pyplot as plt from random import choice from math import log,exp,sqrt,sin from random import normalvariate,random from pickle import dump,load #from math import abs import numpy as np def Error(p,target,deltaT): Error.value = Error.value*exp(-deltaT/Error.tau) # Error.value += ...
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
import NEF from matplotlib import pyplot as plt from random import choice from math import log,exp,sqrt,sin from random import normalvariate,random from pickle import dump,load #from math import abs import numpy as np def Error(p,target,deltaT): Error.value = Error.value*exp(-deltaT/Error.tau) # Error.value +=...
plt.plot(tvals,xhatvals,label="decoded") # plt.plot(tvals,ervals,label ="error") plt.plot(tvals,avvals,label="a vals") plt.legend() # plt.show() # plt.savefig("savedfig_allpoints_normalized_300neurons_etap05_woverallplots_"+str(c)) # ...
v = "0p4"
conditional_block
main.py
import email import json import logging import os 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.spar...
(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
import email import json import logging import os 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.spar...
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 email import json import logging
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
import email import json import logging import os 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.spar...
@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
import math import warnings import numpy as np import scipy.sparse as sp __all__ = ['median', 'nanmedian', 'nansum', 'nanmean', 'nanvar', 'nanstd', 'nanmin', 'nanmax', 'nanargmin', 'nanargmax', 'rankdata', 'nanrankdata', 'ss', 'nn', 'partsort', 'argpartsort', 'replace', 'anynan', 'alln...
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
import math import warnings import numpy as np import scipy.sparse as sp __all__ = ['median', 'nanmedian', 'nansum', 'nanmean', 'nanvar', 'nanstd', 'nanmin', 'nanmax', 'nanargmin', 'nanargmax', 'rankdata', 'nanrankdata', 'ss', 'nn', 'partsort', 'argpartsort', 'replace', 'anynan', 'alln...
return a_min, a_max, mean, var, nans, non_nans if sp.issparse(arr): arr = arr.todense() y = np.zeros((arr.shape[1], 6), dtype=float) y[:, 0] = nanmin(arr, 0) y[:, 1] = nanmax(arr, 0) if weights: tot_w = np.sum(weights) y[:, 4] = countnans(arr, weights, 0) y[...
var *= non_nans / d
conditional_block
func.py
import math import warnings import numpy as np import scipy.sparse as sp __all__ = ['median', 'nanmedian', 'nansum', 'nanmean', 'nanvar', 'nanstd', 'nanmin', 'nanmax', 'nanargmin', 'nanargmax', 'rankdata', 'nanrankdata', 'ss', 'nn', 'partsort', 'argpartsort', 'replace', 'anynan', 'alln...
(a, axis): if axis is None: a = np.ravel(a) outaxis = 0 else: a = np.asarray(a) outaxis = axis return a, outaxis def fastsort(a): """ Sort an array and provide the argsort. Parameters ---------- a : array_like Input array. Returns ------...
_chk_asarray
identifier_name
func.py
import math import warnings import numpy as np import scipy.sparse as sp __all__ = ['median', 'nanmedian', 'nansum', 'nanmean', 'nanvar', 'nanstd', 'nanmin', 'nanmax', 'nanargmin', 'nanargmax', 'rankdata', 'nanrankdata', 'ss', 'nn', 'partsort', 'argpartsort', 'replace', 'anynan', 'alln...
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
window.onload=function(){ var box=getClass('bannera',document); // console.dir(box); var as=box[0].getElementsByTagName('a'); // console.dir(as); var bodians=getClass('lunbodian',document); // console.dir(bodians); var bodiandiv=bodians[0].getElementsByTagName('div'); // console.dir(bodiandiv); var lrclickbox=...
var tps=$(".weixin")[0]; var aas=$("a",tps)[0]; var bs=$("b",tps)[0]; yidong(wxs,tps,hys,aas,bs); var kst=$(".ks3t")[0]; var ks=$(".ks33")[0]; var aar=$("a",ks)[0]; var ksb=$(".ks3b")[0]; var bb=$("b",ks)[0]; yidong(kst,ks,ksb,aar,bb); function yidong(wx,tp,hy,aa,b){ hover(wx,function(){ tp.style.bac...
var wxs=$('.shouji')[0]; var hys=$(".shoujji")[0];
random_line_split
yintai.js
window.onload=function(){ var box=getClass('bannera',document); // console.dir(box); var as=box[0].getElementsByTagName('a'); // console.dir(as); var bodians=getClass('lunbodian',document); // console.dir(bodians); var bodiandiv=bodians[0].getElementsByTagName('div'); // console.dir(bodiandiv); var lrclickbox...
{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
window.onload=function(){ var box=getClass('bannera',document); // console.dir(box); var as=box[0].getElementsByTagName('a'); // console.dir(as); var bodians=getClass('lunbodian',document); // console.dir(bodians); var bodiandiv=bodians[0].getElementsByTagName('div'); // console.dir(bodiandiv); var lrclickbox...
aa,function(){ aa.style.opacity='0.7' },function(){ aa.style.opacity="1" }) } };
页脚的三个标志 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
window.onload=function(){ var box=getClass('bannera',document); // console.dir(box); var as=box[0].getElementsByTagName('a'); // console.dir(as); var bodians=getClass('lunbodian',document); // console.dir(bodians); var bodiandiv=bodians[0].getElementsByTagName('div'); // console.dir(bodiandiv); var lrclickbox...
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
import logging import re from typing import List import numpy as np import pandas as pd from . import note, split from .note import Note, Link, Category from .split import SplitNote LOGGER = logging.getLogger(__name__) NOTE_PARSE_REGEX = re.compile('id=\'([\d\w]+)\', note=\'([\d\w :,]+)\'') class NoteManager: "...
(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
import logging import re from typing import List import numpy as np import pandas as pd from . import note, split from .note import Note, Link, Category from .split import SplitNote LOGGER = logging.getLogger(__name__) NOTE_PARSE_REGEX = re.compile('id=\'([\d\w]+)\', note=\'([\d\w :,]+)\'') class NoteManager: "...
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
import logging import re from typing import List import numpy as np import pandas as pd from . import note, split from .note import Note, Link, Category from .split import SplitNote LOGGER = logging.getLogger(__name__) NOTE_PARSE_REGEX = re.compile('id=\'([\d\w]+)\', note=\'([\d\w :,]+)\'') class NoteManager: "...
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
import logging import re from typing import List import numpy as np import pandas as pd from . import note, split from .note import Note, Link, Category from .split import SplitNote LOGGER = logging.getLogger(__name__) NOTE_PARSE_REGEX = re.compile('id=\'([\d\w]+)\', note=\'([\d\w :,]+)\'') class NoteManager:
"""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
import { Component, OnInit, Input, Output, ViewEncapsulation, 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 ...
}, 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