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 |
|---|---|---|---|---|
ws.rs | achieve this, a pipeline needs to be connected to the `in` port of this connector and send events to it. There are multiple ways to target a certain connection with a specific event:
//!
//! * Send the event you just received from the `ws_server` right back to it. It will be able to track the the event to its websocke... | Message::Close(_) => {
// read from the stream once again to drive the closing handshake | random_line_split | |
ws.rs | ### Configuration
//!
//! | Option | Description | Type | Required | Default value |
//! |------------------|-----------------------------... | {
meta.insert("binary", Value::const_true())?;
} | conditional_block | |
ws.rs | "name": "separate",
//! "config": {
//! "buffered": false
//! }
//! }
//! ],
//! codec = "json",
//! config = {
//! "url": "127.0.0.1:4242",
//! }
//! end;
//! ```
//!
//! An annotated example of a secure WS server configuration:
//!
//! ```tremor title="config.troy"
//! define conn... | new | identifier_name | |
ws.rs | //! ```
//!
//! An annotated example of a secure WS server configuration:
//!
//! ```tremor title="config.troy"
//! define connector ws_server from ws_server
//! with
//! preprocessors = ["separate"],
//! codec = "json",
//! config = {
//! "url": "0.0.0.0:65535",
//! "tls": {
//! # Security certific... | {
Self { sink }
} | identifier_body | |
cabi.rs | .to_string()).into(), err_out);
mem::zeroed()
}
}
}
macro_rules! export (
(
$name:ident($($aname:ident: $aty:ty),*) -> Result<$rv:ty> $body:block
) => (
#[no_mangle]
pub unsafe extern "C" fn $name($($aname: $aty,)* err_out: *mut CError) -> $rv
{
... | } else { | random_line_split | |
cabi.rs | 8,
pub failed: c_int,
pub code: c_int,
}
fn get_error_code_from_kind(kind: &ErrorKind) -> c_int {
match *kind {
ErrorKind::SourceMap(SourceMapError::IndexedSourcemap) => 2,
ErrorKind::SourceMap(SourceMapError::BadJson(_)) => 3,
ErrorKind::SourceMap(SourceMapError::CannotFlatten(_)) ... | <'a>(out: *mut Token, tm: &'a TokenMatch<'a>) {
(*out).dst_line = tm.dst_line;
(*out).dst_col = tm.dst_col;
(*out).src_line = tm.src_line;
(*out).src_col = tm.src_col;
(*out).name = match tm.name {
Some(name) => name.as_ptr(),
None => ptr::null()
};
(*out).name_len = tm.name.... | set_token | identifier_name |
main.rs | /foo.rs`
* Each such `*.rs` file will become one (1) top-level binary
* - Other top-level files in `src/` are importable within the project,
* but do not become exportable automatically.
* - You can combine keywords in your lib.rs to re-export everything,
* but you only get that one anointed lib.rs... | (msg: &str) {
println!("Blort says: {}", msg);
}
}
// next, the series of *declarations*, each of which points to one of the
// module implementations discussed above. The declaration phase is easy to
// forget, because the implementations are all part of the project, and so
// their source files are ver... | blort | identifier_name |
main.rs | /foo.rs`
* Each such `*.rs` file will become one (1) top-level binary
* - Other top-level files in `src/` are importable within the project,
* but do not become exportable automatically.
* - You can combine keywords in your lib.rs to re-export everything,
* but you only get that one anointed lib.rs... |
}
// next, the series of *declarations*, each of which points to one of the
// module implementations discussed above. The declaration phase is easy to
// forget, because the implementations are all part of the project, and so
// their source files are very close by. But you are *required* to make an
// explicit dec... | {
println!("Blort says: {}", msg);
} | identifier_body |
main.rs | /bin/foo.rs`
* Each such `*.rs` file will become one (1) top-level binary
* - Other top-level files in `src/` are importable within the project,
* but do not become exportable automatically.
* - You can combine keywords in your lib.rs to re-export everything,
* but you only get that one anointed li... | // module implementations discussed above. The declaration phase is easy to
// forget, because the implementations are all part of the project, and so
// their source files are very close by. But you are *required* to make an
// explicit declaration nontheless. If you throw in references to `crate::x::y`
// without h... | println!("Blort says: {}", msg);
}
}
// next, the series of *declarations*, each of which points to one of the | random_line_split |
validate.rs | to validate.
#[structopt(
name = "config-toml",
long,
env = "VECTOR_CONFIG_TOML",
use_delimiter(true)
)]
paths_toml: Vec<PathBuf>,
/// Vector config files in JSON format to validate.
#[structopt(
name = "config-json",
long,
env = "VECTOR_CONF... |
}
/// Performs topology, component, and health checks.
pub async fn validate(opts: &Opts, color: bool) -> ExitCode {
let mut fmt = Formatter::new(color);
let mut validated = true;
let mut config = match validate_config(opts, &mut fmt) {
Some(config) => config,
None => return exitcode::CO... | {
config::merge_path_lists(vec![
(&self.paths, None),
(&self.paths_toml, Some(config::Format::Toml)),
(&self.paths_json, Some(config::Format::Json)),
(&self.paths_yaml, Some(config::Format::Yaml)),
])
.map(|(path, hint)| config::ConfigPath::File(pa... | identifier_body |
validate.rs | opt(
name = "config-dir",
short = "C",
long,
env = "VECTOR_CONFIG_DIR",
use_delimiter(true)
)]
pub config_dirs: Vec<PathBuf>,
}
impl Opts {
fn paths_with_formats(&self) -> Vec<config::ConfigPath> {
config::merge_path_lists(vec![
(&self.paths, None... | e(&mu | identifier_name | |
validate.rs | format to validate.
#[structopt(
name = "config-toml",
long,
env = "VECTOR_CONFIG_TOML",
use_delimiter(true)
)]
paths_toml: Vec<PathBuf>,
/// Vector config files in JSON format to validate.
#[structopt(
name = "config-json",
long,
env = "VECT... | }
/// Standalone line
fn success(&mut self, msg: impl AsRef<str>) {
self.print(format!("{} {}\n", self.success_intro, msg.as_ref()))
}
/// Standalone line
fn warning(&mut self, warning: impl AsRef<str>) {
self.print(format!("{} {}\n", self.warning_intro, warning.as_ref()))
... | } else {
println!("{:>width$}", "Validated", width = self.max_line_width)
} | random_line_split |
mod.rs | Clone)]
pub enum RecordFieldType {
Record(TypeId),
Type(Arc::<TigerType>)
}
impl PartialEq for RecordFieldType {
fn eq(&self, other: &Self) -> bool {
use RecordFieldType::*;
match (self, other) {
(Record(id1), Record(id2)) => id1 == id2,
(Record(..), Type(t2)) => if... | typecheck | identifier_name | |
mod.rs | permissions for an int value
pub enum R {
/// Read-only
RO,
/// Read-write
RW
}
/// Unique identifier for Records and Arrays
pub type TypeId = snowflake::ProcessUniqueId;
/// Generate new type id for a Record or Array
pub fn newtypeid() -> TypeId {
snowflake::ProcessUniqueId::new()
}
/// Types i... | } else { false }
}
/// An entry in our `TypeEnviroment` table.
#[derive(Clone, Debug)]
pub enum EnvEntry {
/// A declared varaible
Var {
/// The type of the variable
ty: Arc<TigerType>,
},
/// A declared function
Func {
/// The types of the arguments of the function
... |
/// Returns true iif the type is an Int
pub fn es_int(t: &TigerType) -> bool {
if let TigerType::TInt(_) = *t {
true | random_line_split |
models.py | ar_AE'
Hindi = 'hi_IN'
Tamil = 'ta_IN'
Telugu = 'te_IN'
Kannada = 'kn_IN'
Malayalam = 'ml_IN'
Italian = 'it_IT'
Swedish = 'sv_SE'
French = 'fr_FR'
Japanese = 'ja_JP'
Dutch = 'nl_NL'
Polish = 'pl_PL'
Turkish = 'tr_TR'
EnglishAustralia = 'en_AU'
EnglishCanada = 'en... | (self):
body_repr_length = 100
body_repr = repr(self.body)
print_body = body_repr[:body_repr_length]
if body_repr[body_repr_length:]:
print_body += '...'
return 'Review(reviewer={}, reviewer_url={}, review_url={}, title={}, rating={}, helpful={}, body={})'.format(
... | __repr__ | identifier_name |
models.py | ar_AE'
Hindi = 'hi_IN'
Tamil = 'ta_IN'
Telugu = 'te_IN'
Kannada = 'kn_IN'
Malayalam = 'ml_IN'
Italian = 'it_IT'
Swedish = 'sv_SE'
French = 'fr_FR'
Japanese = 'ja_JP'
Dutch = 'nl_NL'
Polish = 'pl_PL'
Turkish = 'tr_TR'
EnglishAustralia = 'en_AU'
EnglishCanada = 'en... |
return 'ReviewList(reviews={}, asin={}, country={}, page={}, last_page={})'.format(print_reviews,
repr(self.asin),
self.country,
... | print_reviews += '...' | conditional_block |
models.py | D"
ChileanPeso = "CLP"
ChineseYuanRenminbi = "CNY"
ColombianPeso = "COP"
CostaRicanColon = "CRC"
CzechKoruna = "CZK"
DanishKrone = "DKK"
DominicanRepublicPeso = "DOP"
EgyptianPound = "EGP"
Euro = "EUR"
GhanaianCedi = "GHS"
GuatemalanQuetzal = "GTQ"
HongKongDollar = "HKD"
... |
class ReviewSettings: | random_line_split | |
models.py | ar_AE'
Hindi = 'hi_IN'
Tamil = 'ta_IN'
Telugu = 'te_IN'
Kannada = 'kn_IN'
Malayalam = 'ml_IN'
Italian = 'it_IT'
Swedish = 'sv_SE'
French = 'fr_FR'
Japanese = 'ja_JP'
Dutch = 'nl_NL'
Polish = 'pl_PL'
Turkish = 'tr_TR'
EnglishAustralia = 'en_AU'
EnglishCanada = 'en... |
class Review:
def __init__(self, reviewer: str, reviewer_url: str, review_url: str, title: str, rating: int, helpful: int,
body: str):
self.reviewer = reviewer
self.reviewer_url = reviewer_url
self.review_url = review_url
self.title = title
self.rating = r... | def __init__(self, product_name: str, offer_count: int, offers: List[Offer], settings: Dict[str, bool]):
self.product_name = product_name
self.offer_count = offer_count
self.offers = offers
self.page = settings['page']
self.settings = settings
def __repr__(self):
off... | identifier_body |
training.go | : %v", err)
if j.status.Phase != spec.MxJobPhaseFailed {
j.status.SetReason(err.Error())
j.status.SetPhase(spec.MxJobPhaseFailed)
if err := j.updateTPRStatus(); err != nil {
log.Errorf("failed to update cluster phase (%v): %v", spec.MxJobPhaseFailed, err)
}
}
return
}
j.run(stopC)
}()... |
err = j.job.Spec.Validate()
if err != nil {
return fmt.Errorf("invalid job spec: %v", err)
}
for _, t := range j.job.Spec.ReplicaSpecs {
r, err := NewMXReplicaSet(j.KubeCli, *t, j)
if err != nil {
return err
}
j.Replicas = append(j.Replicas, r)
}
if err := j.job.Spec.ConfigureAccelerators(config.... | {
return fmt.Errorf("there was a problem setting defaults for job spec: %v", err)
} | conditional_block |
training.go | Id = util.RandString(4)
}
var shouldCreateCluster bool
switch j.status.Phase {
case spec.MxJobPhaseNone:
shouldCreateCluster = true
//case spec.MxJobPhaseCreating:
// return errCreatedCluster
case spec.MxJobPhaseRunning:
shouldCreateCluster = false
case spec.MxJobPhaseFailed:
shouldCreateCluster = fals... | // Because it will check UID first and return something like:
// "Precondition failed: UID in precondition: 0xc42712c0f0, UID in object meta: ".
if k8sutil.IsKubernetesResourceNotFoundError(err) {
return true, nil | random_line_split | |
training.go | : %v", err)
if j.status.Phase != spec.MxJobPhaseFailed {
j.status.SetReason(err.Error())
j.status.SetPhase(spec.MxJobPhaseFailed)
if err := j.updateTPRStatus(); err != nil {
log.Errorf("failed to update cluster phase (%v): %v", spec.MxJobPhaseFailed, err)
}
}
return
}
j.run(stopC)
}()... | state = spec.StateFailed
}
}
if j.job.Spec.JobMode == spec.LocalJob {
if v, ok := replicaSetStates[spec.WORKER]; ok && v == spec.ReplicaStateSucceeded {
state = spec.StateSucceeded
return state, replicaStatuses, nil
}
} else if j.job.Spec.JobMode == spec.DistJob {
if v, ok := replicaSetStates[spec.S... | {
state := spec.StateUnknown
replicaStatuses := make([]*spec.MxReplicaStatus, 0)
// The state for each replica.
// TODO(jlewi): We will need to modify this code if we want to allow multiples of a given type of replica.
replicaSetStates := make(map[spec.MxReplicaType]spec.ReplicaState)
for _, r := range j.Replic... | identifier_body |
training.go | : %v", err)
if j.status.Phase != spec.MxJobPhaseFailed {
j.status.SetReason(err.Error())
j.status.SetPhase(spec.MxJobPhaseFailed)
if err := j.updateTPRStatus(); err != nil {
log.Errorf("failed to update cluster phase (%v): %v", spec.MxJobPhaseFailed, err)
}
}
return
}
j.run(stopC)
}()... | () string {
return fmt.Sprintf("master-%v-0", j.job.Spec.RuntimeId)
}
// setup the training job.
func (j *TrainingJob) setup(config *spec.ControllerConfig) error {
if j.job == nil {
return fmt.Errorf("job.Spec can't be nil")
}
err := j.job.Spec.SetDefaults()
if err != nil {
return fmt.Errorf("there was a pro... | masterName | identifier_name |
model_pki_patch_role_response.go | to put in Subject. These values support globbing.
AllowedSerialNumbers []string `json:"allowed_serial_numbers,omitempty"`
// If set, an array of allowed URIs for URI Subject Alternative Names. Any valid URI is accepted, these values support globbing.
AllowedUriSans []string `json:"allowed_uri_sans,omitempty"`
//... | NewPkiPatchRoleResponseWithDefaults | identifier_name | |
model_pki_patch_role_response.go | If set, an array of allowed URIs for URI Subject Alternative Names. Any valid URI is accepted, these values support globbing.
AllowedUriSans []string `json:"allowed_uri_sans,omitempty"`
// If set, Allowed URI SANs can be specified using identity template policies. Non-templated URI SANs are also permitted.
Allowed... | {
var this PkiPatchRoleResponse
this.ServerFlag = true
return &this
} | identifier_body | |
model_pki_patch_role_response.go | allow_glob_domains,omitempty"`
// If set, IP Subject Alternative Names are allowed. Any valid IP is accepted and No authorization checking is performed.
AllowIpSans bool `json:"allow_ip_sans,omitempty"`
// Whether to allow \"localhost\" and \"localdomain\" as a valid common name in a request, independent of allowe... | ClientFlag bool `json:"client_flag,omitempty"`
// List of allowed validations to run against the Common Name field. Values can include 'email' to validate the CN is a email address, 'hostname' to validate the CN is a valid hostname (potentially including wildcards). When multiple validations are specified, these tak... |
// Mark Basic Constraints valid when issuing non-CA certificates.
BasicConstraintsValidForNonCa bool `json:"basic_constraints_valid_for_non_ca,omitempty"`
// If set, certificates are flagged for client auth use. Defaults to true. See also RFC 5280 Section 4.2.1.12. | random_line_split |
api_test.go |
ms, err := vmap.VerifiedLatestMapState(ctx, nil)
if err != nil {
t.Fatal(err)
}
// Make sure we don't break on non-existent entries
for i := 0; i < numToDo; i++ {
entry, err := vmap.VerifiedGet(ctx, []byte(fmt.Sprintf("baz%d", i)), ms)
if err != nil {
t.Fatal(err)
}
dd := entry.GetLeafInput()
if l... | {
account := (&verifiable.Client{
Service: service,
}).Account("999", "secret")
vmap := account.VerifiableMap("testmap")
numToDo := 1000
var lastP verifiable.MapUpdatePromise
var err error
for i := 0; i < numToDo; i++ {
lastP, err = vmap.Set(ctx, []byte(fmt.Sprintf("foo%d", i)), &pb.LeafData{LeafInput: []by... | identifier_body | |
api_test.go | (ctx context.Context, t *testing.T, service pb.VerifiableDataStructuresServiceServer) {
account := (&verifiable.Client{
Service: service,
}).Account("999", "secret")
vmap := account.VerifiableMap("testmap")
numToDo := 1000
var lastP verifiable.MapUpdatePromise
var err error
for i := 0; i < numToDo; i++ {
la... | testMap | identifier_name | |
api_test.go | bytes.Equal(treeRoot.RootHash, last) {
t.Fatal("Failed calculating tree root")
}
for i := 0; i < 200; i++ {
p, err = log.Add(ctx, &pb.LeafData{LeafInput: []byte(fmt.Sprintf("foo %d", rand.Int()))})
if err != nil {
t.Fatal("Failed adding item")
}
}
treeRoot, err = p.Wait(ctx)
if err != nil {
t.Fatal(... | random_line_split | ||
api_test.go | )
}
ms, err := vmap.VerifiedLatestMapState(ctx, nil)
if err != nil {
t.Fatal(err)
}
// Make sure we don't break on non-existent entries
for i := 0; i < numToDo; i++ {
entry, err := vmap.VerifiedGet(ctx, []byte(fmt.Sprintf("baz%d", i)), ms)
if err != nil {
t.Fatal(err)
}
dd := entry.GetLeafInput()
... |
if treeRoot.TreeSize != 205 {
t.Fatal("Failure getting root hash")
}
cnt := 0
for entry := range log.Entries(context.Background(), 0, treeRoot.TreeSize) {
err = log.VerifyInclusion(ctx, treeRoot, merkle.LeafHash(entry.LeafInput))
if err != nil {
t.Fatal("Failure verifiying inclusion")
}
cnt++
}
if... | {
t.Fatal(err)
} | conditional_block |
client.go | not create an Elastic IP due to quota limits on the account, please contact Equinix Metal support")
ErrInvalidIP = errors.New("invalid IP")
ErrMissingEnvVar = errors.New("missing required env var")
ErrInvalidRequest = errors.New("invalid request")
)
type Client struct {... |
func GetClient() (*Client, error) {
token := os.Getenv(apiTokenVarName)
if token == "" {
return nil, fmt.Errorf("%w: %s", ErrMissingEnvVar, apiTokenVarName)
}
return NewClient(token), nil
}
func (p *Client) GetDevice(ctx context.Context, deviceID string) (*metal.Device, *http.Response, error) {
dev, resp, err... | {
token := strings.TrimSpace(packetAPIKey)
if token != "" {
configuration := metal.NewConfiguration()
configuration.Debug = checkEnvForDebug()
configuration.AddDefaultHeader("X-Auth-Token", token)
configuration.AddDefaultHeader("X-Consumer-Token", clientName)
configuration.UserAgent = fmt.Sprintf(clientUAF... | identifier_body |
client.go | not create an Elastic IP due to quota limits on the account, please contact Equinix Metal support")
ErrInvalidIP = errors.New("invalid IP")
ErrMissingEnvVar = errors.New("missing required env var")
ErrInvalidRequest = errors.New("invalid request")
)
type Client struct {... |
stringWriter := &strings.Builder{}
userData := string(userDataRaw)
userDataValues := map[string]interface{}{
"kubernetesVersion": pointer.StringPtrDerefOr(req.MachineScope.Machine.Spec.Version, ""),
}
tags := make([]string, 0, len(packetMachineSpec.Tags)+len(req.ExtraTags))
copy(tags, packetMachineSpec.Tags)... | {
return nil, fmt.Errorf("unable to retrieve bootstrap data from secret: %w", err)
} | conditional_block |
client.go | not create an Elastic IP due to quota limits on the account, please contact Equinix Metal support")
ErrInvalidIP = errors.New("invalid IP")
ErrMissingEnvVar = errors.New("missing required env var")
ErrInvalidRequest = errors.New("invalid request")
)
type Client struct {... | () (*Client, error) {
token := os.Getenv(apiTokenVarName)
if token == "" {
return nil, fmt.Errorf("%w: %s", ErrMissingEnvVar, apiTokenVarName)
}
return NewClient(token), nil
}
func (p *Client) GetDevice(ctx context.Context, deviceID string) (*metal.Device, *http.Response, error) {
dev, resp, err := p.DevicesApi... | GetClient | identifier_name |
client.go | not create an Elastic IP due to quota limits on the account, please contact Equinix Metal support")
ErrInvalidIP = errors.New("invalid IP")
ErrMissingEnvVar = errors.New("missing required env var")
ErrInvalidRequest = errors.New("invalid request")
)
type Client struct {... | Facility: []string{facility},
BillingCycle: &req.MachineScope.PacketMachine.Spec.BillingCycle,
Plan: req.MachineScope.PacketMachine.Spec.MachineType,
OperatingSystem: req.MachineScope.PacketMachine.Spec.OS,
IpxeScriptUrl: &req.MachineScope.PacketMachine.Spec.IPXEUrl,
Tags: ... | serverCreateOpts := metal.CreateDeviceRequest{}
if facility != "" {
serverCreateOpts.DeviceCreateInFacilityInput = &metal.DeviceCreateInFacilityInput{
Hostname: &hostname, | random_line_split |
main.rs | CS,
n_bits: usize,
lhs: LinearCombination,
rhs: LinearCombination
) -> Result<LinearCombination, R1CSError> {
let lhs_bits = scalar_to_bits_le(cs, n_bits, lhs)?;
let rhs_bits = scalar_to_bits_le(cs, n_bits, rhs)?;
let zero = LinearCombination::default();
// Iterate through bits from most ... | 0u64 }; | conditional_block | |
main.rs | () {
let val = eval(&local_var);
let valid = (n_bits..256).any(|i| get_bit(&val, i) == 0);
val_cache = Some(
if valid {
Ok(val)
} else {
Err(R1CSError::GadgetError {
... | brackets: &TaxBrackets, total: u64) -> u64 {
(0..brackets.0.len())
.map(|i| {
let last_cutoff = if i == 0 { 0u64 } else { brackets.0[i-1].0 };
let (next_cutoff, rate) = brackets.0[i];
let amount = if total > next_cutoff {
next_cutoff - last_cutoff
... | ompute_taxes( | identifier_name |
main.rs | .is_none() {
let val = eval(&local_var);
let valid = (n_bits..256).any(|i| get_bit(&val, i) == 0);
val_cache = Some(
if valid {
Ok(val)
} else {
Err(R1CSError::GadgetError {
... | ) -> Result<LinearCombination, R1CSError> {
let lhs_bits = scalar_to_bits_le(cs, n_bits, lhs)?;
let rhs_bits = scalar_to_bits_le(cs, n_bits, rhs)?;
let zero = LinearCombination::default();
// Iterate through bits from most significant to least, comparing each pair.
let (lt, _) = lhs_bits.into_iter... | rhs: LinearCombination | random_line_split |
main.rs | _none() {
let val = eval(&local_var);
let valid = (n_bits..256).any(|i| get_bit(&val, i) == 0);
val_cache = Some(
if valid {
Ok(val)
} else {
Err(R1CSError::GadgetError {
... | let (_, _, bit_lt) = cs.multiply(negate_bit(l_bit), r_bit.into());
let (_, _, bit_gt) = cs.multiply(l_bit.into(), negate_bit(r_bit));
// new_lt = lt + eq && bit_lt
// -> lt_diff = new_lt - lt = eq * bit_lt
// new_gt = gt + eq && bit_gt
// -> g... | {
let lhs_bits = scalar_to_bits_le(cs, n_bits, lhs)?;
let rhs_bits = scalar_to_bits_le(cs, n_bits, rhs)?;
let zero = LinearCombination::default();
// Iterate through bits from most significant to least, comparing each pair.
let (lt, _) = lhs_bits.into_iter().zip(rhs_bits.into_iter())
.rev(... | identifier_body |
infer.py | font_color = (0.8, 0.8, 0.8)
# Intrinsics.
K = samples[common.K][0]
output_K = K * output_scale
output_K[2, 2] = 1.0
# Tiles for the grid visualization.
tiles = []
# Size of the output fields.
output_size =\
int(output_scale * crop_size[0]), int(output_scale * crop_size[1])
# Prefix of the vi... | (
sess, samples, predictions, im_ind, crop_size, output_scale, model_store,
renderer, task_type, infer_name, infer_dir, vis_dir):
"""Estimates object poses from one image.
Args:
sess: TensorFlow session.
samples: Dictionary with input data.
predictions: Dictionary with predictions.
im_i... | process_image | identifier_name |
infer.py | ], :crop_size[0]]
obj_labels = vis.colorize_label_map(obj_labels)
obj_labels = visualization.write_text_on_image(
misc.resize_image_py(obj_labels.astype(np.uint8), tile_size),
[{'name': '', 'val': 'gt obj labels', 'fmt': ':s'}],
size=font_size, color=font_color)
tiles.append(obj_labels)
... | obj_corr[key] = obj_corr[key][sorted_inds] | conditional_block | |
infer.py | txt'.format(im_ind, obj_id))
tf.gfile.MakeDirs(os.path.dirname(corr_path))
with open(corr_path, 'w') as f:
f.write(txt)
def process_image(
sess, samples, predictions, im_ind, crop_size, output_scale, model_store,
renderer, task_type, infer_name, infer_dir, vis_dir):
"""Estimates object poses fro... | model_store=model_store, | random_line_split | |
infer.py | font_color = (0.8, 0.8, 0.8)
# Intrinsics.
K = samples[common.K][0]
output_K = K * output_scale
output_K[2, 2] = 1.0
# Tiles for the grid visualization.
tiles = []
# Size of the output fields.
output_size =\
int(output_scale * crop_size[0]), int(output_scale * crop_size[1])
# Prefix of the vi... | coord_3d = obj_pred['coord_3d'][sort_inds]
conf = obj_pred['conf'][sort_inds]
conf_obj = obj_pred['conf_obj'][sort_inds]
conf_frag = obj_pred['conf_frag'][sort_inds]
# Add the predicted correspondences.
pred_corr_num = len(coord_2d)
txt += '{}\n'.format(pred_corr_num)
for i in range(pred_corr_num):
... | txt = '# Corr format: u v x y z px_id frag_id conf conf_obj conf_frag\n'
txt += '{}\n'.format(image_path)
txt += '{} {} {} {}\n'.format(scene_id, im_id, obj_id, pred_time)
# Add intrinsics.
for i in range(3):
txt += '{} {} {}\n'.format(K[i, 0], K[i, 1], K[i, 2])
# Add ground-truth poses.
txt += '{}\n'... | identifier_body |
main.rs | rows - 1
} else {
x - 1
}
};
let next = |x| (x + 1) % rows;
[ (prev(r), prev(c)), (prev(r), c), (prev(r), next(c)),
(r, prev(c)), (r, next(c)),
(next(r), prev(c)), (next(r), c), (next(r), next(c))
]
}
/**
* @returns a vecto... | <T>(
net: &Kohonen<T>,
samples: &std::vec::Vec<T>,
its: u32,
associate: sphere_of_influence::AssociationKind)
-> Kohonen<T>
where T: kohonen_neuron::KohonenNeuron + Send + Sync + 'static {
let mut rv = net.clone();
let width = net.cols as f64;
// training with a large fixed radius for a bit ... | iter_train | identifier_name |
main.rs | rows - 1
} else {
x - 1
}
};
let next = |x| (x + 1) % rows;
[ (prev(r), prev(c)), (prev(r), c), (prev(r), next(c)),
(r, prev(c)), (r, next(c)),
(next(r), prev(c)), (next(r), c), (next(r), next(c))
]
}
/**
* @returns a vecto... | }
let nets: Vec<Kohonen<T>> =
descs
.par_iter()
.map(|(my_net, sample)| {
let associate = associate.clone();
let mut net = my_net.clone();
feed_sample(&mut net, &sample, rate, radius, associate);
net
})
... | Kohonen<T>: Send + Sync {
let mut descs = Vec::new();
for i in 0..samples.len() {
descs.push((net.clone(), samples[i].clone()));
//feed_sample(net, &samples[i], rate, radius); | random_line_split |
main.rs | rows - 1
} else {
x - 1
}
};
let next = |x| (x + 1) % rows;
[ (prev(r), prev(c)), (prev(r), c), (prev(r), next(c)),
(r, prev(c)), (r, next(c)),
(next(r), prev(c)), (next(r), c), (next(r), next(c))
]
}
/**
* @returns a vecto... | rv = train(net2, samples, rate, radius.ceil() as i32, associate.clone())
}
rv
}
pub fn show<T: kohonen_neuron::KohonenNeuron>(net: &Kohonen<T>, path: &str) {
let rows = net.rows;
let cols = net.cols;
let path = Path::new(path);
let mut os = match File::create(&path) {
Err(why) ... | {
let mut rv = net.clone();
let width = net.cols as f64;
// training with a large fixed radius for a bit should help things get into
// the right general places
/*for _i in 0..(its / 2) {
let radius = width / 2.0;
let rate = 0.5;
rv = train(rv.clone(), samples, rate, radius a... | identifier_body |
dis2py.py | == "YIELD_VALUE":
push(operations.Yield(pop()))
elif opname == "RETURN_VALUE":
if is_comp:
push(operations.Return(operations.Value(temp_name)))
else:
push(operations.Return(pop()))
elif opname == "BUILD_MAP":
count = int(instruction.arg)
args = pop_n(2 * count)
push(operations.BuildMap(ar... | push(
operations.FunctionCall(
operations.Attribute(operations.Value(temp_name), operations.Value(func)),
[pop()] | random_line_split | |
dis2py.py | operations.Continue())
#otherwise this is a normal jump to the top of the loop, so do nothing
else:
for instruction3 in instructions:
if (instruction3.opname == "FOR_ITER" and int(
instruction3.argval[len("to "):]
) == instruction2.offset) or (
instruction3.opname.s... | disasm = re.sub(r"^#.*\n?", "", disasm, re.MULTILINE).strip() # ignore comments
for name, func in split_funcs(disasm):
yield name, *decompile(func, get_flags(name)|flags, tab_char) | identifier_body | |
dis2py.py |
else:
ast.append((indent, operation))
def pop():
return ast.pop()[1]
def pop_n(n):
nonlocal ast
if n > 0: # ast[:-0] would be the empty list and ast[-0:] would be every element in ast
if raw_jumps:
ret = [x for _, x,_ in ast[-n:]]
else:
ret = [x for _, x in ast[-n:]]
ast = ast[:-n]
... | ast.append((indent,operation,instruction.offset)) | conditional_block | |
dis2py.py | (operation):
if raw_jumps:
ast.append((indent,operation,instruction.offset))
else:
ast.append((indent, operation))
def pop():
return ast.pop()[1]
def pop_n(n):
nonlocal ast
if n > 0: # ast[:-0] would be the empty list and ast[-0:] would be every element in ast
if raw_jumps:
ret = [x for _,... | push | identifier_name | |
docker_image_dest.go | schema),
// but may accept a different manifest type, the returned error must be an ManifestTypeRejectedError.
func (d *dockerImageDestination) PutManifest(ctx context.Context, m []byte) error {
digest, err := manifest.Digest(m)
if err != nil {
return err
}
d.manifestDigest = digest
refTail, err := d.ref.tagOr... | err
}
defer res | conditional_block | |
docker_image_dest.go |
// Reference returns the reference used to set up this destination. Note that this should directly correspond to user's intent,
// e.g. it should use the public hostname instead of the result of resolving CNAMEs or following redirects.
func (d *dockerImageDestination) Reference() types.ImageReference {
return d.ref... | {
c, err := newDockerClientFromRef(sys, ref, true, "pull,push")
if err != nil {
return nil, err
}
return &dockerImageDestination{
ref: ref,
c: c,
}, nil
} | identifier_body | |
docker_image_dest.go | = locationQuery.Encode()
res, err = d.c.makeRequestToResolvedURL(ctx, "PUT", uploadLocation.String(), map[string][]string{"Content-Type": {"application/octet-stream"}}, nil, -1, v2Auth)
if err != nil {
return types.BlobInfo{}, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusCreated {
logrus.Debug... | default: | random_line_split | |
docker_image_dest.go | () types.ImageReference {
return d.ref
}
// Close removes resources associated with an initialized ImageDestination, if any.
func (d *dockerImageDestination) Close() error {
return nil
}
func (d *dockerImageDestination) SupportedManifestMIMETypes() []string {
return []string{
imgspecv1.MediaTypeImageManifest,
... | Reference | identifier_name | |
factor_data_preprocess.py | (save_list[-1].split('.')[0]):
print('被添加数据长度不够')
raise Exception
for panel_f in os.listdir(target_date_path):
toadded_dat = pd.read_csv(os.path.join(added_date_path, panel_f),
encoding='gbk', engine='python',
index_col=['c... |
sf_close_daily = sf_close_daily[tt] | random_line_split | |
factor_data_preprocess.py | =0)
pd_s = tmpp[tmpp.columns[0]]
mv = tmpp[tmpp.columns[1]]
mv_weights = mv/np.sum(mv)
v = np.dot(np.mat(pd_s), np.mat(mv_weights).T)
return np.array(v).flatten()
# 中位数
elif type == 'median':
return np.nanmedian(pd_s)
elif type == 'mean':
return np.nan... | identifier_body | ||
factor_data_preprocess.py | datdf.loc[fac_to_fill.index, fac] = fac_to_fill[fac].values
if pd.isnull(datdf[fac]).any():
datdf[fac] = datdf[fac].fillna(np.nanmean(datdf[fac]))
# 针对sw行业存在缺失值的情况
if len(datdf) < len(data):
idx_to_append = data.index.difference(datdf.index)
datdf = pd.concat([datdf, data.l... | use_dummies = 1
if not ind_neu:
use_dummies = 0
# 市值中性行业不中性
if use_dummies == 0 and size_neu:
X = lncap
# 行业中性市值不中性
elif use_dummies == 1 and not size_neu:
X = pd.get_dummies(datdf[f'Industry_{ind}'])
else:
# 使用 pd.get_dummies 生成行业哑变量
ind_dummy_matrix ... | 生成行业哑变量
| identifier_name |
factor_data_preprocess.py | ��对sw行业存在缺失值的情况
if len(datdf) < len(data):
idx_to_append = data.index.difference(datdf.index)
datdf = pd.concat([datdf, data.loc[idx_to_append, :]])
datdf.sort_index()
return datdf
def coerce_numeric(s):
try:
return float(s)
except:
return np.nan
def winsoriz... | gbk', engine='python',
index_col=['code'])
r | conditional_block | |
pplot.py | style_unifpf():
return _style_thickline({ 'color': '#D0E4FF' })
def _style_strategy(name, i):
if name.startswith('mUNIF'):
return _style_thickline({ 'color': 'wheat' })
styles = bb.genericsettings.line_styles
style = styles[i % len(styles)].copy()
del style['linestyle']
style['markers... |
for (kind, name, ds, style) in _pds_plot_iterator(pds, dim, funcId):
#print name, ds
budgets = ds.funvals[:, 0]
funvals = groupby(ds.funvals[:, 1:], axis=1)
# Throw away funvals after ftarget reached
try:
limit = np.nonzero(funvals < 10**-8)[0][0] + 1
e... | baseline_budgets = baseline_ds.funvals[:, 0]
baseline_funvals = groupby(baseline_ds.funvals[:, 1:], axis=1)
baseline_safefunvals = np.maximum(baseline_funvals, 10**-8) # eschew zeros
# fvb is matrix with each row being [budget,funval]
baseline_fvb = np.transpose(np.vstack([baseline_budge... | conditional_block |
pplot.py | _style_unifpf():
return _style_thickline({ 'color': '#D0E4FF' })
def _style_strategy(name, i):
if name.startswith('mUNIF'):
return _style_thickline({ 'color': 'wheat' }) | style = styles[i % len(styles)].copy()
del style['linestyle']
style['markersize'] = 12.
style['markeredgewidth'] = 1.5
style['markerfacecolor'] = 'None'
style['markeredgecolor'] = style['color']
style['linestyle'] = 'solid'
style['zorder'] = 1
style['linewidth'] = 2
return styl... |
styles = bb.genericsettings.line_styles | random_line_split |
pplot.py | (self, lst, **kwargs):
return np.median(lst, **kwargs)
def __str__(self):
return 'median'
def _style_thickline(xstyle):
style = { 'linestyle': 'solid', 'zorder': -1, 'linewidth': 6 }
style.update(xstyle)
return style
def _style_algorithm(name, i):
# Automatic colors are fine, no m... | __call__ | identifier_name | |
pplot.py | _style_unifpf():
return _style_thickline({ 'color': '#D0E4FF' })
def _style_strategy(name, i):
if name.startswith('mUNIF'):
return _style_thickline({ 'color': 'wheat' })
styles = bb.genericsettings.line_styles
style = styles[i % len(styles)].copy()
del style['linestyle']
style['marke... |
def legend(obj, ncol=3, **kwargs):
"""
Show a legend. obj can be an Axes or Figure (in that case, also pass
handles and labels arguments).
"""
# Font size handling here is a bit weird. We specify fontsize=6
# in legend constructor since that affects spacing. However, we
# need to manua... | """
An iterator that will in turn yield all drawable curves
in the form of (kind, name, ds, style) tuples (where kind
is one of 'algorithm', 'oracle', 'unifpf', 'strategy').
"""
i = 0
for (algname, ds) in pds.algds_dimfunc((dim, funcId)):
yield ('algorithm', algname, ds, _style_algorithm... | identifier_body |
parser.go | Do not delete this <div>. -->
<div id="nav"></div>
<!-- Content is HTML-escaped elsewhere -->
<pre>
<a id="L1"></a><span class="comment">// Copyright 2009 The Go Authors. All rights reserved.</span>
<a id="L2"></a><span class="comment">// Use of this source code is governed by a BSD-style</span>
<a id="L3... | <h1 id="generatedHeader">Source file /src/pkg/exp/datafmt/parser.go</h1>
<!-- The Table of Contents is automatically inserted in this <div>. | random_line_split | |
capture_agents.py | publish
solutions, (2) you retain this notice, and (3) you provide clear
attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
Attribution Information: The Pacman AI projects were developed at UC Berkeley.
The core projects and autograders were primarily created by John DeNero
(denero@cs.berkeley.ed... | (self, index, time_for_computing=.1):
"""Initialize capture agent with several variables you can query.
self.index = index for this agent
self.red = true if you're on the red team, false otherwise
self.agents_on_team = a list of agent objects that make up your team
self.distance... | __init__ | identifier_name |
capture_agents.py | or publish
solutions, (2) you retain this notice, and (3) you provide clear
attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
Attribution Information: The Pacman AI projects were developed at UC Berkeley.
The core projects and autograders were primarily created by John DeNero
(denero@cs.berkeley... | score and the opponents score. This number is negative if you're
losing.
"""
if self.red:
return game_state.get_score()
else:
return game_state.get_score() * -1
def get_maze_distance(self, pos1, pos2):
"""Return the distance between two point... | def get_score(self, game_state):
"""Return how much you are beating the other team by.
This is in the form of a number that is the difference between your | random_line_split |
capture_agents.py | rules."""
def __init__(self, index):
"""Initialize agent with given index."""
self.index = index
def get_action(self, state):
"""Return a random legal action."""
return random.choice(state.get_legal_actions(self.index))
class CaptureAgent(Agent):
"""A base class for capt... | """Initialize agent with given index."""
self.index = index | identifier_body | |
capture_agents.py | publish
solutions, (2) you retain this notice, and (3) you provide clear
attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
Attribution Information: The Pacman AI projects were developed at UC Berkeley.
The core projects and autograders were primarily created by John DeNero
(denero@cs.berkeley.ed... |
else:
return self.choose_action(game_state)
def choose_action(self, game_state):
"""Override this method to make a good agent.
It should return a legal action within the time limit (otherwise a
random legal action will be chosen for you).
"""
util.raise... | return game_state.get_legal_actions(self.index)[0] | conditional_block |
mod.rs | which are
//! combined into final render pipeline. We should follow the same philosophy.
//!
//! ### Multi-thread
//!
//! In most cases, dividing OpenGL rendering across multiple threads will not result in
//! any performance improvement due the pipeline nature of OpenGL. What we are about
//! to do is actually exploi... |
drop(Box::from_raw(CTX as *mut VideoSystem));
CTX = std::ptr::null();
}
pub(crate) unsafe fn frames() -> Arc<DoubleBuf<Frame>> {
ctx().frames()
}
/// Creates an surface with `SurfaceParams`.
#[inline]
pub fn create_surface(params: SurfaceParams) -> Result<SurfaceHandle> {
ctx().create_surface(params... | {
return;
} | conditional_block |
mod.rs | which are
//! combined into final render pipeline. We should follow the same philosophy.
//!
//! ### Multi-thread
//!
//! In most cases, dividing OpenGL rendering across multiple threads will not result in
//! any performance improvement due the pipeline nature of OpenGL. What we are about
//! to do is actually exploi... |
/// Gets the `ShaderParams` if available.
#[inline]
pub fn shader(handle: ShaderHandle) -> Option<ShaderParams> {
ctx().shader(handle)
}
/// Get the resource state of specified shader.
#[inline]
pub fn shader_state(handle: ShaderHandle) -> ResourceState {
ctx().shader_state(handle)
}
/// Delete shader state ... | #[inline]
pub fn create_shader(params: ShaderParams, vs: String, fs: String) -> Result<ShaderHandle> {
ctx().create_shader(params, vs, fs)
} | random_line_split |
mod.rs | which are
//! combined into final render pipeline. We should follow the same philosophy.
//!
//! ### Multi-thread
//!
//! In most cases, dividing OpenGL rendering across multiple threads will not result in
//! any performance improvement due the pipeline nature of OpenGL. What we are about
//! to do is actually exploi... | (params: SurfaceParams) -> Result<SurfaceHandle> {
ctx().create_surface(params)
}
/// Gets the `SurfaceParams` if available.
#[inline]
pub fn surface(handle: SurfaceHandle) -> Option<SurfaceParams> {
ctx().surface(handle)
}
/// Get the resource state of specified surface.
#[inline]
pub fn surface_state(handle... | create_surface | identifier_name |
mod.rs | //! application::oneshot().unwrap();
//!
//! // Declares the uniform variable layouts.
//! let mut uniforms = UniformVariableLayout::build()
//! .with("u_ModelViewMatrix", UniformVariableType::Matrix4f)
//! .with("u_MVPMatrix", UniformVariableType::Matrix4f)
//! .finish();
//!
//! // Declares the attributes... | {
ctx().delete_render_texture(handle)
} | identifier_body | |
crystallography_frame_viewer.py | PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with OnDA.
# If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2014-2019 Deutsches Elektronen-Synchrotron DESY,
# a research centre of the Helmholtz Associatio... | pen=self._ring_pen,
pxMode=False,
)
def _back_button_clicked(self):
# Type () -> None
# Manages clicks on the 'back' button.
self._stop_stream()
if self._current_frame_index > 0:
self._current_frame_index -= 1
print("Showing frame ... | x=peak_x_list,
y=peak_y_list,
symbol="o",
size=[5] * len(current_data[b"peak_list"][b"intensity"]),
brush=(255, 255, 255, 0), | random_line_split |
crystallography_frame_viewer.py | PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with OnDA.
# If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2014-2019 Deutsches Elektronen-Synchrotron DESY,
# a research centre of the Helmholtz Associatio... |
try:
current_data = self._frame_list[self._current_frame_index]
except IndexError:
# If the framebuffer is empty, returns without drawing anything.
return
self._img[self._visual_pixel_map_y, self._visual_pixel_map_x] = (
current_data[b"detector_... | self._frame_list.append(copy.deepcopy(self.received_data[-1]))
self._current_frame_index = len(self._frame_list) - 1
# Resets the 'received_data' attribute to None. One can then check if
# data has been received simply by checking wether the attribute is not
# None.
... | conditional_block |
crystallography_frame_viewer.py | PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with OnDA.
# If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2014-2019 Deutsches Elektronen-Synchrotron DESY,
# a research centre of the Helmholtz Associatio... | (geometry_file, hostname, port):
# type: (Dict[str, Any], str, int) -> None
"""
OnDA frame viewer for crystallography. This program must connect to a running OnDA
monitor for crystallography. If the monitor broadcasts detector frame data, this
viewer will display it. The viewer will also show, overl... | main | identifier_name |
crystallography_frame_viewer.py | PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with OnDA.
# If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2014-2019 Deutsches Elektronen-Synchrotron DESY,
# a research centre of the Helmholtz Associatio... |
def _forward_button_clicked(self):
# Type () -> None
# Manages clicks on the 'forward' button.
self._stop_stream()
if (self._current_frame_index + 1) < len(self._frame_list):
self._current_frame_index += 1
print("Showing frame {0} in the buffer".format(self._cur... | self._stop_stream()
if self._current_frame_index > 0:
self._current_frame_index -= 1
print("Showing frame {0} in the buffer".format(self._current_frame_index))
self._update_image() | identifier_body |
run.py | AutoCompression
def argsparser():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'--config_path',
type=str,
default=None,
help="path of compression strategy config.",
required=True)
parser.add_argument(
'--save_dir',
type... | return example['input_ids'], example['token_type_ids'], label
else:
return example['input_ids'], example['token_type_ids']
def create_data_holder(task_name):
"""
Define the input data holder for the glue task.
"""
input_ids = paddle.static.data(
name="input_ids"... | text_pair=example['sentence2'],
max_seq_len=max_seq_length)
if not is_test: | random_line_split |
run.py | AutoCompression
def argsparser():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'--config_path',
type=str,
default=None,
help="path of compression strategy config.",
required=True)
parser.add_argument(
'--save_dir',
type... | ():
devices = paddle.device.get_device().split(':')[0]
places = paddle.device._convert_to_place(devices)
exe = paddle.static.Executor(places)
val_program, feed_target_names, fetch_targets = paddle.static.load_inference_model(
global_config['model_dir'],
exe,
model_filename=global... | eval | identifier_name |
run.py | def argsparser():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'--config_path',
type=str,
default=None,
help="path of compression strategy config.",
required=True)
parser.add_argument(
'--save_dir',
type=str,
defau... | if name.find("bias") > -1:
return True
elif name.find("b_0") > -1:
return True
elif name.find("norm") > -1:
return True
else:
return False | identifier_body | |
run.py | AutoCompression
def argsparser():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'--config_path',
type=str,
default=None,
help="path of compression strategy config.",
required=True)
parser.add_argument(
'--save_dir',
type... |
else:
| return True | conditional_block |
rt_threaded.rs | ZOMG").unwrap();
});
});
assert_ok!(rx.await)
});
assert_eq!(out, "ZOMG");
cfg_metrics! {
let metrics = rt.metrics();
drop(rt);
assert_eq!(1, metrics.remote_schedule_count());
let mut local = 0;
for i in 0..metrics.num_workers() {
... |
});
}
rx.recv().unwrap();
// Wait for the pool to shutdown
block.wait();
}
}
#[test]
fn multi_threadpool() {
use tokio::sync::oneshot;
let rt1 = rt();
let rt2 = rt();
let (tx, rx) = oneshot::channel();
let (done_tx, done_rx) = mpsc::channel();
... | {
tx.send(()).unwrap();
} | conditional_block |
rt_threaded.rs | ("ZOMG").unwrap();
});
});
assert_ok!(rx.await)
});
assert_eq!(out, "ZOMG");
cfg_metrics! {
let metrics = rt.metrics();
drop(rt);
assert_eq!(1, metrics.remote_schedule_count());
let mut local = 0;
for i in 0..metrics.num_workers() {
... | const TRACKS: usize = 50;
for _ in 0..50 {
let rt = rt();
let mut start_txs = Vec::with_capacity(TRACKS);
let mut final_rxs = Vec::with_capacity(TRACKS);
for _ in 0..TRACKS {
let (start_tx, mut chain_rx) = tokio::sync::mpsc::channel(10);
for _ in 0..CHA... | const CHAIN: usize = 200;
const CYCLES: usize = 5; | random_line_split |
rt_threaded.rs | });
start_txs.push(start_tx);
final_rxs.push(final_rx);
}
{
rt.block_on(async move {
for start_tx in start_txs {
start_tx.send("ping").await.unwrap();
}
for mut final_rx in final_rxs {
... | wake_during_shutdown | identifier_name | |
FormBaseInput.ts | GenericFormInput, validateIt?: boolean, skipSendValue?: boolean) => void);
/**
* Form context passed by the parent form
*/
protected formContext: IFormContext;
/**
* Constructor for any Simple Form input
* @param props The props for this component
* @param context The context for this component
... |
}
/**
* Loads the data from the Store async or sync.
* If Async loading the return true
* @param dataStoreKey The Key from the datastore
* @param loadedFunction The funtion to call after data is loaded
* @param waitText The Waiting Text for async loading controls.
*/
public loadDataFromStore(dataStoreK... | {
let entry = this.state.dataStores ? this.state.dataStores.find(e => e.key == configKey) : undefined;
if (!entry) {
let waitText = this.commonFormater.formatMessage(LocalsCommon.loadData);
loadedFunction(configKey, undefined, waitText, true);
}
provider.retrieveFilteredListData(configKey,co... | conditional_block |
FormBaseInput.ts | console.warn(this.props.inputKey + " 'id' prop was specified and will be ignored");
}
if (props.name) {
console.warn(this.props.inputKey + " 'name' prop was specified and will be ignored");
}
if (props.label) {
console.warn(this.props.inputKey + " 'label' prop was spec... | setError | identifier_name | |
FormBaseInput.ts | : GenericFormInput, validateIt?: boolean, skipSendValue?: boolean) => void);
/**
* Form context passed by the parent form
*/
protected formContext: IFormContext;
/**
* Constructor for any Simple Form input
* @param props The props for this component
* @param context The context for this component... | * @param loadedFunction The funtion to call after data is loaded
* @param waitText The Waiting Text for async loading controls.
*/
public loadDataFromStore(dataStoreKey:string, loadedFunction:DataLoadedFunction, waitText: string): boolean {
let dataBinderAsync:Promise<any[]> = this.dataStore[dataStoreKey] as... | random_line_split | |
FormBaseInput.ts | The sender Control that has the Filter Text
* @param filter The Filter Text.
*/
public loadDataFromStoreWithFilter(configKey:string, provider:IDataProviderFilterAsync, loadedFunction:DataLoadedFunction,
waitText: string, control:Control, filter:string) {
if (provider) {
let entry = this.state.dataStore... | {
this.setState((prevState: S): S => {
this.props.control.Value = value;
prevState.currentValue = value;
return prevState;
},
() => {
this.debouncedSubmitValue(this, validate, skipSendValue);
}
);
} | identifier_body | |
object-security-ui.js | : true,
stripeRows : true,
autoExpandColumn : 'username'
//,title : EURB.ObjSec.availableUsers
});
var authoritiesStore = new Ext.data.Store({
reader:new Ext.data.JsonReader({
id:'id'
,totalProperty:'aclEntryListTotalCount'
,root:'aclEntryList'
,fields:[
{name: ... | var sharingCheckColumn = new Ext.grid.CheckColumn({
header:EURB.ObjSec.authoritiesSharing
,id:'sharing'
,dataIndex:'sharing'
,editor:new CheckBoxClass()
,align:'center'
});
var authoritiesColModel = new Ext.grid.ColumnModel({
defaults: {
sortable: true
,width:20
},
columns: [{
header: EURB... | ,width:20
,editor:new CheckBoxClass()
,align:'center'
}); | random_line_split |
object-security-ui.js | :this
,params:{
cmd:'storeData',
data:Ext.encode(data),
sid:EURB.Authorities.selectedSID
}
};
Ext.Ajax.request(o);*/
}
,requestCallback:function(options, success, response) {
if(true !== success) {
this.showError(response.responseText);
return false;
}
try {
var o =... | {//user
userStore.each(function(r){
if(r.get('id') === theId) {
usersArr.push(r);
}
});
} | conditional_block | |
1_compute_MASTER.py | = 'absolute_map_%s' % orbit_id
# Standard values are:
# folder_flux = '%d_%d' % (orbit_id,part)
# file_flux = 'flux_'
folder_flux = '%s_%d' % (orbit_id,part)
file_flux = 'flux_'
# Tolerance of the maximal magnitude difference (5% = 0.05)
p = 0.1
# Recalculate previously computed minutes ? (Recommendation: False -- t... | current_step = orbit_step | conditional_block | |
1_compute_MASTER.py | INCLUDES
import numpy as np
import subprocess
import os
import sys
import time
import resources.constants as const
from resources.routines import *
from resources.TimeStepping import *
######################################################################
# PARAMETERS
# km (only required to compute orbit's period)
ap... | # select only none zero value with resilience to rounding errors
# See resources/routines.py
map_obs = slice_map(map_obstot, minute)
# Count the number of points for that particular minute
total_targets += np.shape(map_obs)[0]
if np.shape(map_obs)[0] > 0 :
# Execute the stray light code only if there is... | np.savetxt('%s/INPUT/coord_sun.dat' % path,[xs,ys,zs,ra_sun,dec_sun,rs],delimiter='\n')
| random_line_split |
d3cap.rs | ether_hdr) };
self.pkts.send(Pkt::IP6(PktMeta::new(ipp.src, ipp.dst, u32::from(ntohs(ipp.len)))))?;
},
ETHERTYPE_802_1X => {
//io::println("802.1X!");
},
_ => {
//println!("Unknown type: {:x}", x);
}
}
... | .collect()) | random_line_split | |
d3cap.rs | ip4: ProtocolHandler<IP4Addr>,
pub ip6: ProtocolHandler<IP6Addr>,
}
impl ProtoGraphController {
fn spawn() -> io::Result<ProtoGraphController> {
let (cap_tx, cap_rx) = channel();
let ctl = ProtoGraphController {
cap_tx: cap_tx,
mac: ProtocolHandler::new("mac")?,
... |
let tap_hdr = unsafe { &*(pkt.pkt_ptr() as *const tap::RadiotapHeader) };
let base: &dot11::Dot11BaseHeader = magic(tap_hdr);
let fc = &base.fr_ctrl;
if fc.protocol_version() != 0 {
// bogus packet, bail
return Err(ParseErr::UnknownPacket);
}
m... | {
unsafe { skip_bytes_cast(pkt, pkt.it_len as isize) }
} | identifier_body |
d3cap.rs | Send,
UnknownPacket
}
impl<T> From<SendError<T>> for ParseErr {
fn from(_: SendError<T>) -> ParseErr {
ParseErr::Send
}
}
trait PktParser {
fn parse(&mut self, pkt: &cap::PcapData) -> Result<(), ParseErr>;
}
pub struct CaptureCtx {
sess: cap::PcapSession,
parser: Box<PktParser+'st... | start_capture | identifier_name | |
d3cap.rs | ip4: ProtocolHandler<IP4Addr>,
pub ip6: ProtocolHandler<IP6Addr>,
}
impl ProtoGraphController {
fn spawn() -> io::Result<ProtoGraphController> {
let (cap_tx, cap_rx) = channel();
let ctl = ProtoGraphController {
cap_tx: cap_tx,
mac: ProtocolHandler::new("mac")?,
... |
match pkt.unwrap() {
Pkt::Mac(ref p) => phctl.mac.update(p),
Pkt::IP4(ref p) => phctl.ip4.update(p),
Pkt::IP6(ref p) => phctl.ip6.update(p),
}
}
})?;
Ok(ctl)
}
fn sender(&self) -> Sender<Pk... | {
break
} | conditional_block |
mod.rs | is_lexical(&self) -> bool {
matches!(self, Self::Lexical)
}
/// Returns `true` if the this mode is `Strict`.
pub fn is_strict(&self) -> bool {
matches!(self, Self::Strict)
}
/// Returns `true` if the this mode is `Global`.
pub fn is_global(&self) -> bool |
}
#[derive(Debug, Trace, Finalize, PartialEq, Clone)]
pub enum ConstructorKind {
Base,
Derived,
}
impl ConstructorKind {
/// Returns `true` if the constructor kind is `Base`.
pub fn is_base(&self) -> bool {
matches!(self, Self::Base)
}
/// Returns `true` if the constructor kind is `D... | {
matches!(self, Self::Global)
} | identifier_body |
mod.rs | if the constructor kind is `Base`.
pub fn is_base(&self) -> bool {
matches!(self, Self::Base)
}
/// Returns `true` if the constructor kind is `Derived`.
pub fn is_derived(&self) -> bool {
matches!(self, Self::Derived)
}
}
// We don't use a standalone `NativeObject` for `Captures` b... | prototype | identifier_name | |
mod.rs | fn is_lexical(&self) -> bool {
matches!(self, Self::Lexical)
}
/// Returns `true` if the this mode is `Strict`.
pub fn is_strict(&self) -> bool {
matches!(self, Self::Strict)
}
/// Returns `true` if the this mode is `Global`.
pub fn is_global(&self) -> bool {
matches!(... | }
/// Boa representation of a Function Object.
///
/// FunctionBody is specific to this interpreter, it will either be Rust code or JavaScript code (AST Node)
///
/// <https://tc39.es/ecma262/#sec-ecmascript-function-objects>
#[derive(Clone, Trace, Finalize)]
pub enum Function {
Native {
#[unsafe_ignore_tr... | .deref_mut()
.as_mut_any()
.downcast_mut::<T>()
.ok_or_else(|| context.construct_type_error("cannot downcast `Captures` to given type"))
} | random_line_split |
mod.rs | {
self.0
.deref_mut()
.as_mut_any()
.downcast_mut::<T>()
.ok_or_else(|| context.construct_type_error("cannot downcast `Captures` to given type"))
}
}
/// Boa representation of a Function Object.
///
/// FunctionBody is specific to this interpreter, it wil... | {
return context.throw_type_error("Not a function");
} | conditional_block | |
EncryptDecryptTextFile.py |
import RotateCipher
import ShiftCipher
import TranspositionCipher
def process_textfile(
string_path: str,
encryption_algorithm: str,
algorithm_key: float,
output_folderpath: str = str(
Path(os.path.expandvars("$HOME")).anchor
) + r"/EncryptDecrypt/",
output_filename: st... | for key, value in kwargs.items():
str_value = str(value)
if str_value.lower() == "False":
kwargs[key] = False
elif str_value.lower() == "True":
kwargs[key] = True
output_filename = ('/' + output_filename)
if not (output_filename.endswith(".txt")):
... | encryption_algorithm = encryption_algorithm.lower()
available_algorithms = ["rotate", "transposition"]
if encryption_algorithm not in available_algorithms:
pprint.pprint(
["Enter an algorithm from the list. Not case-sensitive.",
available_algorithms]
)
... | identifier_body |
EncryptDecryptTextFile.py |
import RotateCipher
import ShiftCipher
import TranspositionCipher
def | (
string_path: str,
encryption_algorithm: str,
algorithm_key: float,
output_folderpath: str = str(
Path(os.path.expandvars("$HOME")).anchor
) + r"/EncryptDecrypt/",
output_filename: str = r"EncryptDecrypt.txt",
to_decrypt=False,
**kwargs
):
encryption_alg... | process_textfile | identifier_name |
EncryptDecryptTextFile.py |
import RotateCipher
import ShiftCipher
import TranspositionCipher
def process_textfile(
string_path: str,
encryption_algorithm: str,
algorithm_key: float,
output_folderpath: str = str(
Path(os.path.expandvars("$HOME")).anchor
) + r"/EncryptDecrypt/",
output_filename: st... | algorithm_key=1,
output_folderpath=r"C:\Users\Rives\Downloads\Encryptions"
)
print(dict_processedtext3a["output_file"])
dict_processedtext3b = process_textfile(
string_path=dict_processedtext3a["output_file"],
encryption... | for i in range(2):
dict_processedtext3a = process_textfile(
string_path=r"C:\Users\Rives\Downloads\Quizzes\Quiz 0 Overwrite Number 2.txt",
encryption_algorithm="rotate",
| random_line_split |
EncryptDecryptTextFile.py |
import RotateCipher
import ShiftCipher
import TranspositionCipher
def process_textfile(
string_path: str,
encryption_algorithm: str,
algorithm_key: float,
output_folderpath: str = str(
Path(os.path.expandvars("$HOME")).anchor
) + r"/EncryptDecrypt/",
output_filename: st... |
if len(algo) == 0:
algo = "rotate"
pprint.pprint(
process_textfile(
string_path=input_filepath,
encryption_algorithm=algo,
algorithm_key=algorithm_key,
output_folderpath=output_folder,
o... | output_file = "EncryptDecrypt.txt" | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.