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
domain_randomization.py
to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A...
def fill_buffer(self, num_domains: int): """ Fill the internal buffer with domains. :param num_domains: number of randomized domain parameter sets to store in the buffer """ if self._randomizer is None: raise pyrado.TypeErr(msg="The randomizer must not be None ...
"""Set the selection method.""" if selection not in ["cyclic", "random"]: raise pyrado.ValueErr(given=selection, eq_constraint="cyclic or random") self._selection = selection
identifier_body
borrow_set.rs
statement in which it appears on /// the right hand side; we map each such location to the /// corresponding `BorrowIndex`. crate location_map: FxHashMap<Location, BorrowIndex>, /// Locations which activate borrows. /// NOTE: a given location may activate more than one borrow in the future ///...
( locals_are_invalidated_at_exit: bool, body: &Body<'tcx>, move_data: &MoveData<'tcx> ) -> Self { struct HasStorageDead(BitSet<Local>); impl<'tcx> Visitor<'tcx> for HasStorageDead { fn visit_local(&mut self, local: &Local, ctx: PlaceContext, _: Location) { ...
build
identifier_name
borrow_set.rs
in which it appears on /// the right hand side; we map each such location to the /// corresponding `BorrowIndex`. crate location_map: FxHashMap<Location, BorrowIndex>, /// Locations which activate borrows. /// NOTE: a given location may activate more than one borrow in the future /// when more...
} } if locals_are_invalidated_at_exit { LocalsStateAtExit::AllAreInvalidated } else { let mut has_storage_dead = HasStorageDead(BitSet::new_empty(body.local_decls.len())); has_storage_dead.visit_body(body); let mut has_storage_dead_or...
{ self.0.insert(*local); }
conditional_block
borrow_set.rs
statement in which it appears on /// the right hand side; we map each such location to the /// corresponding `BorrowIndex`. crate location_map: FxHashMap<Location, BorrowIndex>, /// Locations which activate borrows. /// NOTE: a given location may activate more than one borrow in the future ///...
} } impl<'tcx> BorrowSet<'tcx> { pub fn build( tcx: TyCtxt<'tcx>, body: &Body<'tcx>, locals_are_invalidated_at_exit: bool, move_data: &MoveData<'tcx>, ) -> Self { let mut visitor = GatherBorrows { tcx, body, idx_vec: IndexVec::new(...
LocalsStateAtExit::SomeAreInvalidated{ has_storage_dead_or_moved } }
random_line_split
train_denoise_clouds.py
n_samples_matrix, _, _ = self.matrix.shape f_surface = zarr.open('training_surfaces_libnoise.zarr', 'r') self.surface = 1.0 - f_surface['surface'][:] n_samples_surface, _ = self.surface.shape f_clouds = zarr.open('training_clouds.zarr', 'r') self.clouds = f_clouds['clouds'][:]...
self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.lr, weight_decay=self.weight_decay) self.loss_fn = nn.MSELoss().to(self.device) self.scheduler = torch.optim.lr_scheduler.StepLR(self.optimizer, step_size=scheduler, gamma=0.5) np.random.seed(123) self.surf0 = ...
f.close()
random_line_split
train_denoise_clouds.py
f_surface = zarr.open('training_surfaces_libnoise.zarr', 'r') self.surface = 1.0 - f_surface['surface'][:] n_samples_surface, _ = self.surface.shape f_clouds = zarr.open('training_clouds.zarr', 'r') self.clouds = f_clouds['clouds'][:] n_samples_clouds, _ = self.clouds.s...
""" Dataset class that will provide data during training. Modify it accordingly for your dataset. This one shows how to do augmenting during training for a very simple training set """ def __init__(self, n_training): """ Args: n_training (int): number of tra...
identifier_body
train_denoise_clouds.py
n_samples_matrix, _, _ = self.matrix.shape f_surface = zarr.open('training_surfaces_libnoise.zarr', 'r') self.surface = 1.0 - f_surface['surface'][:] n_samples_surface, _ = self.surface.shape f_clouds = zarr.open('training_clouds.zarr', 'r') self.clouds = f_clouds['clouds'][:]...
(self, index): Phi = self.matrix[self.index_matrix[index], :, :].astype('float32') rho = 0.4 / self.eigenvals[self.index_matrix[index]] Phi_split = Phi.reshape((5, 24, 3072)) surface = np.random.uniform(low=0.2, high=1.0) * self.surface[self.index_surface[index], :] clou...
__getitem__
identifier_name
train_denoise_clouds.py
n_samples_matrix, _, _ = self.matrix.shape f_surface = zarr.open('training_surfaces_libnoise.zarr', 'r') self.surface = 1.0 - f_surface['surface'][:] n_samples_surface, _ = self.surface.shape f_clouds = zarr.open('training_clouds.zarr', 'r') self.clouds = f_clouds['clouds'][:]...
return Phi_split, surface.astype('float32'), clouds.astype('float32'), rho.astype('float32'), d_split.astype('float32') def __len__(self): return self.n_training def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): torch.save(state, filename) if is_best: ...
d_split[i, :] = Phi_split[i, :, :] @ (clouds[i, :] + (1.0 - clouds[i, :])**2 * surface)
conditional_block
create_load_files.py
conf = SparkConf().setAppName('word count') sc = SparkContext(conf=conf) sqlContext = SQLContext(sc) schema = types.StructType([types.StructField('Word', types.StringType(), False), types.StructField('Count', types.IntegerType(), False), types.StructField('Percen...
contents = line.split() return str(contents[0]), int(contents[1]), float(contents[2])
identifier_body
create_load_files.py
elif genre == "self-help": genre = "SH" genre_bag_words = crime_words.map(bags_format) genre_word_df = sqlContext.createDataFrame(genre_bag_words, schema=schema).cache() genre_word_df.createOrReplaceTempView(genre + '_words') # Input Files books_data = pd.read_csv("../../data/batch_1/books.csv"...
r5_url = amazon_data["R5 URL"][index] if type(r5_url) is float: r5_url = "" amazon_url = amazon_data["Book URL"][index] if type(amazon_url) is float: amazon_url = "" # Description data good_reads_desc = desc_data["GoodReads Description"][index] if type(good_reads_desc) is...
r5 = ""
conditional_block
create_load_files.py
elif genre == "science fiction": genre = "SF" elif genre == "self-help": genre = "SH" genre_bag_words = crime_words.map(bags_format) genre_word_df = sqlContext.createDataFrame(genre_bag_words, schema=schema).cache() genre_word_df.createOrReplaceTempView(genre + '_words') # Inpu...
elif genre == "non-fiction": genre = "NF"
random_line_split
create_load_files.py
(line): contents = line.split() return str(contents[0]), int(contents[1]), float(contents[2]) conf = SparkConf().setAppName('word count') sc = SparkContext(conf=conf) sqlContext = SQLContext(sc) schema = types.StructType([types.StructField('Word', types.StringType(), False), types.S...
bags_format
identifier_name
zigzag_graph.rs
= self.base_graph().degree() + expanded_parents.len(); for ii in 0..(self.degree() - current_length) { if self.reversed() { parents[ii + current_length] = self.size() - 1 } else { parents[ii + current_length] = 0 } ...
{ cache.read_reverse(node as u32, |parents| cb(parents.unwrap())) }
conditional_block
zigzag_graph.rs
new graph with expansion component inverted and a distinct /// base DRG graph -- with the direction of drg connections reversed. (i.e. from high-to-low nodes). /// The name is 'weird', but so is the operation -- hence the choice. fn zigzag(&self) -> Self; /// Constructs a new graph. fn base_graph(&...
expansion_degree
identifier_name
zigzag_graph.rs
ARENT_CACHE .write() .unwrap() .insert(res.id.clone(), ParentCache::new(nodes as u32)); } } res } } impl<H, G> ParameterSetMetadata for ZigZagGraph<H, G> where H: Hasher, G: Graph<H> + ParameterSetMetadata, { fn id...
{ Self::new(None, nodes, base_degree, expansion_degree, seed) }
identifier_body
zigzag_graph.rs
( nodes: usize, base_degree: usize, expansion_degree: usize, seed: [u32; 7], ) -> Self; } impl<Z: ZigZag> Graph<Z::BaseHasher> for Z { fn size(&self) -> usize { self.base_graph().size() } fn degree(&self) -> usize { self.base_graph().degree() + self.expa...
random_line_split
converter.py
return binding class Paint: def __init__(self, cs, value): self.cs = cs self.value = value def draw(self): return self.cs.getRGB(*self.value) class TextState(PDFTextState): def __init__(self): super().__init__() self.fill = None self.extState = {} d...
@get_default('font') def get_font(self, objid, obj=None): for (fontid, spec) in dict_value(obj).items(): spec = dict_value(spec) spec, fontType, embedFont, opentype = pdffonts.getType(spec) if fontType: font = fontType(spec, embedFont=embedFont and s...
get_function = getattr(self, 'get_' + res_type.lower(), None) return get_function and get_function(None, obj=res_obj)
identifier_body
converter.py
('Page')] self.viewBox = page.cropbox self.ymax = page.mediabox[3] - page.mediabox[1] def is_visible(self, span, bbox): boxset = set(map(lambda p: (int(p[0]), int(p[1])), span.bbox)) if len(boxset) < len(span.bbox): return False xmin, ymin, xmax, ymax = bbox ...
do_gs
identifier_name
converter.py
return binding class Paint: def __init__(self, cs, value): self.cs = cs self.value = value def draw(self): return self.cs.getRGB(*self.value) class TextState(PDFTextState): def __init__(self): super().__init__() self.fill = None self.extState = {} d...
self.fonts[literal(fontid)] = font @get_default('colorspace') def get_colorspace(self, objid, obj=None): for (csid, spec) in dict_value(obj).items(): cs = colorspace.parse(spec) if cs: self.colorspaces[literal(csid)] = cs def get_procset(sel...
self.xobjects[objid] = font.embedFont
conditional_block
converter.py
return False xmin, ymin, xmax, ymax = bbox return all(xmin < x < xmax and ymin < y < ymax for x, y in boxset) def get_current_layer(self): i = -1 depth = 0 while True: layerName = self.layer_stack[i] if layerName == 'end': depth += 1 ...
random_line_split
diagnostic_server.rs
ProcessBuilder; use serde::{Deserialize, Serialize}; use tracing::warn; use crate::core::Edition; use crate::util::errors::CargoResult; use crate::util::Config; const DIAGNOSTICS_SERVER_VAR: &str = "__CARGO_FIX_DIAGNOSTICS_SERVER"; #[derive(Deserialize, Serialize, Hash, Eq, PartialEq, Clone)] pub enum Message { ...
{ listener: TcpListener, addr: SocketAddr, } pub struct StartedServer { addr: SocketAddr, done: Arc<AtomicBool>, thread: Option<JoinHandle<()>>, } impl RustfixDiagnosticServer { pub fn new() -> Result<Self, Error> { let listener = TcpListener::bind("127.0.0.1:0") .with_con...
RustfixDiagnosticServer
identifier_name
diagnostic_server.rs
ProcessBuilder; use serde::{Deserialize, Serialize}; use tracing::warn; use crate::core::Edition; use crate::util::errors::CargoResult; use crate::util::Config; const DIAGNOSTICS_SERVER_VAR: &str = "__CARGO_FIX_DIAGNOSTICS_SERVER"; #[derive(Deserialize, Serialize, Hash, Eq, PartialEq, Clone)] pub enum Message { ...
if !files.is_empty() { writeln!( self.config.shell().err(), "\nafter fixes were automatically applied the compiler \ reported errors within these files:\n" )?; for file i...
{ self.config .shell() .warn("failed to automatically apply fixes suggested by rustc")?; }
conditional_block
diagnostic_server.rs
::ProcessBuilder; use serde::{Deserialize, Serialize}; use tracing::warn; use crate::core::Edition; use crate::util::errors::CargoResult; use crate::util::Config; const DIAGNOSTICS_SERVER_VAR: &str = "__CARGO_FIX_DIAGNOSTICS_SERVER"; #[derive(Deserialize, Serialize, Hash, Eq, PartialEq, Clone)] pub enum Message { ...
self.config.shell().warn(&format!("\ {} If you are trying to migrate from the previous edition ({prev_edition}), the process requires following these steps: 1. Start with `edition = \"{prev_edition}\"` in `Cargo.toml` 2. Run `cargo fix --edition` 3. Modify `Cargo.toml` to set `edition = \"{this_ed...
message: "".to_string(), // Dummy, so that this only long-warns once. edition: *edition, }) {
random_line_split
getast.go
, pkg, nil } // should return a list of *ast.TypeSpec we are interested in func GetTypeSpecs(f *ast.File) []*ast.TypeSpec { var out []*ast.TypeSpec // check all declarations... for i := range f.Decls { // for GenDecls... if g, ok := f.Decls[i].(*ast.GenDecl); ok { // and check the specs... for _, s := ...
random_line_split
getast.go
(filename string) (files []*ast.File, pkgName string, err error) { var ( f *ast.File fInfo os.FileInfo ) fset := token.NewFileSet() fInfo, err = os.Stat(filename) if err != nil { return } if fInfo.IsDir() { var pkgs map[string]*ast.Package pkgs, err = parser.ParseDir(fset, filename, nil, parser.Al...
GetAST
identifier_name
getast.go
// GetAST simply creates the ast out of a filename and filters // out non-exported elements. func GetAST(filename string) (files []*ast.File, pkgName string, err error) { var ( f *ast.File fInfo os.FileInfo ) fset := token.NewFileSet() fInfo, err = os.Stat(filename) if err != nil { return } if fInfo...
{ globalIdents = make(map[string]gen.Base) globalProcessed = make(map[string]struct{}) }
identifier_body
getast.go
.AllErrors) if err != nil { return } // we'll assume one package per dir var pkg *ast.Package for _, pkg = range pkgs { pkgName = pkg.Name } files = make([]*ast.File, len(pkg.Files)) var i = 0 for _, file := range pkg.Files { files[i] = file i++ } return } f, err = parser.ParseFile...
// skip fmt.Printf(chalk.Yellow.Color(" (\u26a0 field %q unsupported)"), sf.FieldName) continue for_fields } out = append(out, gen.StructField{ FieldTag: nm.Name, FieldName: nm.Name, FieldElem: el, }) } continue for_fields } // field tag var flagExtension bool ...
{ var sf gen.StructField // field name switch len(field.Names) { case 1: sf.FieldName = field.Names[0].Name case 0: sf.FieldName = embedded(field.Type) if sf.FieldName == "" { // means it's a selector expr., or // something else unsupported fmt.Printf(chalk.Yellow.Color(" (\u26a0 field %...
conditional_block
main.go
else { *ns = NullString{s.String, true} } return nil } type Env struct { sqlDb *sql.DB } // json object to map the endpoint input data type RequestInput struct { Event_UUID string `json:"event_uuid"` Username string `json:"username"` Unix_timestamp int64 `json:"unix_timestamp"` IP_Address string `...
{ *ns = NullString{s.String, false} }
conditional_block
main.go
_address"` } // geo location of the IP in the request type currentGeo struct { Lat float64 `json:"lat"` Lon float64 `json:"lon"` Radius uint16 `json:"radius"` } // json object representing the preceeding or succeeding IP type ipResponse struct { Ip string `json:"ip,omitempty"'` Speed *float32 `json:"speed,...
if valid_ip == nil { respondWithError("Invalid IP Address", writer) fmt.Println("Invalid IP Address: ", input.IP_Address) return } // building a temp table that appends row_number column which is used in join condition selectStatement := fmt.Sprintf(`with new_table AS (select uuid, username, ipaddress, dat...
{ decoder := json.NewDecoder(req.Body) var input RequestInput writer.Header().Set("Content-Type", "application/json") err := decoder.Decode(&input) if err != nil { respondWithError(err.Error(), writer) fmt.Println("handling ", req.RequestURI, ": ", err) return } tm := time.Unix(input.Unix_timestamp, 0) ...
identifier_body
main.go
_address"` } // geo location of the IP in the request type currentGeo struct { Lat float64 `json:"lat"` Lon float64 `json:"lon"` Radius uint16 `json:"radius"` } // json object representing the preceeding or succeeding IP type ipResponse struct { Ip string `json:"ip,omitempty"'` Speed *float32 `json:"speed,...
(writer http.ResponseWriter, req *http.Request){ decoder := json.NewDecoder(req.Body) var input RequestInput writer.Header().Set("Content-Type", "application/json") err := decoder.Decode(&input) if err != nil { respondWithError(err.Error(), writer) fmt.Println("handling ", req.RequestURI, ": ", err) return ...
home
identifier_name
main.go
_address"` } // geo location of the IP in the request type currentGeo struct { Lat float64 `json:"lat"` Lon float64 `json:"lon"` Radius uint16 `json:"radius"` } // json object representing the preceeding or succeeding IP type ipResponse struct { Ip string `json:"ip,omitempty"'` Speed *float32 `json:"speed,...
tx.Commit() // Defined the paramters as NullString to handle dereferencing issue with nil values returned from the database. type sqlrow struct { uuid NullString username NullString ipaddress NullString date_time NullString } // variables to hold the current, preceeding and succeeding database records ...
_, err = env.sqlDb.Exec("insert into request(uuid, username, ipaddress, date_time) values(?, ?, ?, ?)", input.Event_UUID, input.Username, input.IP_Address, input.Unix_timestamp) if err != nil { log.Fatal(err) panic(err) }
random_line_split
btc-arbitrage.ts
TT.Factories.GDAX.FeedFactory(logger, products).then((feed: GDAXFeed) => { // Configure all message streams to use the same websocket feed // Create the source message streams by creating a MessageStream for each product, using the same WS feed for each const streams = products.map((product) => new GTT.Core...
console.log(`arbitrageValue: ${arbitrageValue}`); sufficentBalances(btc_needed, eth_needed, usd_needed).then(result => { if (!result) { console.log('Insufficient Balances'); return } // alert me. process.stdout.write("\x07"); // buy eth with bi...
let btc_needed = eth_btc.times(amount); let usd_needed = btc_min_amount.times(btc_price.minus(min_increment));
random_line_split
btc-arbitrage.ts
TT.Factories.GDAX.FeedFactory(logger, products).then((feed: GDAXFeed) => { // Configure all message streams to use the same websocket feed // Create the source message streams by creating a MessageStream for each product, using the same WS feed for each const streams = products.map((product) => new GTT.Core...
de: string, product: string, amount: string, price: string) { const [base, quote] = product.split('-'); console.log(side + ' ' + base + ' ' + amount + ' ' + product + '@ ' + price); const order: PlaceOrderMessage = { time: new Date(), type: 'placeOrder', productId: product, size: amount, ...
erMessageWithREST(si
identifier_name
btc-arbitrage.ts
TT.Factories.GDAX.FeedFactory(logger, products).then((feed: GDAXFeed) => { // Configure all message streams to use the same websocket feed // Create the source message streams by creating a MessageStream for each product, using the same WS feed for each const streams = products.map((product) => new GTT.Core...
if (arbitrageValue.gt(arbitrageLimit)) {return} // if (executedArbitrage === true) {return} // i need 0.01 BTC // I need 0.01 / btc_eth exchange rate // I need 0.0
turn}
conditional_block
btc-arbitrage.ts
0; i < products.length; i++) { outStream[i] = feed.pipe(streams[i]); latest[i] = Big(-100000); } for (let i = 0; i < latest.length; i++) { outStream[i].on('data', (msg: StreamMessage) => { if (msg.type === 'trade') { mangeTradeMessage(i, msg as TradeMessage)...
// arbitrageValue = eth_price2 - eth_price let arbitrageLimit = Big(-1); let min_increment = Big(0.01); if (arbitrageValue.gte(zero)) {return} if (eth_btc.isZero() || eth_btc.lt(zero)) {return} if (arbitrageValue.gt(arbitrageLimit)) {return} // if (executedArbitrage === true) {return} /...
identifier_body
asset.rs
nomination, /// since if there were further not yet known nominations the value /// returned by this function will not match the valid data #[inline] pub fn ticker(&self) -> &str { &self.active_nomination().ticker() } /// Current asset name /// /// Current value determi...
random_line_split
asset.rs
serde(crate = "serde_crate", rename_all = "camelCase") )] #[derive( Clone, Getters, PartialEq, Debug, Display, StrictEncode, StrictDecode, )] #[display("{genesis_nomination} ({id})")] pub struct Asset { /// Bech32-representation of the asset genesis genesis: String, /// Asset ID, which is equal to ...
lf) -> &str { &self.active_nomination().ticker() } /// Current version of the asset contract, represented in Ricardian form /// /// Current value determined by the last known renomination operation – /// or, by the genesis nomination, if no renomination are known /// /// NB: the ret...
(&se
identifier_name
asset.rs
serde(crate = "serde_crate", rename_all = "camelCase") )] #[derive( Clone, Getters, PartialEq, Debug, Display, StrictEncode, StrictDecode, )] #[display("{genesis_nomination} ({id})")] pub struct Asset { /// Bech32-representation of the asset genesis genesis: String, /// Asset ID, which is equal to Con...
/ Returns sum of all known allocations, in atomic value units #[inline] pub fn known_value(&self) -> AtomicValue { self.known_allocations.iter().map(Allocation::value).sum() } /// Returns sum of known allocation after applying `filter` function. Useful /// for filtering UTXOs owned by the c...
self.last_nomination().unwrap_or(&self.genesis_nomination) } //
identifier_body
csv_import_accts_txns.rs
transactions_map, )?; Ok(()) } fn import_accounts( rdr: &mut csv::Reader<File>, raw_acct_map: &mut HashMap<u16, RawAccount>, acct_map: &mut HashMap<u16, Account>, ) -> Result<(), Box<dyn Error>> { let header1 = rdr.headers()?.clone(); // account_num let mut header2: csv::StringRecord ...
// A StringRecord doesn't accept the same range indexing needed below, so a Vec of Strings will be used let headerstrings: Vec<String> = header1.into_iter().map(|field| field.to_string()).collect(); let acct_num_warn = "Transactions will not import correctly if account numbers in th...
random_line_split
csv_import_accts_txns.rs
>, ) -> Result<(), Box<dyn Error>> { let header1 = rdr.headers()?.clone(); // account_num let mut header2: csv::StringRecord = csv::StringRecord::new(); // name let mut header3: csv::StringRecord = csv::StringRecord::new(); // ticker let header4: csv::StringRecord; // is_margin // Account ...
sanitize_string_for_d128_parsing_basic
identifier_name
csv_import_accts_txns.rs
1.into_iter().map(|field| field.to_string()).collect(); let acct_num_warn = "Transactions will not import correctly if account numbers in the CSV import file aren't ordered chronologically (i.e., beginning in column 4 - the 1st account column - the value should be 1. The next column's value should be 2, th...
{ let mut near_done = "".to_string(); // First, remove commas. let no_comma_string = field.replace(",", ""); let almost_done = no_comma_string.replace(" ", ""); // Next, if ASCII (better be), check for accounting formating if almost_done.is_ascii...
identifier_body
csv_import_accts_txns.rs
_map, )?; Ok(()) } fn import_accounts( rdr: &mut csv::Reader<File>, raw_acct_map: &mut HashMap<u16, RawAccount>, acct_map: &mut HashMap<u16, Account>, ) -> Result<(), Box<dyn Error>> { let header1 = rdr.headers()?.clone(); // account_num let mut header2: csv::StringRecord = csv::String...
; if amount.is_nan() { println!("FATAL: Couldn't convert amount to d128 for transaction:\n{:#?}", record); std::process::exit(1); } let amount_rounded = round_d128_1e8(&amount); if amount != amount_rounded { changed...
{ let c = sanitize_string_for_d128_parsing_full(field).parse::<d128>().unwrap(); amount = c; }
conditional_block
servergroup.go
promlog.AllowedLevel{}, Format: &promlog.AllowedFormat{}, } if err := logCfg.Level.Set("info"); err != nil { return nil, err } sg.targetManager = discovery.NewManager(ctx, promlog.New(logCfg)) // Background the updating go sg.targetManager.Run() go sg.Sync() return sg, nil } // ServerGroupState encapsula...
} apiClients = append(apiClients, apiClient) } } } apiClientMetricFunc := func(i int, api, status string, took float64) { serverGroupSummary.WithLabelValues(targets[i], api, status).Observe(took) } logrus.Debugf("Updating targets from discovery manager: %v", targets) apiClient, err := promclient...
{ return err }
conditional_block
servergroup.go
cheme: lset.Get(model.SchemeLabel), Host: lset.Get(model.AddressLabel), Path: lset.Get(PathPrefixLabel), } targets = append(targets, u.Host) client, err := api.NewClient(api.Config{Address: u.String(), RoundTripper: s}) if err != nil { return err } if len(s.Cfg.QueryParams)...
{ return s.State().apiClient.Metadata(ctx, metric, limit) }
identifier_body
servergroup.go
.PathPrefix)}) lset := labels.New(lbls...) logrus.Tracef("Potential target pre-relabel: %v", lset) lset = relabel.Process(lset, s.Cfg.RelabelConfigs...) logrus.Tracef("Potential target post-relabel: %v", lset) // Check if the target was dropped, if so we skip it if len(lset) == 0 { contin...
LabelNames
identifier_name
servergroup.go
&promlog.AllowedLevel{}, Format: &promlog.AllowedFormat{}, } if err := logCfg.Level.Set("info"); err != nil { return nil, err } sg.targetManager = discovery.NewManager(ctx, promlog.New(logCfg)) // Background the updating go sg.targetManager.Run() go sg.Sync() return sg, nil } // ServerGroupState encapsu...
End: s.Cfg.AbsoluteTimeRangeConfig.End, Truncate: s.Cfg.AbsoluteTimeRangeConfig.Truncate, } } if s.Cfg.RelativeTimeRangeConfig != nil { apiClient = &promclient.RelativeTimeFilter{ API: apiClient, Start: s.Cfg.RelativeTimeRangeConfig.Start, End: s.Cfg.Re...
API: apiClient, Start: s.Cfg.AbsoluteTimeRangeConfig.Start,
random_line_split
server.js
}, function(ret) { if (ret.statusCode) { console.log("user_" + userData.id + "成功注册推送"); } }); } }; //推送开关 var _push = { open: function(cb) { var ajpush = api.require('ajpush'); if (ajpush) { ajpush.resumePush(function(ret) { if (typeof cb === 'function') { cb(ret && ret.s...
var gpsCache = app.storage.val('gps'); if (typeof(callback) === 'function') { callback(gpsCache.lat, gpsCache.lng); } console.log('定位超时,使用缓存数据');
random_line_split
server.js
{ app.openView(null, 'member', 'login'); }, { bgclose: false }); }); return {}; } return _user; }; //坐标反查 var _getAddrByLoc = function(lat, lng, config) { var def = { callback: null, silent: false }; var opt = $.extend(def, config || {}); var map = api.require('bMap'); va...
ata.longitude }; app.storage.val('bdMapData', bdMapParam); if (refresh) { ap
conditional_block
spline.rs
_sample`]: behaves like [`Spline::sample`] but will return either the first /// or last key if out of bound; it will return `None` if not enough key. #[derive(Debug, Clone)] #[cfg_attr(feature = "serialization", derive(Deserialize, Serialize))] pub struct Spline<T, V>(pub(crate) Vec<Key<T, V>>); impl<T, V> Spline<...
key and return the key already present. /// /// The key is updated — if present — with the provided function. /// /// # Notes /// /// That function makes sense only if you
= self.0.len() { None } else { Some(self.0.remove(index)) } } /// Update a
identifier_body
spline.rs
<T, V>>, T: PartialOrd { Self::from_vec(iter.collect()) } /// Retrieve the keys of a spline. pub fn keys(&self) -> &[Key<T, V>] { &self.0 } /// Number of keys. #[inline(always)] pub fn len(&self) -> usize { self.0.len() } /// Check whether the spline has no key. #[inline(always)] pu...
// Car
identifier_name
spline.rs
amped_sample`]: behaves like [`Spline::sample`] but will return either the first /// or last key if out of bound; it will return `None` if not enough key. #[derive(Debug, Clone)] #[cfg_attr(feature = "serialization", derive(Deserialize, Serialize))] pub struct Spline<T, V>(pub(crate) Vec<Key<T, V>>); impl<T, V> Sp...
Interpolation::Linear => { let cp1 = &keys[i + 1]; let nt = normalize_time(t, cp0, cp1); let value = Interpolate::lerp(cp0.value, cp1.value, nt); Some((value, cp0, Some(cp1))) } Interpolation::Cosine => { let two_t = T::one() + T::one(); let cp1 = &key...
random_line_split
spline.rs
_sample`]: behaves like [`Spline::sample`] but will return either the first /// or last key if out of bound; it will return `None` if not enough key. #[derive(Debug, Clone)] #[cfg_attr(feature = "serialization", derive(Deserialize, Serialize))] pub struct Spline<T, V>(pub(crate) Vec<Key<T, V>>); impl<T, V> Spline<...
None } } }) } /// Sample a spline at a given time with clamping. pub fn clamped_sample(&self, t: T) -> Option<V> where T: Additive + One + Trigo + Mul<T, Output = T> + Div<T, Output = T> + PartialOrd, V: Interpolate<T> { self.clamped_sample_with_key(t).map(|(v, _, _)| v) } ...
((last.value, &last, None)) } else {
conditional_block
data_import.py
_splits={only_non_splits}) ...") with open(file, newline='') as csvfile: reader = csv.DictReader(csvfile, fieldnames=None) for row in reader: splits = canonicalize_and_sort_splits(row.get('splits')) totle_splits = canonicalize_and_sort_splits(row.get('totle_splits')) ...
# "0.5": { ... } # insert Totle as the agg_name in the aggregated data structure tok_ts_dex_prices[token][
for token, ts_agg_prices in json.load(open(f)).items(): for ts, agg_prices in ts_agg_prices.items(): # test for agg_name keys because Totle's JSON structure is different from aggs if any(map(lambda k: k in AGG_NAMES, agg_prices.keys())): # agg dex_prices f...
conditional_block
data_import.py
={only_non_splits}) ...") with open(file, newline='') as csvfile: reader = csv.DictReader(csvfile, fieldnames=None) for row in reader: splits = canonicalize_and_sort_splits(row.get('splits')) totle_splits = canonicalize_and_sort_splits(row.get('totle_splits')) i...
@functools.lru_cache() def get_all_agg_prices(files=None): files = files or glob.glob(f'{JSON_DATA_DIR}/2019*ts_agg_prices.json') tok_ts_agg_prices = defaultdict(lambda: defaultdict(lambda: defaultdict(list))) for f in files: for token, ts_agg_prices in json.load(open(f)).items(): fo...
"""Returns an aggregated dict of DEXs used in splits, i.e. token: {trade_size: [dex, dex, ...]}""" files = files or glob.glob(f'{JSON_DATA_DIR}/2019*ts_dexs_with_pair.json') tok_ts_dexs_with_pair = defaultdict(lambda: defaultdict(list)) for f in files: for token, ts_dexs_with_pair in json.load(ope...
identifier_body
data_import.py
_splits={only_non_splits}) ...") with open(file, newline='') as csvfile: reader = csv.DictReader(csvfile, fieldnames=None) for row in reader: splits = canonicalize_and_sort_splits(row.get('splits')) totle_splits = canonicalize_and_sort_splits(row.get('totle_splits')) ...
for file in csv_files: print(f"reading {file} ...") f_exchange, f_token, *_ = os.path.basename(file).split('_') with open(file, newline='') as csvfile: reader = csv.DictReader(csvfile, fieldnames=None) # time,action,trade_size,token,exchange,exchange_price,slippage,co...
tok_ts_ex_pscs = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
random_line_split
data_import.py
={only_non_splits}) ...") with open(file, newline='') as csvfile: reader = csv.DictReader(csvfile, fieldnames=None) for row in reader: splits = canonicalize_and_sort_splits(row.get('splits')) totle_splits = canonicalize_and_sort_splits(row.get('totle_splits')) i...
(files=None): """Returns an aggregated dict of split data, i.e. token: {trade_size: {agg: [{dex: pct, dex: pct}, {...}, ...]}}""" files = files or glob.glob(f'{JSON_DATA_DIR}/2019*ts_splits_by_agg.json') tok_ts_splits_by_agg = defaultdict(lambda: defaultdict(lambda: defaultdict(list))) for f in files: ...
get_all_splits_by_agg
identifier_name
ourairports.rs
_deg: Option<f64>, /// Longitude of the centre of the high-numbered end of the runway, in decimal degrees (positive is east), if available. he_longitude_deg: Option<f64>, /// Elevation above MSL of the high-numbered end of the runway in feet. he_elevation_ft: Option<i32>, #[serde(rename = "he_headin...
vec_string_from_string
identifier_name
ourairports.rs
. municipality: String, /// true if the airport currently has scheduled airline service; false otherwise. #[serde(deserialize_with = "bool_from_str")] scheduled_service: bool, /// The code that an aviation GPS database (such as Jeppesen's or Garmin's) would normally use for the airport. This will al...
/// for voice communication (radio navigation aids appear in struct Navaids) #[derive(Deserialize, Serialize)] pub struct AirportFrequency { /// Internal OurAirports integer identifier for the frequency. /// This will stay persistent, even if the radio frequency or description changes. id: String, /// I...
keywords: Vec<String>, } /// Contains information about a single airport radio frequency
random_line_split
num_format.rs
with this source code. // spell-checker:ignore (vars) charf cninetyninehexfloatf decf floatf intf scif strf Cninety //! handles creating printed output for numeric substitutions // spell-checker:ignore (vars) charf decf floatf intf scif strf Cninety use std::env; use std::vec::Vec; use crate::display::Quotable; us...
(field: &FormatField, in_str_opt: Option<&String>) -> Option<String> { let field_char = field.field_char; // num format mainly operates by further delegating to one of // several Formatter structs depending on the field // see formatter.rs for more details // to do switch to static dispatch le...
num_format
identifier_name
num_format.rs
with this source code. // spell-checker:ignore (vars) charf cninetyninehexfloatf decf floatf intf scif strf Cninety //! handles creating printed output for numeric substitutions // spell-checker:ignore (vars) charf decf floatf intf scif strf Cninety use std::env; use std::vec::Vec; use crate::display::Quotable; us...
// when character constant arguments have excess characters // issue a warning when POSIXLY_CORRECT is not set fn warn_char_constant_ign(remaining_bytes: &[u8]) { match env::var("POSIXLY_CORRECT") { Ok(_) => {} Err(e) => { if let env::VarError::NotPresent = e { show_war...
{ // important: keep println here not print show_error!("{}: expected a numeric value", pf_arg.maybe_quote()); }
identifier_body
num_format.rs
distributed with this source code. // spell-checker:ignore (vars) charf cninetyninehexfloatf decf floatf intf scif strf Cninety //! handles creating printed output for numeric substitutions // spell-checker:ignore (vars) charf decf floatf intf scif strf Cninety use std::env; use std::vec::Vec; use crate::display::...
ret.offset += 1; top_char = str_it.next(); } _ => {} } // we want to exit with offset being // the index of the first non-zero // digit before the decimal point or // if there is none, the zero before the // decimal point, or, if there is none, // the ...
random_line_split
qaoaLibrary.py
si) retvalue = 0 for k in range(Neigs): retvalue += overlap(final, vec[:,k])**2 return np.sqrt(retvalue) #betagamma = all betas first, then all gammas def expectQAOAp(psi, H, betagamma): ppsi = pointer(psi) pH = pointer(H) qc.uniform(ppsi) p = len(betagamma)/2 qc.evolveQA...
break; if spline[-1]!='0': print("Error: clause descriptions must have a terminal 0")
random_line_split
qaoaLibrary.py
with bounds""" def __init__(self, T, stepsize=0.5): self.maxT= T def __call__(self, **kwargs): """take a random step but ensure the new position is within the bounds""" x = kwargs["x_new"] return (sum(x)<self.maxT) # Set input and return types qc.expectH.restype ...
(n): psi = state() H = ham() qc.allocate(byref(psi),n) qc.allocateH(byref(H),n) return (psi, H) # Generate Ham object from coefficients zzc, xc and zc (given as np arrays) def hamGen(H, zzc, xc, zc): n = len(xc) H.zzc = (c_double * n**2)(*zzc.flatten().tolist()) H.xc ...
initialize
identifier_name
qaoaLibrary.py
# Set input and return types qc.expectH.restype = c_double qc.overlap.resype = c_double qc.energy.restype = c_double qc.qaoa1energy.restype = c_double # Initialize state and hamiltonian def initialize(n): psi = state() H = ham() qc.allocate(byref(psi),n) qc.allocateH(byref(H),...
"""random displacement with bounds""" def __init__(self, T, stepsize=0.5): self.maxT= T def __call__(self, **kwargs): """take a random step but ensure the new position is within the bounds""" x = kwargs["x_new"] return (sum(x)<self.maxT)
identifier_body
qaoaLibrary.py
igs): val, vec = ground(H, Neigs) final = c2pyState(psi) retvalue = 0 for k in range(Neigs): retvalue += overlap(final, vec[:,k])**2 return np.sqrt(retvalue) #betagamma = all betas first, then all gammas def expectQAOAp(psi, H, betagamma): ppsi = pointer(psi) pH = pointe...
print("Error: variable indices must lie between 0 and %d"%n) break;
conditional_block
publish.rs
subcommand. //! use std::convert::TryFrom; use std::path::PathBuf; use std::str::FromStr; use colored::Colorize; use structopt::StructOpt; use zksync::web3::types::H256; use zksync_eth_signer::PrivateKeySigner; use zksync_types::tx::PackedEthSignature; use crate::error::Error; use crate::executable::compiler::Comp...
let verifying_key = VerifyingKeyFile::try_from(&verifying_key_path)?; if !self.quiet { eprintln!( " {} the instance `{}` of `{} v{}` to network `{}`", "Uploading".bright_green(), self.instance, manifest.project.name, ...
{ VirtualMachine::setup_contract( self.verbosity, self.quiet, &binary_path, zinc_const::contract::CONSTRUCTOR_IDENTIFIER, &proving_key_path, &verifying_key_path, )?; }
conditional_block
publish.rs
` subcommand. //! use std::convert::TryFrom; use std::path::PathBuf; use std::str::FromStr; use colored::Colorize; use structopt::StructOpt; use zksync::web3::types::H256; use zksync_eth_signer::PrivateKeySigner; use zksync_types::tx::PackedEthSignature; use crate::error::Error; use crate::executable::compiler::Com...
let initial_transfer = crate::transaction::new_initial( &wallet, response.address, self.change_pubkey_fee_token, response.change_pubkey_fee, ) .await?; let address = response.address; let response = http_client .initial...
let wallet = zksync::Wallet::new(zksync::RpcProvider::new(network.into()), wallet_credentials) .await?;
random_line_split
publish.rs
subcommand. //! use std::convert::TryFrom; use std::path::PathBuf; use std::str::FromStr; use colored::Colorize; use structopt::StructOpt; use zksync::web3::types::H256; use zksync_eth_signer::PrivateKeySigner; use zksync_types::tx::PackedEthSignature; use crate::error::Error; use crate::executable::compiler::Comp...
} impl Command { /// /// A shortcut constructor. /// pub fn new( verbosity: usize, quiet: bool, manifest_path: PathBuf, instance: String, network: Option<String>, change_pubkey_fee_token: Option<String>, ) -> Self { Self { verbosi...
{ Self { address, account_id, } }
identifier_body
publish.rs
` subcommand. //! use std::convert::TryFrom; use std::path::PathBuf; use std::str::FromStr; use colored::Colorize; use structopt::StructOpt; use zksync::web3::types::H256; use zksync_eth_signer::PrivateKeySigner; use zksync_types::tx::PackedEthSignature; use crate::error::Error; use crate::executable::compiler::Com...
{ /// The address of the published contract instance. pub address: zksync_types::Address, /// The account ID of the published contract instance. pub account_id: zksync_types::AccountId, } impl Data { /// /// A shortcut constructor. /// pub fn new(address: zksync_types::Address, account...
Data
identifier_name
process_release_data.py
fields = [fileindex_item[COLUMN_CHECKSUM], fileindex_item[COLUMN_FILENAME]] if len(fileindex_item) > COLUMN_FILEDATE: fields.append(fileindex_item[COLUMN_FILEDATE]) f.write(bytes(";".join(fields) + "\n", "UTF-8")) def write_fileindex_md(hashalgo_md, fileindex, repo_name, hasha...
fileindex.sort(key=lambda a: (a[COLUMN_FILENAME].casefold(), a[COLUMN_FILEDATE])) write_fileindex_csv(hashalgo_csv, fileindex) hashalgo_md = os.path.join(root_dir, hashalgo_dir, hashalgo + ".md") write_fileindex_md(hashalgo_md, fileindex, repo_name, hashalgo)
random_line_split
process_release_data.py
: """Context manager for changing the current working directory""" def __init__(self, newPath): self.newPath = os.path.expanduser(newPath) def __enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPath) def __exit__(self, etype, value, traceback): os.chdir(sel...
cd
identifier_name
process_release_data.py
.savedPath = os.getcwd() os.chdir(self.newPath) def __exit__(self, etype, value, traceback): os.chdir(self.savedPath) def download_fileindex_csv(repo_name, download_dir, hashalgo, github_token=None): if github_token: github_release._github_token_cli_arg = github_token fileindex_cs...
logging.debug(hashalgo + ": downloading release assets") # Find out which filenames are present in multiple versions (need to give them unique names) filenames = [checksum_filename[1] for checksum_filename in fileindex] from collections import Counter # Sort based on filename and filedate filei...
"""Download files associated with HASHALGO release into directory (root_dir)/(hashalgo). List of files is taken from (root_dir)/(hashalgo).csv. If multiple hashes associated with the same filename then the last entry will be used. """ if github_token: github_release._github_token_cli_arg = github_tok...
identifier_body
process_release_data.py
.savedPath = os.getcwd() os.chdir(self.newPath) def __exit__(self, etype, value, traceback): os.chdir(self.savedPath) def download_fileindex_csv(repo_name, download_dir, hashalgo, github_token=None): if github_token: github_release._github_token_cli_arg = github_token fileindex_cs...
return fileindex def write_fileindex_csv(hashalgo_csv, fileindex): with open(hashalgo_csv, "wb") as f: for fileindex_item in fileindex: fields = [fileindex_item[COLUMN_CHECKSUM], fileindex_item[COLUMN_FILENAME]] if len(fileindex_item) > COLUMN_FILEDATE: fields....
fields = line.rstrip().split(";") if len(fields) <= COLUMN_FILEDATE: fields.append("") # if date is missing then add an empty field fileindex.append(fields)
conditional_block
model.py
def forward(self, x, pre_sts=None, last_only=False): """ :param x: the input sequence :param pre_sts: to prevent recalculation. the prefix sequence's hidden states and Q,V saved in previous turn. :return: logits of vocab words """ sts = self.transformer(x, pre_sts) ...
class Block(nn.Module): def __init__(self, n_ctx, cfg, scale=False): super(Block, self).__init__() nx = cfg.n_embd self.attn = Attention(nx, n_ctx, cfg, scale) self.ln_1 = LayerNorm(nx) self.mlp = MLP(4 * nx, cfg) self.ln_2 = LayerNorm(nx) def forward(self, x,...
if pre_sts is None: e = self.drop(self.embed(x)) # Add the position information to the input embeddings h = e.sum(dim=2) # for eval mode else: # get newly added words' embeddings prev_len = pre_sts[0].size(1) e_new = self.drop(self....
identifier_body
model.py
def forward(self, x, pre_sts=None, last_only=False): """ :param x: the input sequence :param pre_sts: to prevent recalculation. the prefix sequence's hidden states and Q,V saved in previous turn. :return: logits of vocab words """ sts = self.transformer(x, pre_sts) ...
size_out = x.size()[:-1] + (self.nf,) x = torch.addmm(self.b, x.view(-1, x.size(-1)), self.w) x = x.view(*size_out) else: raise NotImplementedError return x class Attention(nn.Module): def __init__(self, nx, n_ctx, cfg, scale=False): super(At...
if self.rf == 1:
random_line_split
model.py
def forward(self, x, pre_sts=None, last_only=False): """ :param x: the input sequence :param pre_sts: to prevent recalculation. the prefix sequence's hidden states and Q,V saved in previous turn. :return: logits of vocab words """ sts = self.transformer(x, pre_sts) ...
else: raise NotImplementedError return x class Attention(nn.Module): def __init__(self, nx, n_ctx, cfg, scale=False): super(Attention, self).__init__() n_state = nx # in Attention: n_state=768 (nx=n_embd) # [switch nx => n_state from Block to Attention to keep...
size_out = x.size()[:-1] + (self.nf,) x = torch.addmm(self.b, x.view(-1, x.size(-1)), self.w) x = x.view(*size_out)
conditional_block
model.py
def forward(self, x, pre_sts=None, last_only=False): """ :param x: the input sequence :param pre_sts: to prevent recalculation. the prefix sequence's hidden states and Q,V saved in previous turn. :return: logits of vocab words """ sts = self.transformer(x, pre_sts) ...
(self, x, pre_key=None, pre_value=None): x = self.c_attn(x) query, key, value = x.split(self.split_size, dim=2) query = self.split_heads(query) key = self.split_heads(key, k=True) value = self.split_heads(value) # prevent recalculation if pre_key is not None and p...
forward
identifier_name
manager.rs
fn create_network_config() -> Result<Rc<RefCell<NetworkConfig>>> { let mut network = NetworkConfig::new(); network.add_bridge("clear", "172.17.0.0/24")?; Ok(Rc::new(RefCell::new(network))) } pub fn load() -> Result<RealmManager> { let mut manager = RealmManager::new()?; ...
{ let network = RealmManager::create_network_config()?; Ok(RealmManager { realm_map: HashMap::new(), realm_list: Vec::new(), symlinks: Rc::new(RefCell::new(RealmSymlinks::new())), network: network.clone(), systemd: Systemd::new(network), ...
identifier_body
manager.rs
.borrow_mut().load_symlinks()?; if ! PathBuf::from(REALMS_BASE_PATH).exists() { bail!("realms base directory {} does not exist", REALMS_BASE_PATH); } for dent in fs::read_dir(REALMS_BASE_PATH)? { let path = dent?.path(); manager.process_realm_path(&path) ...
random_line_split
manager.rs
RefCell::new(network))) } pub fn load() -> Result<RealmManager> { let mut manager = RealmManager::new()?; manager.symlinks.borrow_mut().load_symlinks()?; if ! PathBuf::from(REALMS_BASE_PATH).exists() { bail!("realms base directory {} does not exist", REALMS_BASE_PATH); ...
(&mut self, realm: Realm) -> &Realm { self.realm_map.insert(realm.name().to_owned(), realm.clone()); self.realm_list.push(realm.clone()); self.realm_map.get(realm.name()).expect("cannot find realm we just added to map") } fn remove_realm_entry(&mut self, name: &str) -> Result<()> { ...
add_realm_entry
identifier_name
Multiple_PhotometryConstruction.py
plt.show() while True: try: proceed = str(input("Does everything look okay?")) if proceed == 'y': trim.append(100) note.append('All good') break elif proceed == 'n': trim....
pulleventdata
identifier_name
Multiple_PhotometryConstruction.py
def evaluate_rawdata(time,Subjects_465,Subjects_405, subjs): trim = [] note = [] if len(Subjects_465) == 1: fig1 = plt.figure() plt.plot(time[0],Subjects_465[0].data, color='green', label = 'Gcamp6f') plt.plot(time[0],Subjects_405[0].data, color='blueviolet', label = 'ISOS') ...
timex = [] if len(s465) == 1: timex.append(np.linspace(1,len(s465[0].data), len(s465[0].data))/s465[0].fs) else: for i in range(0, len(s465)): timex.append(np.linspace(1,len(s465[i].data), len(s465[i].data))/s465[i].fs) return timex
identifier_body
Multiple_PhotometryConstruction.py
65[i].data))/s465[i].fs) return timex def evaluate_rawdata(time,Subjects_465,Subjects_405, subjs): trim = [] note = [] if len(Subjects_465) == 1: fig1 = plt.figure() plt.plot(time[0],Subjects_465[0].data, color='green', label = 'Gcamp6f') plt.plot(time[0],Subjects_405[0].data, c...
y_all.append(np.multiply(baseline[0][0], np.array(trimmed_s405[0])) + baseline[0][1]) y_df.append(np.array(trimmed_s465[0]) - y_all[0]) dFF.append(np.multiply(100,np.divide(y_df[0],y_all[0]))) std_dFF.append(np.std(dFF[0])) else: for i in range(0, len(s465)): s_in...
#process data baseline.append(np.polyfit(np.array(trimmed_s405[0]), np.array(trimmed_s465[0]), 1))
random_line_split
Multiple_PhotometryConstruction.py
[i].data))/s465[i].fs) return timex def evaluate_rawdata(time,Subjects_465,Subjects_405, subjs): trim = [] note = [] if len(Subjects_465) == 1: fig1 = plt.figure() plt.plot(time[0],Subjects_465[0].data, color='green', label = 'Gcamp6f') plt.plot(time[0],Subjects_405[0].data, col...
return event_list_dict def send_events(event_list_dict): md= MetaData(engine) test_conn = engine.connect() if not engine.dialect.has_table(test_conn,'eventdata'): eventdata = Table('eventdata', md, Column('idx', Integer, primary_key=True, nullable=False, autoincrement=True), ...
for e in all_events[i]: subject_list = [int(subjects[i])]*len(e.onset) session_list = [s]*len(e.onset) name_list = [e.name]*len(e.onset) onset_list = e.onset.tolist() offset_list = e.offset.tolist() for j in range(0,len(onse...
conditional_block
apps.go
)
() (err error) { var aids []int if c.AccountID == 0 { s := NewSpinner("Looking up accounts") s.Start() as, err := api.Accounts() if err != nil { return fmt.Errorf("unable to look up accounts: %w", err) } for _, a := range as { aids = append(aids, a.ID) } s.Stop() } else { aids = append(aids...
Run
identifier_name
apps.go
) Run() (err error) { var aids []int if c.AccountID == 0 { s := NewSpinner("Looking up accounts") s.Start() as, err := api.Accounts() if err != nil { return fmt.Errorf("unable to look up accounts: %w", err) } for _, a := range as { aids = append(aids, a.ID) } s.Stop() } else { aids = append...
() } fmt.Println() return err } // AppsCreateCmd handles creating apps on Section type AppsCreateCmd struct { AccountID int `required short:"a" help:"ID of account to create the app under"` Hostname string `required short:"d" help:"FQDN the app can be accessed at"` Origin string `required short:"o" help...
ing{p.Name, p.Image} table.Append(r) } table.Render
conditional_block
apps.go
// Run executes the command func (c *AppsListCmd) Run() (err error) { var aids []int if c.AccountID == 0 { s := NewSpinner("Looking up accounts") s.Start() as, err := api.Accounts() if err != nil { return fmt.Errorf("unable to look up accounts: %w", err) } for _, a := range as { aids = append(aid...
{ t = tablewriter.NewWriter(out) t.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false}) t.SetCenterSeparator("|") t.SetAlignment(tablewriter.ALIGN_LEFT) return t }
identifier_body
apps.go
) Run() (err error) { var aids []int if c.AccountID == 0 { s := NewSpinner("Looking up accounts") s.Start() as, err := api.Accounts() if err != nil { return fmt.Errorf("unable to look up accounts: %w", err) } for _, a := range as { aids = append(aids, a.ID) } s.Stop() } else { aids = append...
s.Stop() if err != nil { if err == api.ErrStatusForbidden { stacks, herr := api.Stacks() if herr != nil { return fmt.Errorf("unable to query stacks: %w", herr) } for _, s := range stacks { if s.Name == c.StackName { return err } } return fmt.Errorf("bad request: unable to find sta...
api.Timeout = 120 * time.Second // this specific request can take a long time r, err := api.ApplicationCreate(c.AccountID, c.Hostname, c.Origin, c.StackName)
random_line_split
Week_05.py
can return data as a result. """ # writing a function def printInfo(): # defines what the function does when called print("Name: John Smith") # calls the function to run print("Age: 45") # calls the function again printInfo() printInfo() # Function Stages """ There are two stages: functi...
input("Enter your name") checkCaps(name) """ 2. No Name: Define a function that takes in two arguments, first_name and last_ name, and makes both optional. If no values are passed into the parameters, it should output “No name passed in”; otherwise, it should print out the name. """ # solution # def checkName(first_...
se") name =
conditional_block
Week_05.py
can return data as a result. """ # writing a function def printInfo(): # defines what the function does when called print("Name: John Smith") # calls the function to run print("Age: 45") # calls the function again printInfo() printInfo() # Function Stages """ There are two stages: functi...
.5) # *args """ The use of *args allows you to pass a variable number of arguments into a function. This allows you to make functions more modular. The magic isn’t the “args” keyword here though; it’s really the unary operator ( * ) that allows us to perform this feature. You could theoretically replace the word args ...
t(num1) addNums(5, num2=2
identifier_body
Week_05.py
can return data as a result. """ # writing a function def printInfo(): # defines what the function does when called print("Name: John Smith") # calls the function to run print("Age: 45") # calls the function again printInfo() printInfo() # Function Stages """ There are two stages: functi...
outputData("John Smith", 5, True, "Jess") # **kwargs """ Like args, kwargs allows us to take in an arbitrary number of values in a function; however, it works as a dictionary with keyword arguments instead. Keyword arguments are values passed in with keys, which allow us to access them easily within the function bl...
def outputData(name, *args): print(type(args)) for arg in args: print(arg)
random_line_split
Week_05.py
can return data as a result. """ # writing a function def printInfo(): # defines what the function does when called print("Name: John Smith") # calls the function to run print("Age: 45") # calls the function again printInfo() printInfo() # Function Stages """ There are two stages: functi...
print("Your name is: {}".format(full_name)) printName("John Smith") printName("Amanda") # Multiple parameters # passing multiple parameters into a function def addNums(num1, num2): result = num1+num2 print("{} + {} = {}".format(num1, num2, result)) addNums(5, 8) addNums(3.5, 5.5) # passing a list # ...
ll_name):
identifier_name
controller.go
", id) nfsGaneshaConfig := ` EXPORT { Export_Id = ` + idStr + `; Path = /` + path + `; Pseudo = /` + path + `; Protocols = 4; Transports = TCP; Sectype = sys; Access_Type = ` + accessType + `; Squash = ` + s.ToLower(squash) + `; FSAL { Name = VFS; } }` return nfsGaneshaConfig } func createGaneshaConfig(...
validateAccessMode
identifier_name
controller.go
getServerConfig(spec.Exports) exportsList := make([]string, 0) id := 10 for claimName, claimConfig := range serverConfig { exportsList = append(exportsList, createGaneshaExport(id, claimName, claimConfig["accessMode"], claimConfig["squash"])) id++ } // fsid_device parameter is important as in case of an ove...
{ switch s.ToLower(mode) { case "none": case "rootid": case "root": case "all": default: return fmt.Errorf("Invalid value (%s) for squash, valid values are (none, rootId, root, all)", mode) } return nil }
identifier_body
controller.go
} // Controller represents a controller object for nfs server custom resources type Controller struct { context *clusterd.Context containerImage string } // NewController create controller for watching nfsserver custom resources created func NewController(context *clusterd.Context, containerImage string) *Co...
Group: nfsv1alpha1.CustomResourceGroup, Version: nfsv1alpha1.Version, Scope: apiextensionsv1beta1.NamespaceScoped, Kind: reflect.TypeOf(nfsv1alpha1.NFSServer{}).Name(),
random_line_split
controller.go
, Scope: apiextensionsv1beta1.NamespaceScoped, Kind: reflect.TypeOf(nfsv1alpha1.NFSServer{}).Name(), } // Controller represents a controller object for nfs server custom resources type Controller struct { context *clusterd.Context containerImage string } // NewController create controller for watching...
return pvcNameList } func createPVCSpecList(spec *nfsv1alpha1.NFSServerSpec) []v1.Volume { pvcSpecList := make([]v1.Volume, 0) pvcNameList := getPVCNameList(spec) for _, claimName := range pvcNameList { pvcSpecList = append(pvcSpecList, v1.Volume{ Name: claimName, VolumeSource: v1.VolumeSource{ Persi...
{ claimName := export.PersistentVolumeClaim.ClaimName if claimName != "" { pvcNameList = append(pvcNameList, claimName) } }
conditional_block
role_conversion.py
$', 'soc.tasks.updates.role_conversion.updateHosts'), ] return patterns class HostUpdater(object): """Class which is responsible for updating Host entities. """ def run(self, batch_size=25): """Starts the updater. """ self._process(None, batch_size) def _process(self, start_key, ba...
"""Starts a bunch of iterative tasks which update references in StudentProjects. """ return updateReferencesForModel('student_project')
identifier_body
role_conversion.py
Host from soc.models.linkable import Linkable from soc.models.mentor import Mentor from soc.models.org_admin import OrgAdmin from soc.models.role import StudentInfo from soc.modules.gsoc.models.mentor import GSoCMentor from soc.modules.gsoc.models.organization import GSoCOrganization from soc.modules.gsoc.models.org_...
(request): """Starts a task which updates Host entities. """ updater = HostUpdater() updater.run() return http.HttpResponse("Ok") def updateRole(role_name): """Starts a task which updates a particular role. """ if role_name == 'gsoc_mentor': updater = RoleUpdater(GSoCMentor, GSoCProfile, 'progra...
updateHosts
identifier_name
role_conversion.py
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """...
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #
random_line_split
role_conversion.py
Host from soc.models.linkable import Linkable from soc.models.mentor import Mentor from soc.models.org_admin import OrgAdmin from soc.models.role import StudentInfo from soc.modules.gsoc.models.mentor import GSoCMentor from soc.modules.gsoc.models.organization import GSoCOrganization from soc.modules.gsoc.models.org_...
# process the next batch of entities start_key = entities[-1].key() deferred.defer(self._process, start_key, batch_size) except DeadlineExceededError: # here we should probably be more careful deferred.defer(self._process, start_key, batch_size) class RoleUpdater(object): """Clas...
sponsor = entity.scope host_for = entity.user.host_for if not host_for: host_for = [] user = entity.user if sponsor.key() not in host_for: host_for.append(sponsor.key()) user.host_for = host_for db.put(user)
conditional_block