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
admission_test.go
/* Copyright 2017 The Kubernetes 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 agreed to in writing, ...
func TestAdmitPolicyDoesNotExist(t *testing.T) { controller, err := newControllerWithTestServer(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) }, false) if err != nil { t.Fatalf("Unexpected error while creating test admission controller/server: %v", err) } attrs := makeAdmissionRecord(ma...
{ serve := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) } controller, err := newControllerWithTestServer(serve, false) if err != nil { t.Fatalf("Unexpected error while creating test admission controller/server: %v", err) } mockClient := &fake.Clientset{} mockClient.AddReactor("list", "...
identifier_body
admission_test.go
/* Copyright 2017 The Kubernetes 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 agreed to in writing, ...
(baseURL, path string) (string, error) { tempfile, err := ioutil.TempFile("", "") if err != nil { return "", err } p := tempfile.Name() kubeConfigTmpl := ` clusters: - name: test cluster: server: {{ .BaseURL }}{{ .Path }} users: - name: alice user: token: deadbeef contexts: - name: de...
makeKubeConfigFile
identifier_name
precompiled_objects.go
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not...
(path string) bool { return path[len(path)-1] == os.PathSeparator } // getSdkName gets category and sdk from the filepath func getSdkName(path string) string { sdkName := strings.Split(path, string(os.PathSeparator))[0] // the path of the form "sdkName/example/", where the first part is sdkName return sdkName }
isDir
identifier_name
precompiled_objects.go
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not...
// GetPrecompiledObjectOutput returns the run output of the example func (cd *CloudStorage) GetPrecompiledObjectOutput(ctx context.Context, precompiledObjectPath, bucketName string) (string, error) { data, err := cd.getFileFromBucket(ctx, precompiledObjectPath, OutputExtension, bucketName) if err != nil { return ...
{ extension, err := getFileExtensionBySdk(precompiledObjectPath) if err != nil { return "", err } data, err := cd.getFileFromBucket(ctx, precompiledObjectPath, extension, bucketName) if err != nil { return "", err } result := string(data) return result, nil }
identifier_body
precompiled_objects.go
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not...
bucketAttrs, errWithAttrs := bucket.Attrs(ctx) if errWithAttrs != nil { return nil, fmt.Errorf("error during receiving bucket's attributes: %s", err) } return nil, fmt.Errorf("Bucket(%q).Objects: %v", bucketAttrs.Name, err) } path := attrs.Name if isPathToPrecompiledObjectFile(path) { objectDir...
} if err != nil {
random_line_split
precompiled_objects.go
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not...
path := attrs.Name if isPathToPrecompiledObjectFile(path) { objectDirs[filepath.Dir(path)] = true //save base path (directory) of a file } } return objectDirs, nil } // appendPrecompiledObject add precompiled object to the common structure of precompiled objects func appendPrecompiledObject(objectInfo Obje...
{ bucketAttrs, errWithAttrs := bucket.Attrs(ctx) if errWithAttrs != nil { return nil, fmt.Errorf("error during receiving bucket's attributes: %s", err) } return nil, fmt.Errorf("Bucket(%q).Objects: %v", bucketAttrs.Name, err) }
conditional_block
load.py
# -*- coding: utf-8 -*- # @Time : 2018/5/2 9:21 # @Author : chen # @Site : # @File : load.py # @Software: PyCharm ''' 数据集的结构 longitude,latitude:经纬度 housing_median_age: 房屋年龄的中位数 total_rooms: 总房间数 total_bedrooms: 卧室数量 population: 人口数 households: 家庭数 median_income: 收入中位数 median_house_value: 房屋价值中位数 ocean_proximity: 离大海的...
housing_tr = pd.DataFrame(X, columns=housing_num.columns) # 6.2 处理文本 from sklearn.preprocessing import LabelEncoder encoder = LabelEncoder() # 这个是用来将字符串编码为数字(数字的选取都在字符串的长度-1) housing_cat = housing["ocean_proximity"] housing_cat_encoded = encoder.fit_transform(housing_cat) # 这里有两个fit,fit+transform就等于fit_transform prin...
random_line_split
load.py
# -*- coding: utf-8 -*- # @Time : 2018/5/2 9:21 # @Author : chen # @Site : # @File : load.py # @Software: PyCharm ''' 数据集的结构 longitude,latitude:经纬度 housing_median_age: 房屋年龄的中位数 total_rooms: 总房间数 total_bedrooms: 卧室数量 population: 人口数 households: 家庭数 median_income: 收入中位数 median_house_value: 房屋价值中位数 ocean_proximity: 离大海的...
SV文件,返回一个相应的数据类型 ''' csv_path = os.path.join('./', housing_path, "housing.csv") data = pd.read_csv(csv_path) # print(data) return data data = load_housing_data() # df.value_counts() 可以帮助我们统计每一列数据的分布情况 # df.describe() 可以帮助我们整体了解数据集的情况,包含count,mean,min,max,std(标准差)等等 print(data["ocean_proximity"].va...
os.path.join(housing_path, "housing.tgz") urllib.request.urlretrieve(housing_url, tgz_path) housing_tgz = tarfile.open(tgz_path) housing_tgz.extractall(path=housing_path) housing_tgz.close() # fetch_housing_data() import pandas as pd def load_housing_data(housing_path=HOUSING_PATH): ''' 利用pa...
identifier_body
load.py
# -*- coding: utf-8 -*- # @Time : 2018/5/2 9:21 # @Author : chen # @Site : # @File : load.py # @Software: PyCharm ''' 数据集的结构 longitude,latitude:经纬度 housing_median_age: 房屋年龄的中位数 total_rooms: 总房间数 total_bedrooms: 卧室数量 population: 人口数 households: 家庭数 median_income: 收入中位数 median_house_value: 房屋价值中位数 ocean_proximity: 离大海的...
), ('std_scaler', StandardScaler()) ]) cat_pipeline = Pipeline([ ('selector', DataFrameSelector(cat_attribs)), ('label_binarizer', MyLabelBinarizer()), ]) full_pipeline = FeatureUnion(transformer_list=[ ("num_pipeline", num_pipeline), ("cat_pipeline", cat_pipeline), ]) housing_prepared = full_pip...
r()
identifier_name
load.py
# -*- coding: utf-8 -*- # @Time : 2018/5/2 9:21 # @Author : chen # @Site : # @File : load.py # @Software: PyCharm ''' 数据集的结构 longitude,latitude:经纬度 housing_median_age: 房屋年龄的中位数 total_rooms: 总房间数 total_bedrooms: 卧室数量 population: 人口数 households: 家庭数 median_income: 收入中位数 median_house_value: 房屋价值中位数 ocean_proximity: 离大海的...
规划 from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() # 创建一个回归的实例 lin_reg.fit(housing_prepared, housing_labels) # 拟合数据集分别是训练集以及训练标签 some_data = housing.iloc[:5] some_labels = housing_labels.iloc[:5] some_data_prepared = full_pipeline.transform(some_data) # 调用full_pipeline对数据进行预处理 print("Pr...
) housing_prepared = full_pipeline.fit_transform(X=housing) housing_temp = pd.DataFrame(housing_prepared) # 因为这个columns已经更新了不能使用之前的columns print(housing_prepared) # 7. 线性
conditional_block
targets.go
package asp import ( "fmt" "os" "path/filepath" "strings" "time" "github.com/thought-machine/please/src/cli" "github.com/thought-machine/please/src/core" ) // filegroupCommand is the command we put on filegroup rules. const filegroupCommand = pyString("filegroup") // textFileCommand is the command we put on ...
(target *core.BuildTarget) error { s := f.f.scope.NewPackagedScope(f.f.scope.state.Graph.PackageOrDie(target.Label), f.f.scope.mode, 1) s.config = f.s.config s.Set("CONFIG", f.s.config) s.Callback = true s.Set(f.f.args[0], pyString(target.Label.Name)) _, err := s.interpreter.interpretStatements(s, f.f.code) retu...
Call
identifier_name
targets.go
package asp import ( "fmt" "os" "path/filepath" "strings" "time" "github.com/thought-machine/please/src/cli" "github.com/thought-machine/please/src/core" ) // filegroupCommand is the command we put on filegroup rules. const filegroupCommand = pyString("filegroup") // textFileCommand is the command we put on ...
if target.Label.PackageName == "_please" { return nil } for _, whitelist := range state.Config.Sandbox.ExcludeableTargets { if whitelist.Matches(target.Label) { return nil } } for _, dir := range state.Config.Parse.ExperimentalDir { if strings.HasPrefix(target.Label.PackageName, dir) { return nil }...
if target.Sandbox && (target.Test == nil || target.Test.Sandbox) { return nil } }
random_line_split
targets.go
package asp import ( "fmt" "os" "path/filepath" "strings" "time" "github.com/thought-machine/please/src/cli" "github.com/thought-machine/please/src/core" ) // filegroupCommand is the command we put on filegroup rules. const filegroupCommand = pyString("filegroup") // textFileCommand is the command we put on ...
// addEntryPoints adds entry points to a target func addEntryPoints(s *scope, arg pyObject, target *core.BuildTarget) { entryPointsPy, ok := asDict(arg) s.Assert(ok, "entry_points must be a dict") entryPoints := make(map[string]string, len(entryPointsPy)) for name, entryPointPy := range entryPointsPy { entryPo...
{ if t.IsRemoteFile { for _, url := range mustList(args[urlsBuildRuleArgIdx]) { t.AddSource(core.URLLabel(url.(pyString))) } } else if t.IsTextFile { t.FileContent = args[fileContentArgIdx].(pyString).String() } addMaybeNamed(s, "srcs", args[srcsBuildRuleArgIdx], t.AddSource, t.AddNamedSource, false, false...
identifier_body
targets.go
package asp import ( "fmt" "os" "path/filepath" "strings" "time" "github.com/thought-machine/please/src/cli" "github.com/thought-machine/please/src/core" ) // filegroupCommand is the command we put on filegroup rules. const filegroupCommand = pyString("filegroup") // textFileCommand is the command we put on ...
else if cmd, ok := obj.(pyString); ok { return strings.TrimSpace(string(cmd)), nil } cmds, ok := asDict(obj) s.Assert(ok, "Unknown type for command [%s]", obj.Type()) // Have to convert all the keys too m := make(map[string]string, len(cmds)) for k, v := range cmds { if v != None { sv, ok := v.(pyString) ...
{ return "", nil }
conditional_block
tables.py
################################################################################# # The Institute for the Design of Advanced Energy Systems Integrated Platform # Framework (IDAES IP) was produced under the DOE Institute for the # Design of Advanced Energy Systems (IDAES). # # Copyright (c) 2018-2023 by the software own...
return st
for i, a in enumerate(attributes): j = None if isinstance(a, (list, tuple)): # if a is list or tuple, assume index supplied try: assert len(a) > 1 except AssertionError: _log.error(f"An index must be supplide...
conditional_block
tables.py
################################################################################# # The Institute for the Design of Advanced Energy Systems Integrated Platform # Framework (IDAES IP) was produced under the DOE Institute for the # Design of Advanced Energy Systems (IDAES). # # Copyright (c) 2018-2023 by the software own...
(blocks, attributes, heading=None, exception=True): """ Create a Pandas DataFrame that contains a list of user-defined attributes from a set of Blocks. Args: blocks (dict): A dictionary with name keys and BlockData objects for values. Any name can be associated with a block. Use an ...
generate_table
identifier_name
tables.py
################################################################################# # The Institute for the Design of Advanced Energy Systems Integrated Platform # Framework (IDAES IP) was produced under the DOE Institute for the # Design of Advanced Energy Systems (IDAES). # # Copyright (c) 2018-2023 by the software own...
return DataFrame.from_dict(stream_attributes, orient=orient) def create_stream_table_ui( streams, true_state=False, time_point=0, orient="columns", precision=5 ): """ Method to create a stream table in the form of a pandas dataframe. Method takes a dict with name keys and stream values. Use an Ord...
random_line_split
tables.py
################################################################################# # The Institute for the Design of Advanced Energy Systems Integrated Platform # Framework (IDAES IP) was produced under the DOE Institute for the # Design of Advanced Energy Systems (IDAES). # # Copyright (c) 2018-2023 by the software own...
stream_attributes = OrderedDict() stream_states = stream_states_dict(streams=streams, time_point=time_point) full_keys = [] # List of all rows in dataframe to fill in missing data stream_attributes["Units"] = {} for key, sb in stream_states.items(): stream_attributes[key] = {} i...
UNFIXED = "unfixed" FIXED = "fixed" PARAMETER = "parameter" EXPRESSION = "expression"
identifier_body
signin.py
import json import os from copy import deepcopy from PySide2.QtCore import Slot, QTimer, Qt, QEvent, QObject from PySide2.QtGui import QCloseEvent, QBitmap, QPainter from PySide2.QtWidgets import QWidget, QMessageBox, QLineEdit from ctpbee import CtpBee, current_app from ctpbee import VLogger from app.lib.g...
= QBitmap(self.size()) self.bmp.fill() self.p = QPainter(self.bmp) self.p.setPen(Qt.black) self.p.setBrush(Qt.black) self.p.drawRoundedRect(self.bmp.rect(), 10, 10) self.setMask(self.bmp) @Slot() def check_disable(self): if self.login_tab.curre...
super(SignInWidget, self).__init__() self.setupUi(self) self.setWindowTitle("ctpbee客户端") # self.setWindowFlag(Qt.FramelessWindowHint) # 去边框 self.setWindowFlags(Qt.WindowCloseButtonHint) self.setStyleSheet(qss) # tab self.setTabOrder(self.userid_sim, self.p...
identifier_body
signin.py
import json import os from copy import deepcopy from PySide2.QtCore import Slot, QTimer, Qt, QEvent, QObject from PySide2.QtGui import QCloseEvent, QBitmap, QPainter from PySide2.QtWidgets import QWidget, QMessageBox, QLineEdit from ctpbee import CtpBee, current_app from ctpbee import VLogger from app.lib.g...
self.common_sign_in() elif self.login_tab.currentIndex() == 1: self.detailed_sign_in() def common_sign_in(self): info = dict( userid=self.userid_sim.currentText(), password=self.password_sim.text(), interface=self.interface_sim.curr...
x() == 0:
identifier_name
signin.py
import json import os from copy import deepcopy from PySide2.QtCore import Slot, QTimer, Qt, QEvent, QObject from PySide2.QtGui import QCloseEvent, QBitmap, QPainter from PySide2.QtWidgets import QWidget, QMessageBox, QLineEdit from ctpbee import CtpBee, current_app from ctpbee import VLogger from app.lib.g...
self.detailed_sign_in() def common_sign_in(self): info = dict( userid=self.userid_sim.currentText(), password=self.password_sim.text(), interface=self.interface_sim.currentText(), ) which_ = self.other.currentText() if which_ == 'si...
Index() == 1:
conditional_block
signin.py
import json import os from copy import deepcopy from PySide2.QtCore import Slot, QTimer, Qt, QEvent, QObject from PySide2.QtGui import QCloseEvent, QBitmap, QPainter from PySide2.QtWidgets import QWidget, QMessageBox, QLineEdit from ctpbee import CtpBee, current_app from ctpbee import VLogger from app.lib.g...
md_address="tcp://180.168.146.187:10131", td_address="tcp://180.168.146.187:10130", product_info="", appid="simnow_client_test", auth_code="0000000000000000", ) class SignInWidget(QWidget, Ui_SignIn): def __init__(self): super(SignInWidget, self).__init__() self.se...
simnow_24 = dict( brokerid="9999",
random_line_split
context.rs
//!The [`Context`][context] contains all the input data for the request //!handlers, as well as some utilities. This is where request data, like //!headers, client address and the request body can be retrieved from and it //!can safely be picked apart, since its ownership is transferred to the //!handler. //! //!##Acce...
//!Handler context and request body reading extensions. //! //!#Context //!
random_line_split
context.rs
//!Handler context and request body reading extensions. //! //!#Context //! //!The [`Context`][context] contains all the input data for the request //!handlers, as well as some utilities. This is where request data, like //!headers, client address and the request body can be retrieved from and it //!can safely be picke...
else { None }) }, _ => None }; BodyReader { reader: reader, multipart_boundary: boundary } } } #[cfg(not(feature = "multipart"))] impl<'a, 'b> BodyReader<'a, 'b> { ///Internal method that may c...
{ Some(boundary.clone()) }
conditional_block
context.rs
//!Handler context and request body reading extensions. //! //!#Context //! //!The [`Context`][context] contains all the input data for the request //!handlers, as well as some utilities. This is where request data, like //!headers, client address and the request body can be retrieved from and it //!can safely be picke...
<'a, 'b: 'a> { reader: HttpReader<&'a mut BufReader<&'b mut NetworkStream>>, #[cfg(feature = "multipart")] multipart_boundary: Option<String> } #[cfg(feature = "multipart")] impl<'a, 'b> BodyReader<'a, 'b> { ///Try to create a `multipart/form-data` reader from the request body. /// ///``` ...
BodyReader
identifier_name
local_cache.rs
// src/io/local_cache.rs -- a local cache of files obtained from another IoProvider // Copyright 2017-2018 the Tectonic Project // Licensed under the MIT License. use fs2::FileExt; use tempfile; use std::collections::HashMap; use std::ffi::{OsStr, OsString}; use std::fs::{self, File}; use std::io::{BufRead, BufReader,...
return OpenResult::NotAvailable; } }; // OK, we can stream the file to a temporary location on disk, // computing its SHA256 as we go. let mut digest_builder = digest::create(); let mut length = 0; let mut temp_dest = match tempfile::Builder::new(...
{ return OpenResult::Err(e.into()); }
conditional_block
local_cache.rs
// src/io/local_cache.rs -- a local cache of files obtained from another IoProvider // Copyright 2017-2018 the Tectonic Project // Licensed under the MIT License. use fs2::FileExt; use tempfile; use std::collections::HashMap; use std::ffi::{OsStr, OsString}; use std::fs::{self, File}; use std::io::{BufRead, BufReader,...
(&mut self, name: &OsStr, length: u64, digest: Option<DigestData>) -> Result<()> { let digest_text = match digest { Some(ref d) => d.to_string(), None => "-".to_owned(), }; // Due to a quirk about permissions for file locking on Windows, we // need to add `.read(...
record_cache_result
identifier_name
local_cache.rs
// src/io/local_cache.rs -- a local cache of files obtained from another IoProvider // Copyright 2017-2018 the Tectonic Project // Licensed under the MIT License. use fs2::FileExt; use tempfile; use std::collections::HashMap; use std::ffi::{OsStr, OsString}; use std::fs::{self, File}; use std::io::{BufRead, BufReader,...
let mut temp_dest = match tempfile::Builder::new() .prefix("download_") .rand_bytes(6) .tempfile_in(&self.data_path) { Ok(f) => f, Err(e) => return OpenResult::Err(e.into()), }; let mut buf = [0u8; 8192]; while let Ok(nbytes) = stream.read(&mut buf) { if nbytes == 0 { b...
// computing its SHA256 as we go. let mut digest_builder = digest::create(); let mut length = 0;
random_line_split
mod.rs
/* * Copyright (c) 2017-2018 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
, message: InnerMessage) { let bytes = match encode(message) { Ok(message) => message, Err(error) => { error!("{}", error); return; }, }; let message = UserMessage::new("", Some(&bytes.to_vari...
self
identifier_name
mod.rs
/* * Copyright (c) 2017-2018 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
// Set the selected file on the input[type="file"]. fn select_file(&mut self, file: &str) { if let Some(ref input_file) = self.model.activated_file_input.take() { // FIXME: this is not working. input_file.set_value(file); } } fn send(&self, message: InnerMessage) { ...
let document = get_document!(self); load_username(&document, username); load_password(&document, password); }
identifier_body
mod.rs
/* * Copyright (c) 2017-2018 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR ...
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
random_line_split
mod.rs
/* * Copyright (c) 2017-2018 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
fn send(&self, message: InnerMessage) { let bytes = match encode(message) { Ok(message) => message, Err(error) => { error!("{}", error); return; }, }; let message = UserMessage::new("", ...
// FIXME: this is not working. input_file.set_value(file); } }
conditional_block
BRDF_descriptors.py
#!/usr/bin/env python """Retrieve BRDF shape descriptors from MCD43A1 and MCD43A2 MODIS products. BRDF descriptors are here assumed to be the weights to the linear kernel model fit to the data. In this case, we assume that the MODIS set of kernels have been used. """ # KaFKA A fast Kalman filter implementation for ra...
raise IOError("Can't open %s" % fname) if roi is None: data = g.ReadAsArray() else: ulx, uly, lrx, lry = roi xoff = ulx yoff = uly xcount = lrx - ulx ycount = lry - uly data = g.ReadAsArray(xoff, yoff, xcount, ycount).astype( ...
if g is None:
random_line_split
BRDF_descriptors.py
#!/usr/bin/env python """Retrieve BRDF shape descriptors from MCD43A1 and MCD43A2 MODIS products. BRDF descriptors are here assumed to be the weights to the linear kernel model fit to the data. In this case, we assume that the MODIS set of kernels have been used. """ # KaFKA A fast Kalman filter implementation for ra...
(band_no, a1_granule, a2_granule, band_transfer=None, roi=None): if band_transfer is not None: band_no = band_transfer[band_no] fname_a1 = 'HDF4_EOS:EOS_GRID:"%s":MOD_Grid_BRDF:' % (a1_granule) fname_a2 = 'HDF4_EOS:EOS_GRID:"%s":MOD_Grid_BRDF:' % (a2_granule) try: ...
process_masked_kernels
identifier_name
BRDF_descriptors.py
#!/usr/bin/env python """Retrieve BRDF shape descriptors from MCD43A1 and MCD43A2 MODIS products. BRDF descriptors are here assumed to be the weights to the linear kernel model fit to the data. In this case, we assume that the MODIS set of kernels have been used. """ # KaFKA A fast Kalman filter implementation for ra...
if __name__ == "__main__": mcd43a1_dir = "/group_workspaces/cems2/qa4ecv/vol2/modis.c6.brdf/ladsweb.nascom.nasa.gov/allData/6/MCD43A1/2015/" mcd43a2_dir = "/group_workspaces/cems2/qa4ecv/vol2/modis.c6.brdf/ladsweb.nascom.nasa.gov/allData/6/MCD43A2/2015/" rr = RetrieveBRDFDescriptors("h17v05", ...
"""Retrieving BRDF descriptors.""" def __init__(self, tile, mcd43a1_dir, start_time, end_time=None, mcd43a2_dir=None, roi=None): """The class needs to locate the data granules. We assume that these are available somewhere in the filesystem and that we can index them by loca...
identifier_body
BRDF_descriptors.py
#!/usr/bin/env python """Retrieve BRDF shape descriptors from MCD43A1 and MCD43A2 MODIS products. BRDF descriptors are here assumed to be the weights to the linear kernel model fit to the data. In this case, we assume that the MODIS set of kernels have been used. """ # KaFKA A fast Kalman filter implementation for ra...
else: raise ValueError("You can only use a string or a datetime object") return output_time def open_gdal_dataset(fname, roi=None): g = gdal.Open(fname) if g is None: raise IOError("Can't open %s" % fname) if roi is None: data = g.ReadAsArray() else: ulx, uly, ...
try: output_time = datetime.datetime.strptime(timestamp, "%Y-%m-%d") except ValueError: try: output_time = datetime.datetime.strptime(timestamp, "%Y%j") ...
conditional_block
bidirectional.rs
use rand::{self, Rng, SeedableRng}; use rand_xorshift::XorShiftRng; use cgmath::{EuclideanSpace, InnerSpace, Point2, Vector3}; use collision::Ray3; use super::{ algorithm::{contribute, make_tiles, Tile}, LocalProgress, Progress, Renderer, TaskRunner, }; use crate::cameras::Camera; use crate::film::{Film, Samp...
fn render_tile<R: Rng>( index: usize, mut rng: R, tile: Tile, film: &Film, camera: &Camera, world: &World, resources: &Resources, renderer: &Renderer, bidir_params: &BidirParams, progress: LocalProgress, ) { let mut lamp_path = Vec::with_capacity(bidir_params.bounces as usi...
{ fn gen_rng() -> XorShiftRng { XorShiftRng::from_rng(rand::thread_rng()).expect("could not generate RNG") } let tiles = make_tiles(film.width(), film.height(), renderer.tile_size, camera); let status_message = "Rendering"; on_status(Progress { progress: 0, message: &status...
identifier_body
bidirectional.rs
use rand::{self, Rng, SeedableRng}; use rand_xorshift::XorShiftRng; use cgmath::{EuclideanSpace, InnerSpace, Point2, Vector3}; use collision::Ray3; use super::{ algorithm::{contribute, make_tiles, Tile}, LocalProgress, Progress, Renderer, TaskRunner, }; use crate::cameras::Camera; use crate::film::{Film, Samp...
else { &mut [] }; contribute(bounce, &mut main, additional_samples, exe); if i == 0 { main.1 *= brdf_in; for (_, reflectance) in additional_samples { *reflectance *= brdf_in; } } ...
{ &mut *additional }
conditional_block
bidirectional.rs
use rand::{self, Rng, SeedableRng}; use rand_xorshift::XorShiftRng; use cgmath::{EuclideanSpace, InnerSpace, Point2, Vector3}; use collision::Ray3; use super::{ algorithm::{contribute, make_tiles, Tile}, LocalProgress, Progress, Renderer, TaskRunner, }; use crate::cameras::Camera; use crate::film::{Film, Samp...
() -> XorShiftRng { XorShiftRng::from_rng(rand::thread_rng()).expect("could not generate RNG") } let tiles = make_tiles(film.width(), film.height(), renderer.tile_size, camera); let status_message = "Rendering"; on_status(Progress { progress: 0, message: &status_message, })...
gen_rng
identifier_name
bidirectional.rs
use cgmath::{EuclideanSpace, InnerSpace, Point2, Vector3}; use collision::Ray3; use super::{ algorithm::{contribute, make_tiles, Tile}, LocalProgress, Progress, Renderer, TaskRunner, }; use crate::cameras::Camera; use crate::film::{Film, Sample}; use crate::lamp::{RaySample, Surface}; use crate::tracer::{trace...
use rand::{self, Rng, SeedableRng}; use rand_xorshift::XorShiftRng;
random_line_split
parser.go
package node import ( "fmt" "go/token" "go/scanner" "go/ast" "io/ioutil" "errors" "io" "bytes" "strings" "./vector" "go/parser" ) // The parser structure holds the parser's internal state. type parser struct { file *token.File errors scanner.ErrorList scanner scanner.Scanner // Tracing/de...
imports []*ast.ImportSpec // list of imports // Label scopes // (maintained by open/close LabelScope) labelScope *ast.Scope // label scope for current function targetStack [][]*ast.Ident // stack of unresolved labels } // parseOperand may return an expression or a raw type (incl. array...
// Ordinary identifier scopes pkgScope *ast.Scope // pkgScope.Outer == nil topScope *ast.Scope // top-most scope; may be pkgScope unresolved []*ast.Ident // unresolved identifiers
random_line_split
parser.go
package node import ( "fmt" "go/token" "go/scanner" "go/ast" "io/ioutil" "errors" "io" "bytes" "strings" "./vector" "go/parser" ) // The parser structure holds the parser's internal state. type parser struct { file *token.File errors scanner.ErrorList scanner scanner.Scanner // Tracing/de...
(a ...interface{}) { const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " const n = len(dots) pos := p.file.Position(p.pos) fmt.Printf("%5d:%3d: ", pos.Line, pos.Column) i := 2 * p.indent for i > n { fmt.Print(dots) i -= n } // i <= n fmt.Print(dots[0:i]) fmt.Println(a...) } f...
printTrace
identifier_name
parser.go
package node import ( "fmt" "go/token" "go/scanner" "go/ast" "io/ioutil" "errors" "io" "bytes" "strings" "./vector" "go/parser" ) // The parser structure holds the parser's internal state. type parser struct { file *token.File errors scanner.ErrorList scanner scanner.Scanner // Tracing/de...
assert(ident.Obj == nil, "identifier already declared or resolved") if ident.Name == "_" { return } // try to resolve the identifier for s := p.topScope; s != nil; s = s.Outer { if obj := s.Lookup(ident.Name); obj != nil { ident.Obj = obj return } } // all local scopes are known, so any unresolved i...
{ return }
conditional_block
parser.go
package node import ( "fmt" "go/token" "go/scanner" "go/ast" "io/ioutil" "errors" "io" "bytes" "strings" "./vector" "go/parser" ) // The parser structure holds the parser's internal state. type parser struct { file *token.File errors scanner.ErrorList scanner scanner.Scanner // Tracing/de...
func trace(p *parser, msg string) *parser { p.printTrace(msg, "(") p.indent++ return p } // Usage pattern: defer un(trace(p, "...")) func un(p *parser) { p.indent-- p.printTrace(")") } func (p *parser) init(fset *token.FileSet, filename string, src []byte) { p.file = fset.AddFile(filename, -1, len(src)) ...
{ const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " const n = len(dots) pos := p.file.Position(p.pos) fmt.Printf("%5d:%3d: ", pos.Line, pos.Column) i := 2 * p.indent for i > n { fmt.Print(dots) i -= n } // i <= n fmt.Print(dots[0:i]) fmt.Println(a...) }
identifier_body
bindings.go
package action import ( "encoding/json" "errors" "fmt" "io/ioutil" "os" "path/filepath" "regexp" "strings" "unicode" "github.com/zyedidia/json5" "github.com/zyedidia/micro/v2/internal/config" "github.com/zyedidia/micro/v2/internal/screen" "github.com/zyedidia/tcell/v2" ) var Binder = map[string]func(e E...
(k string) (b Event, ok bool) { modifiers := tcell.ModNone // First, we'll strip off all the modifiers in the name and add them to the // ModMask modSearch: for { switch { case strings.HasPrefix(k, "-") && k != "-": // We optionally support dashes between modifiers k = k[1:] case strings.HasPrefix(k, "...
findSingleEvent
identifier_name
bindings.go
package action import ( "encoding/json" "errors" "fmt" "io/ioutil" "os" "path/filepath" "regexp" "strings" "unicode" "github.com/zyedidia/json5" "github.com/zyedidia/micro/v2/internal/config" "github.com/zyedidia/micro/v2/internal/screen" "github.com/zyedidia/tcell/v2" ) var Binder = map[string]func(e E...
for k, v := range parsed { switch val := v.(type) { case string: BindKey(k, val, Binder["buffer"]) case map[string]interface{}: bind, ok := Binder[k] if !ok || bind == nil { screen.TermMessage(fmt.Sprintf("%s is not a valid pane type", k)) continue } for e, a := range val { s, ok := ...
{ defaults := DefaultBindings(p) for k, v := range defaults { BindKey(k, v, bind) } }
conditional_block
bindings.go
package action import ( "encoding/json" "errors" "fmt" "io/ioutil" "os" "path/filepath" "regexp" "strings" "unicode" "github.com/zyedidia/json5" "github.com/zyedidia/micro/v2/internal/config" "github.com/zyedidia/micro/v2/internal/screen" "github.com/zyedidia/tcell/v2" ) var Binder = map[string]func(e E...
"F2": tcell.KeyF2, "F3": tcell.KeyF3, "F4": tcell.KeyF4, "F5": tcell.KeyF5, "F6": tcell.KeyF6, "F7": tcell.KeyF7, "F8": tcell.KeyF8, "F9": tcell.KeyF9, "F10": tcell.KeyF10, "F11": tcell.KeyF11...
"Pause": tcell.KeyPause, "Backtab": tcell.KeyBacktab, "F1": tcell.KeyF1,
random_line_split
bindings.go
package action import ( "encoding/json" "errors" "fmt" "io/ioutil" "os" "path/filepath" "regexp" "strings" "unicode" "github.com/zyedidia/json5" "github.com/zyedidia/micro/v2/internal/config" "github.com/zyedidia/micro/v2/internal/screen" "github.com/zyedidia/tcell/v2" ) var Binder = map[string]func(e E...
func findEvent(k string) (Event, error) { var event Event event, ok, err := findEvents(k) if err != nil { return nil, err } if !ok { event, ok = findSingleEvent(k) if !ok { return nil, errors.New(k + " is not a bindable event") } } return event, nil } // TryBindKey tries to bind a key by writing ...
{ modifiers := tcell.ModNone // First, we'll strip off all the modifiers in the name and add them to the // ModMask modSearch: for { switch { case strings.HasPrefix(k, "-") && k != "-": // We optionally support dashes between modifiers k = k[1:] case strings.HasPrefix(k, "Ctrl") && k != "CtrlH": // ...
identifier_body
ed25519.rs
// -*- mode: rust; -*- // // This file is part of ed25519-dalek. // Copyright (c) 2017-2019 isis lovecruft // See LICENSE for licensing information. // // Authors: // - isis agora lovecruft <isis@patternsinthevoid.net> //! ed25519 keypairs and batch verification. use core::default::Default; use rand::CryptoRng; use ...
fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Keypair, E> where E: SerdeError, { let secret_key = SecretKey::from_bytes(&bytes[..SECRET_KEY_LENGTH]); let public_key = PublicKey::from_bytes(&bytes[SECRET_KEY_LENGTH..]); if se...
formatter.write_str("An ed25519 keypair, 64 bytes in total where the secret key is \ the first 32 bytes and is in unexpanded form, and the second \ 32 bytes is a compressed point for a public key.") }
identifier_body
ed25519.rs
// -*- mode: rust; -*- // // This file is part of ed25519-dalek. // Copyright (c) 2017-2019 isis lovecruft // See LICENSE for licensing information. // // Authors: // - isis agora lovecruft <isis@patternsinthevoid.net> //! ed25519 keypairs and batch verification. use core::default::Default; use rand::CryptoRng; use ...
// Select a random 128-bit scalar for each signature. let zs: Vec<Scalar> = signatures .iter() .map(|_| Scalar::from(thread_rng().gen::<u128>())) .collect(); // Compute the basepoint coefficient, ∑ s[i]z[i] (mod l) let B_coefficient: Scalar = signatures .iter() ....
use rand::thread_rng; use curve25519_dalek::traits::IsIdentity; use curve25519_dalek::traits::VartimeMultiscalarMul;
random_line_split
ed25519.rs
// -*- mode: rust; -*- // // This file is part of ed25519-dalek. // Copyright (c) 2017-2019 isis lovecruft // See LICENSE for licensing information. // // Authors: // - isis agora lovecruft <isis@patternsinthevoid.net> //! ed25519 keypairs and batch verification. use core::default::Default; use rand::CryptoRng; use ...
es: &'a [u8]) -> Result<Keypair, SignatureError> { if bytes.len() != KEYPAIR_LENGTH { return Err(SignatureError(InternalError::BytesLengthError { name: "Keypair", length: KEYPAIR_LENGTH, })); } let secret = SecretKey::from_bytes(&bytes[..SE...
es<'a>(byt
identifier_name
ed25519.rs
// -*- mode: rust; -*- // // This file is part of ed25519-dalek. // Copyright (c) 2017-2019 isis lovecruft // See LICENSE for licensing information. // // Authors: // - isis agora lovecruft <isis@patternsinthevoid.net> //! ed25519 keypairs and batch verification. use core::default::Default; use rand::CryptoRng; use ...
Err(SignatureError(InternalError::VerifyError)) } } /// An ed25519 keypair. #[derive(Debug, Default)] // we derive Default in order to use the clear() method in Drop pub struct Keypair { /// The secret half of this keypair. pub secret: SecretKey, /// The public half of this keypair. pub pub...
Ok(()) } else {
conditional_block
describe.go
// Copyright © 2019 The Knative 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 agr...
client, err := newServingClient(p, namespace, cmd.Flag("target").Value.String()) if err != nil { return err } service, err := client.GetService(cmd.Context(), serviceName) if err != nil { return err } // Print out machine readable output if requested if machineReadablePrintFlags.Output...
if err != nil { return err }
random_line_split
describe.go
// Copyright © 2019 The Knative 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 agr...
section := revSection.WriteColsLn(formatBullet(revisionDesc.percent, ready.Status), revisionHeader(revisionDesc)) if ready.Status == corev1.ConditionFalse { section.WriteAttribute("Error", ready.Reason) } revision.WriteImage(section, revisionDesc.revision) revision.WriteReplicas(section, revisionDesc.revis...
if cond.Type == apis.ConditionReady { ready = cond break } }
conditional_block
describe.go
// Copyright © 2019 The Knative 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 agr...
func addTargetInfo(desc *revisionDesc, target *servingv1.TrafficTarget) { if target != nil { if target.Percent != nil { desc.percent = *target.Percent } desc.latestTraffic = target.LatestRevision desc.tag = target.Tag } } func extractRevisionFromTarget(ctx context.Context, client clientservingv1.KnServin...
generation, err := strconv.ParseInt(revision.Labels[serving.ConfigurationGenerationLabelKey], 0, 0) if err != nil { return nil, fmt.Errorf("cannot extract configuration generation for revision %s: %w", revision.Name, err) } revisionDesc := revisionDesc{ revision: &revision, configurationGenera...
identifier_body
describe.go
// Copyright © 2019 The Knative 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 agr...
service *servingv1.Service) string { return service.Status.URL.String() }
xtractURL(
identifier_name
update.go
/* Copyright 2017 The Kubernetes 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 agreed to in writing, ...
(r rest.Updater, scope *RequestScope, admit admission.Interface) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { ctx := req.Context() // For performance tracking purposes. ctx, span := tracing.Start(ctx, "Update", traceFields(req)...) defer span.End(500 * time.Millisecond) namespa...
UpdateResource
identifier_name
update.go
/* Copyright 2017 The Kubernetes 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 agreed to in writing, ...
return } } if err := checkName(obj, name, namespace, scope.Namer); err != nil { scope.err(err, w, req) return } userInfo, _ := request.UserFrom(ctx) transformers := []rest.TransformFunc{} // allows skipping managedFields update if the resulting object is too big shouldUpdateManagedFields :...
if objectMeta, err := meta.Accessor(obj); err == nil { // ensure namespace on the object is correct, or error if a conflicting namespace was set in the object if err := rest.EnsureObjectNamespaceMatchesRequestNamespace(rest.ExpectedNamespaceForResource(namespace, scope.Resource), objectMeta); err != nil { s...
random_line_split
update.go
/* Copyright 2017 The Kubernetes 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 agreed to in writing, ...
return result, err }) if err != nil { span.AddEvent("Write to database call failed", attribute.Int("len", len(body)), attribute.String("err", err.Error())) scope.err(err, w, req) return } span.AddEvent("Write to database call succeeded", attribute.Int("len", len(body))) status := http.StatusOK ...
{ if accessor, accessorErr := meta.Accessor(obj); accessorErr == nil { accessor.SetManagedFields(nil) shouldUpdateManagedFields = false result, err = requestFunc() } }
conditional_block
update.go
/* Copyright 2017 The Kubernetes 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 agreed to in writing, ...
{ if uo == nil { return nil } co := &metav1.CreateOptions{ DryRun: uo.DryRun, FieldManager: uo.FieldManager, FieldValidation: uo.FieldValidation, } co.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind("CreateOptions")) return co }
identifier_body
plugin.go
package k8scompute import ( "fmt" "regexp" smith_v1 "github.com/atlassian/smith/pkg/apis/smith/v1" "github.com/atlassian/voyager" orch_v1 "github.com/atlassian/voyager/pkg/apis/orchestration/v1" "github.com/atlassian/voyager/pkg/execution/plugins/atlassian/secretenvvar" "github.com/atlassian/voyager/pkg/execut...
(context *wiringplugin.WiringContext) []string { account := context.StateContext.ClusterConfig.Kube2iamAccount region := context.StateContext.Location.Region env := context.StateContext.ClusterConfig.KittClusterEnv nodeRole := fmt.Sprintf("arn:aws:iam::%s:role/%s.paas-%s_node-role", account, region, env) controle...
buildKube2iamRoles
identifier_name
plugin.go
package k8scompute import ( "fmt" "regexp" smith_v1 "github.com/atlassian/smith/pkg/apis/smith/v1" "github.com/atlassian/voyager" orch_v1 "github.com/atlassian/voyager/pkg/apis/orchestration/v1" "github.com/atlassian/voyager/pkg/execution/plugins/atlassian/secretenvvar" "github.com/atlassian/voyager/pkg/execut...
func buildKube2iamRoles(context *wiringplugin.WiringContext) []string { account := context.StateContext.ClusterConfig.Kube2iamAccount region := context.StateContext.Location.Region env := context.StateContext.ClusterConfig.KittClusterEnv nodeRole := fmt.Sprintf("arn:aws:iam::%s:role/%s.paas-%s_node-role", accoun...
{ metrics := make([]autoscaling_v2b1.MetricSpec, len(spec.Scaling.Metrics)) for i, m := range spec.Scaling.Metrics { metrics[i] = m.ToKubeMetric() } return autoscaling_v2b1.HorizontalPodAutoscalerSpec{ ScaleTargetRef: autoscaling_v2b1.CrossVersionObjectReference{ APIVersion: apps_v1.SchemeGroupVersion.Stri...
identifier_body
plugin.go
package k8scompute import ( "fmt" "regexp" smith_v1 "github.com/atlassian/smith/pkg/apis/smith/v1" "github.com/atlassian/voyager" orch_v1 "github.com/atlassian/voyager/pkg/apis/orchestration/v1" "github.com/atlassian/voyager/pkg/execution/plugins/atlassian/secretenvvar" "github.com/atlassian/voyager/pkg/execut...
Resource: secretResource.Name, Path: metadataNamePath, } falseObj := false envFromSource := core_v1.EnvFromSource{ SecretRef: &core_v1.SecretEnvSource{ LocalObjectReference: core_v1.LocalObjectReference{ Name: secretRef.Ref(), }, Optional: &falseObj, }, } envFrom = append(env...
secretRef := smith_v1.Reference{ Name: wiringutil.ReferenceName(secretResource.Name, metadataElement, nameElement),
random_line_split
plugin.go
package k8scompute import ( "fmt" "regexp" smith_v1 "github.com/atlassian/smith/pkg/apis/smith/v1" "github.com/atlassian/voyager" orch_v1 "github.com/atlassian/voyager/pkg/apis/orchestration/v1" "github.com/atlassian/voyager/pkg/execution/plugins/atlassian/secretenvvar" "github.com/atlassian/voyager/pkg/execut...
} // Reference environment variables retrieved from ServiceBinding objects if len(bindingResult) > 0 { var secretResource smith_v1.Resource var err error if shouldUseSecretPlugin { secretRefs, envVars, err := compute.GenerateEnvVars(spec.RenameEnvVar, bindingResult) if err != nil { return nil, fal...
{ shouldUseSecretPlugin = false }
conditional_block
redData_extFunction.py
import time import sys import os from random import randint import signal gameRunning = True currentFolder = "root" previousFolder = str() connected = False updatedRepo = 1 processRun = True passCrack = False def failScreen_missingKernel(): os.system('clear') print("\033[1;37;41m FATAL ERROR.") print("\033[1;37;...
(netLocation): global currentFolder global connected connected = True if netLocation in netList: loadDot = "..." print("Connecting to address", end='') for item in loadDot: sys.stdout.write(item) sys.stdout.flush() time.sleep(0.8) print() connectMsgcheck = netLocation + "-c...
connect
identifier_name
redData_extFunction.py
import time import sys import os from random import randint import signal gameRunning = True currentFolder = "root" previousFolder = str() connected = False updatedRepo = 1 processRun = True passCrack = False def failScreen_missingKernel(): os.system('clear') print("\033[1;37;41m FATAL ERROR.") print("\033[1;37;...
else: if folder == "..": currentFolder = previousFolder elif folder in accessRoutelocal[currentFolder]: previousFolder = currentFolder currentFolder = folder else: print("Directory does not exist.") def openRealOne(file): global updatedRepo if file in localfileSys[currentFold...
print("Incorrect password.") return
conditional_block
redData_extFunction.py
import time import sys import os from random import randint import signal gameRunning = True currentFolder = "root" previousFolder = str() connected = False updatedRepo = 1 processRun = True passCrack = False def failScreen_missingKernel(): os.system('clear') print("\033[1;37;41m FATAL ERROR.") print("\033[1;37;...
def disconnect(): global currentFolder global connected if connected == True: connected = False print("Disconnected from network.") currentFolder = "root" else: print("Not currently connected to any network.") def dl(file): if file in localfileSys[currentFolder]: localfileSys["Downloads...
global currentFolder global connected connected = True if netLocation in netList: loadDot = "..." print("Connecting to address", end='') for item in loadDot: sys.stdout.write(item) sys.stdout.flush() time.sleep(0.8) print() connectMsgcheck = netLocation + "-connectMsg.txt" ...
identifier_body
redData_extFunction.py
import time import sys import os from random import randint import signal gameRunning = True currentFolder = "root" previousFolder = str() connected = False updatedRepo = 1 processRun = True passCrack = False def failScreen_missingKernel(): os.system('clear') print("\033[1;37;41m FATAL ERROR.") print("\033[1;37;...
"clock":"Shows the current UTC time.", "clear":"Clears the screen", "crack":"Cracks a folder or file", "First Objective?":"Try connecting to a network." } for key, value in helpDict.items(): print(key, ":", value) def passCrackinstall(): global passCrack passCrack = True def quickCheat...
"rm":"Deletes a file.",
random_line_split
lib.rs
//! Thread stack traces of remote processes. //! //! `rstack` (named after Java's `jstack`) uses [libunwind]'s ptrace interface to capture stack //! traces of the threads of a remote process. It currently only supports Linux with a kernel //! version of 3.4 or higher, and requires that the `/proc` pseudo-filesystem be ...
} /// The error type returned by methods in this crate. #[derive(Debug)] pub struct Error(ErrorInner); impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self.0 { ErrorInner::Io(ref e) => fmt::Display::fmt(e, fmt), ErrorInner::Unwind(ref e)...
#[derive(Debug)] enum ErrorInner { Io(io::Error), Unwind(unwind::Error),
random_line_split
lib.rs
//! Thread stack traces of remote processes. //! //! `rstack` (named after Java's `jstack`) uses [libunwind]'s ptrace interface to capture stack //! traces of the threads of a remote process. It currently only supports Linux with a kernel //! version of 3.4 or higher, and requires that the `/proc` pseudo-filesystem be ...
{ Io(io::Error), Unwind(unwind::Error), } /// The error type returned by methods in this crate. #[derive(Debug)] pub struct Error(ErrorInner); impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self.0 { ErrorInner::Io(ref e) => fmt::Display::f...
ErrorInner
identifier_name
lib.rs
//! Thread stack traces of remote processes. //! //! `rstack` (named after Java's `jstack`) uses [libunwind]'s ptrace interface to capture stack //! traces of the threads of a remote process. It currently only supports Linux with a kernel //! version of 3.4 or higher, and requires that the `/proc` pseudo-filesystem be ...
Ok(thread) } } fn dump( &self, space: &AddressSpace<PTraceStateRef>, options: &TraceOptions, ) -> unwind::Result<Vec<Frame>> { let state = PTraceState::new(self.0)?; let mut cursor = Cursor::remote(&space, &state)?; let mut trace = vec!...
{ return Err(io::Error::new( io::ErrorKind::Other, format!("unexpected wait status {}", status), )); }
conditional_block
lib.rs
//! Thread stack traces of remote processes. //! //! `rstack` (named after Java's `jstack`) uses [libunwind]'s ptrace interface to capture stack //! traces of the threads of a remote process. It currently only supports Linux with a kernel //! version of 3.4 or higher, and requires that the `/proc` pseudo-filesystem be ...
fn get_name(pid: u32, tid: u32) -> Option<String> { let path = format!("/proc/{}/task/{}/comm", pid, tid); let mut name = vec![]; match File::open(path).and_then(|mut f| f.read_to_end(&mut name)) { Ok(_) => Some(String::from_utf8_lossy(&name).trim().to_string()), Err(e) => { de...
{ for entry in fs::read_dir(dir).map_err(|e| Error(ErrorInner::Io(e)))? { let entry = entry.map_err(|e| Error(ErrorInner::Io(e)))?; let pid = match entry .file_name() .to_str() .and_then(|s| s.parse::<u32>().ok()) { Some(pid) => pid, ...
identifier_body
pyBasic.py
#PRINT print("Welcome to your first Python program") #TYPE CONVERSION aa = 22 print(aa) print(type(aa)) # impression du typage bb = float(aa) # to float print(bb) print(type(bb)) cc = str(bb) # to string print(cc) print(type(cc)) dd = int(aa) # to integer print(dd) print(type(dd)) bool("1") # cast to a boolea...
int("Sum is",addtwo()) print("Sum is",addtwo()) def square(a): return print(a*a) x = 3 # Initialize a Global variable square(x) square(3) # Directly enter a parameter def standard(unit=0): # Set the default value if unit == 0: print("not started") else: ...
= input("Enter a first number: ") intA = int(inpA) inpB = input("Enter a second number: ") intB = int(inpB) added = intA + intB return added # Returns the result of the function pr
identifier_body
pyBasic.py
#PRINT print("Welcome to your first Python program") #TYPE CONVERSION aa = 22 print(aa) print(type(aa)) # impression du typage bb = float(aa) # to float print(bb) print(type(bb)) cc = str(bb) # to string print(cc) print(type(cc)) dd = int(aa) # to integer print(dd) print(type(dd)) bool("1") # cast to a boolea...
e: print("Nice to meet you !") hello() # Calls the function (never executed before) def greet(lang): """ The documentation appears in triple quotes """ if lang =="french": print("Bonjour") elif lang =="german": print("Guten Morgen") else: print("Hello") help(greet) # Print the docume...
("I know you !") els
conditional_block
pyBasic.py
#PRINT print("Welcome to your first Python program") #TYPE CONVERSION aa = 22 print(aa) print(type(aa)) # impression du typage bb = float(aa) # to float print(bb) print(type(bb)) cc = str(bb) # to string print(cc) print(type(cc)) dd = int(aa) # to integer print(dd) print(type(dd)) bool("1") # cast to a boolea...
gs): # Arguments can also be packed into a dictionary for key in args: print(key + " : " + args[key]) printDictionary(Country='Canada',Province='Ontario',City='Toronto') def triangle_area(base, height): # Compute the area of a triangle """ Returns the area of a triangle, given the l...
Dictionary(**ar
identifier_name
pyBasic.py
#PRINT print("Welcome to your first Python program") #TYPE CONVERSION aa = 22 print(aa)
cc = str(bb) # to string print(cc) print(type(cc)) dd = int(aa) # to integer print(dd) print(type(dd)) bool("1") # cast to a boolean value bool(1) bool(0) int(True) int(False) my_age = 39 print(my_age) my_age += 1 #shortcut to update a value print(my_age) #NUMERIC EXPRESSIONS a = 3 aa = a**2 # puissance pr...
print(type(aa)) # impression du typage bb = float(aa) # to float print(bb) print(type(bb))
random_line_split
lib.rs
#![deny(missing_docs, intra_doc_link_resolution_failure)] //! Topological functions execute within a context unique to the path in the runtime call //! graph of other topological functions preceding the current activation record. //! //! Defining a topological function results in a macro definition for binding th...
ty: TypeId, count: usize, } impl Callsite { fn new(ty: TypeId, last_child: &Option<Callsite>) -> Self { let prev_count = match last_child { Some(ref prev) if prev.ty == ty => prev.count, _ => 0, }; Self { ty, count: prev_...
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] struct Callsite {
random_line_split
lib.rs
#![deny(missing_docs, intra_doc_link_resolution_failure)] //! Topological functions execute within a context unique to the path in the runtime call //! graph of other topological functions preceding the current activation record. //! //! Defining a topological function results in a macro definition for binding th...
() { let first_called; let second_called; let (first_byte, second_byte) = (0u8, 1u8); call!( { let curr_byte: u8 = *Env::get::<u8>().unwrap(); assert_eq!(curr_byte, first_byte); first_called = true; ...
call_env
identifier_name
lib.rs
#![deny(missing_docs, intra_doc_link_resolution_failure)] //! Topological functions execute within a context unique to the path in the runtime call //! graph of other topological functions preceding the current activation record. //! //! Defining a topological function results in a macro definition for binding th...
; let parent = replace(&mut *parent, child); scopeguard::guard( (parent_initial_state, parent), move |(prev_initial_state, mut prev)| { if reset_on_drop { prev.state = prev_initial_state; } ...
{ parent.child(callsite_ty, add_env) }
conditional_block
lib.rs
#![deny(missing_docs, intra_doc_link_resolution_failure)] //! Topological functions execute within a context unique to the path in the runtime call //! graph of other topological functions preceding the current activation record. //! //! Defining a topological function results in a macro definition for binding th...
/// Returns a reference to a value in the current environment, as [`Env::get`] does, but panics /// if the value has not been set in the environment. // TODO typename for debugging here would be v. nice pub fn expect<E>() -> impl Deref<Target = E> + 'static where E: Any + 'static, ...
{ Point::with_current(|current| { current .state .env .inner .get(&TypeId::of::<E>()) .map(|guard| { OwningRef::new(guard.to_owned()).map(|anon| anon.downcast_ref().unwrap()) ...
identifier_body
lib.rs
//! Advent of Code - Day 10 Instructions //! //! Balance Bots //! //! You come upon a factory in which many robots are zooming around handing small microchips //! to each other. //! //! Upon closer examination, you notice that each bot only proceeds when it has two microchips, //! and once it does, it gives each one to...
(bot_id: Id, low_dest: Receiver, high_dest: Receiver) -> Instruction { Instruction::Transfer { bot_id, low_dest, high_dest, } } } /// Process a list of instructions. /// /// Be careful--there's no guard currently in place against an incomplete list of instruction...
transfer
identifier_name
lib.rs
//! Advent of Code - Day 10 Instructions //! //! Balance Bots //! //! You come upon a factory in which many robots are zooming around handing small microchips //! to each other. //! //! Upon closer examination, you notice that each bot only proceeds when it has two microchips, //! and once it does, it gives each one to...
} Entry::Vacant(entry) => { entry.insert(value); Ok(()) } }, }; give_to_receiver(low, low_dest)?; ...
{ Ok(()) }
conditional_block
lib.rs
//! Advent of Code - Day 10 Instructions //! //! Balance Bots //! //! You come upon a factory in which many robots are zooming around handing small microchips //! to each other. //! //! Upon closer examination, you notice that each bot only proceeds when it has two microchips, //! and once it does, it gives each one to...
assert_eq!(got, *parsed); } } }
random_line_split
lib.rs
//! Advent of Code - Day 10 Instructions //! //! Balance Bots //! //! You come upon a factory in which many robots are zooming around handing small microchips //! to each other. //! //! Upon closer examination, you notice that each bot only proceeds when it has two microchips, //! and once it does, it gives each one to...
} /// Process a list of instructions. /// /// Be careful--there's no guard currently in place against an incomplete list of instructions /// leading to an infinite loop. pub fn process(instructions: &[Instruction]) -> Result<(Bots, Outputs), Error> { let mut bots = Bots::new(); let mut outputs = Outputs::new(...
{ Instruction::Transfer { bot_id, low_dest, high_dest, } }
identifier_body
detatt_mk.py
################################################################################# # A set of functions for the detection and attribution of climate signals # Megan Kirchmeier-Young # # Many functions adapted from other code as noted. # # to use: #import detatt_mk as da # #reduce dimensions #...
if np.size(np.shape(C))>2: raise ValueError('input C has too many dimensions') if np.shape(C)[0]!=n or np.shape(C)[1]!=n: raise ValueError('dimensions of C must be consistent with dimensions of x0') #if ne is a single value, assume all signals have same ensemble size # and expand ne to size m if np.size(n...
raise ValueError('input x0 has too many dimensions')
conditional_block
detatt_mk.py
################################################################################# # A set of functions for the detection and attribution of climate signals # Megan Kirchmeier-Young # # Many functions adapted from other code as noted. # # to use: #import detatt_mk as da # #reduce dimensions #...
#################################################################################
import numpy as np from scipy import linalg, stats import warnings if np.shape(x)[0] != np.shape(y)[0]: raise ValueError('x and y must have same first dimension') n,m = np.shape(x) #time dimension, number of signals if np.shape(cn1)[0]!=n: raise ValueError('dimension mismatch: x and cn1') p1 = np.shape(c...
identifier_body
detatt_mk.py
################################################################################# # A set of functions for the detection and attribution of climate signals # Megan Kirchmeier-Young # # Many functions adapted from other code as noted. # # to use: #import detatt_mk as da # #reduce dimensions #...
(xL, center_flag=1): # given the control data xL formed into a nxp matrix, calculates the # regularized covariance matrix cl_hat # see Ribes et al. (2009) following Ledoit and Wolf (2004) # # gives the option to center the input matrix first (default); would set # flag to 0 if input matrix has already be...
regC
identifier_name
detatt_mk.py
################################################################################# # A set of functions for the detection and attribution of climate signals
# # to use: #import detatt_mk as da # #reduce dimensions #model response ensemble mean xem2 and obs y2 should be column data (and centered), so use [:,None] if a single forcing #xcl1 and xcl2 are the climate noise array (n_years x n_realizations) split into two parts #(xr,yr,cn1,cn2) = da.re...
# Megan Kirchmeier-Young # # Many functions adapted from other code as noted.
random_line_split
dtobuilder.go
package dtobuilder import ( "math" "sort" "strconv" "time" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/model" "github.com/prometheus/prometheus/model/exemplar" "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/model/metadata" "github.com/promethe...
else if l.Name == model.QuantileLabel && mt == dto.MetricType_SUMMARY { continue } else if l.Name == model.BucketLabel && mt == dto.MetricType_HISTOGRAM { continue } res = append(res, &dto.LabelPair{ Name: pointer.String(l.Name), Value: pointer.String(l.Value), }) } sort.Slice(res, func(i, j i...
{ continue }
conditional_block
dtobuilder.go
package dtobuilder import ( "math" "sort" "strconv" "time" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/model" "github.com/prometheus/prometheus/model/exemplar" "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/model/metadata" "github.com/promethe...
} sort.Slice(res, func(i, j int) bool { switch { case *res[i].Name < *res[j].Name: return true case *res[i].Value < *res[j].Value: return true default: return false } }) return res } func labelPairsEqual(a, b []*dto.LabelPair) bool { if len(a) != len(b) { return false } for i := 0; i < le...
Name: pointer.String(l.Name), Value: pointer.String(l.Value), })
random_line_split
dtobuilder.go
package dtobuilder import ( "math" "sort" "strconv" "time" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/model" "github.com/prometheus/prometheus/model/exemplar" "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/model/metadata" "github.com/promethe...
(a, b []*dto.LabelPair) bool { if len(a) != len(b) { return false } for i := 0; i < len(a); i++ { if *a[i].Name != *b[i].Name || *a[i].Value != *b[i].Value { return false } } return true } func familyType(mf *dto.MetricFamily) dto.MetricType { ty := mf.Type if ty == nil { return dto.MetricType_UNTY...
labelPairsEqual
identifier_name
dtobuilder.go
package dtobuilder import ( "math" "sort" "strconv" "time" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/model" "github.com/prometheus/prometheus/model/exemplar" "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/model/metadata" "github.com/promethe...
func findBucket(h *dto.Histogram, bound float64) *dto.Bucket { for _, b := range h.GetBucket() { // Special handling because Inf - Inf returns NaN. if bound == math.Inf(1) && b.GetUpperBound() == math.Inf(1) { return b } // If it's close enough, use the bucket. if math.Abs(b.GetUpperBound()-bound) < 1e...
{ res := &dto.Exemplar{ Label: toLabelPairs(mt, e.Labels), Value: &e.Value, } if e.HasTs { res.Timestamp = timestamppb.New(time.UnixMilli(e.Ts)) } return res }
identifier_body
jti-grpc-client-python.py
# #################################################################### # # # 888888 88888888888 8888888 # "88b 888 888 # 888 888 888 # 888 888 888 # 888 888 888 # 888 888 888 # 88P 888 888 # 888 888 888...
(): # Explicitly refer to the global variable to avoid creating a local variable that shadows the outer scope. global logger # Create logger. logger = logging.getLogger(__name__) # Create a rotating log file handler based on how much time has elapsed. # In this case, rotate the log file every d...
setupLogging
identifier_name
jti-grpc-client-python.py
# #################################################################### # # # 888888 88888888888 8888888 # "88b 888 888 # 888 888 888 # 888 888 888 # 888 888 888 # 888 888 888 # 88P 888 888 # 888 888 888...
# for debugging purposes. main(sys.argv[1:])
random_line_split
jti-grpc-client-python.py
# #################################################################### # # # 888888 88888888888 8888888 # "88b 888 888 # 888 888 888 # 888 888 888 # 888 888 888 # 888 888 888 # 88P 888 888 # 888 888 888...
elif JTI_SYSLOG_SENSOR_SUBSTRING in message.path: #producer.send(KAFKA_TOPIC_JUNIPER, json_data) producer.send(KAFKA_TOPIC_JUNIPER_SYSLOG, json_data) #producer.send("juniper", json_data) else: producer.send(KAFKA_TOPIC_JUNIPER, jso...
producer.send(KAFKA_TOPIC_JUNIPER_INTERFACES, json_data) #producer.send('juniper', json_data)
conditional_block
jti-grpc-client-python.py
# #################################################################### # # # 888888 88888888888 8888888 # "88b 888 888 # 888 888 888 # 888 888 888 # 888 888 888 # 888 888 888 # 88P 888 888 # 888 888 888...
# TODO - WORK IN PROGRESS ... # ----------[ FUNCTION 'parseArguments()' ]---------- def parseArguments(): logger.info("FUNCTION 'parseArguments(): BEGIN") # Note: Because of the number and complexity of the arguments, we will not use single character option letters # (eg. -o). # Instead, to promote...
global args # STEP 1: Setup the logging so we can start to log debug info right away. setupLogging() logger.debug("\n\n\n--------------------[ JTI-GRPC-CLIENT: BEGIN EXECUTION ]--------------------") # STEP 2: Parse the argument list with which this script was invoked and set global variable 'args'. ...
identifier_body
testing.js
(function(window) { var game; var res; var $scope; var finishGame; var Config = { cooldown: 1000, //milisec pathed: { bugs: 0, code: 0 }, killed: { bugs: 0, code: 0 } }; var GameState = function(game) ...
else { // For the main bolt y += this.game.rnd.integerInRange(20, distance / segments); } if ((!branch && i == segments - 1) || y > distance) { // This causes the bolt to always terminate at the center // lightning bolt bounding bo...
{ // For a branch y += this.game.rnd.integerInRange(10, 20); }
conditional_block
testing.js
(function(window) { var game; var res; var $scope; var finishGame; var Config = { cooldown: 1000, //milisec pathed: { bugs: 0, code: 0 }, killed: { bugs: 0, code: 0 } }; var GameState = function(game) ...
(game) { minutes = Math.floor(game.timer.duration.toFixed(0) / 60000) % 60; seconds = Math.floor(game.timer.duration.toFixed(0) / 1000) % 60; milliseconds = Math.floor(game.timer.duration.toFixed(0)) % 100; //If any of the digits becomes a single digit number, pad it with a zero ...
updateTimer
identifier_name
testing.js
(function(window) { var game; var res; var $scope; var finishGame; var Config = { cooldown: 1000, //milisec pathed: { bugs: 0, code: 0 }, killed: { bugs: 0, code: 0 } }; var GameState = function(game) ...
this.cooldownTimer.paused = true; //cooldownText } function timeIsOut() { var codestat = Config.pathed.code; var bugstat = Config.killed.bugs - Config.pathed.bugs;; stateText.text = " Time is up!\n Pathed Code: " + codestat.toString() + "\n Catched Buds: " + bugstat....
function timeCooldownFn() {
random_line_split
testing.js
(function(window) { var game; var res; var $scope; var finishGame; var Config = { cooldown: 1000, //milisec pathed: { bugs: 0, code: 0 }, killed: { bugs: 0, code: 0 } }; var GameState = function(game) ...
// Setup game window['GameStage7'] = { init: init, destroy: destroy, game: { score: 0, finished: false }, rules: "Kill that irritating bugs! KILL!!! And don't touch qute ponnies, they are your code =)" }; res = window['GameStage7'].game;...
{}
identifier_body