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
payment.component.ts
import { Component, OnInit, Input, Output, ViewEncapsulation, EventEmitter, NgZone } from '@angular/core'; import { Http, Response, RequestOptions, Headers } from '@angular/http'; import { Router, ActivatedRoute } from '@angular/router'; import { AppService } from '../app-service.service'; import { AlertService } from ...
implements OnInit { // @Input() tab: string; // @Input() user; @Output() renewalDateUpdated: EventEmitter<any> = new EventEmitter(); @Output() planTypeUpdated: EventEmitter<any> = new EventEmitter(); httpOptions: RequestOptions; session: any; billingAmount: any; invoices: any; envi...
PaymentComponent
identifier_name
payment.component.ts
import { Component, OnInit, Input, Output, ViewEncapsulation, EventEmitter, NgZone } from '@angular/core'; import { Http, Response, RequestOptions, Headers } from '@angular/http'; import { Router, ActivatedRoute } from '@angular/router'; import { AppService } from '../app-service.service'; import { AlertService } from ...
cancelSubscription() { this.alertService.show('warn', 'Your active subscription would be cancelled.<br /><br />Are you sure you want to cancel your subscription?'); this.alertService.positiveCallback = (() => { this.alertService.hide(); this.loadingService.show('Cancelling...
{ this.planDuration = duration.durationValue; }
identifier_body
mount_linux.go
// +build linux /* Copyright 2014 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 agree...
if err != nil { mounter.logger.With( zap.Error(err), "command", unmountCommand, "target", target, "output", string(output), ).Error("Unmount failed.") return fmt.Errorf("Unmount failed: %v\nUnmounting command: %s\nUnmounting arguments: %s\nOutput: %v\n", err, unmountCommand, target, string(output)) ...
output, err := command.CombinedOutput()
random_line_split
mount_linux.go
// +build linux /* Copyright 2014 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 agree...
(target string) error { return mounter.unmount(target, UMOUNT_COMMAND) } func (mounter *Mounter) unmount(target string, unmountCommand string) error { mounter.logger.With("target", target).Info("Unmounting.") command := exec.Command(unmountCommand, target) output, err := command.CombinedOutput() if err != nil { ...
Unmount
identifier_name
mount_linux.go
// +build linux /* Copyright 2014 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 agree...
if len(source) > 0 { mountArgs = append(mountArgs, source) } mountArgs = append(mountArgs, target) return mountArgs } // Unmount unmounts the target. func (mounter *Mounter) Unmount(target string) error { return mounter.unmount(target, UMOUNT_COMMAND) } func (mounter *Mounter) unmount(target string, unmountC...
{ mountArgs = append(mountArgs, "-o", strings.Join(options, ",")) }
conditional_block
mount_linux.go
// +build linux /* Copyright 2014 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 agree...
// formatAndMount uses unix utils to format and mount the given disk func (mounter *SafeFormatAndMount) formatAndMount(source string, target string, fstype string, options []string) error { options = append(options, "defaults") mounter.Logger = mounter.Logger.With( "source", source, "target", target, "fstype"...
{ hash := fnv.New32a() scanner := bufio.NewReader(file) for { line, err := scanner.ReadString('\n') if err == io.EOF { break } fields := strings.Fields(line) if len(fields) != expectedNumFieldsPerLine { return 0, fmt.Errorf("wrong number of fields (expected %d, got %d): %s", expectedNumFieldsPerLine,...
identifier_body
siamese_output_result.py
"""train a specific model using a given dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import dataset import math import numpy as np import cv2 import os import feature_extractor import time from data_transformation imp...
else: all_ref_features = np.concatenate( (all_ref_features, one_ref_feature), axis=0) i += 1 except tf.errors.OutOfRangeError: tf.logging.info('End of forward ref images') break if FLAGS.save_features: ...
all_ref_features = one_ref_feature
conditional_block
siamese_output_result.py
"""train a specific model using a given dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import dataset import math import numpy as np import cv2 import os import feature_extractor import time from data_transformation imp...
(filename): """Load a config file and merge it into the default options.""" import yaml with open(filename, 'r') as f: cfg = yaml.load(f) return cfg def _parser_humpback_whale(record, phase='train'): with tf.name_scope('parser_humpback_whale'): features = tf.parse_single_example( ...
_cfg_from_file
identifier_name
siamese_output_result.py
"""train a specific model using a given dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import dataset import math import numpy as np import cv2 import os import feature_extractor import time from data_transformation imp...
'similarity_prob_for_one_query/prob_same_ids:0'), feed_dict={'ref_features:0': all_ref_features, 'dut_features:0': np.expand_dims(all_dut_featurs[i],axis=0)}) one_prob_same_ids = np.concatenate( (np.squeeze(one_prob_sam...
f.write('Image,Id\n') for i in range(len(all_dut_image_names)): one_prob_same_ids = sess.run( tf.get_default_graph().get_tensor_by_name(
random_line_split
siamese_output_result.py
"""train a specific model using a given dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import dataset import math import numpy as np import cv2 import os import feature_extractor import time from data_transformation imp...
def _get_tfrecord_names(folder, split): tfrecord_files = [] files_list = os.listdir(folder) for f in files_list: if (split in f) and ('.tfrecord' in f): tfrecord_files.append(os.path.join(folder, f)) return tfrecord_files def main(_): tf_record_base = '/home/westwell/Desktop/d...
with tf.name_scope('parser_humpback_whale'): features = tf.parse_single_example( serialized=record, features={ 'image': tf.FixedLenFeature([], tf.string), 'label': tf.FixedLenFeature([], tf.int64), 'image_name': tf.FixedLenFeature([], tf.st...
identifier_body
font_atlas.rs
#[macro_use] extern crate glium; use euclid::Rect; use font_kit::font::Font; use glium::backend::Facade; use glium::texture::Texture2d; use glium::{glutin, Surface}; use lyon_path::math::{Angle, Point, Vector}; use lyon_path::Segment; use msdfgen::{compute_msdf, recolor_contours, Contour, PathCollector}; use std::coll...
}) } }
{}
conditional_block
font_atlas.rs
#[macro_use] extern crate glium; use euclid::Rect; use font_kit::font::Font; use glium::backend::Facade; use glium::texture::Texture2d; use glium::{glutin, Surface}; use lyon_path::math::{Angle, Point, Vector}; use lyon_path::Segment; use msdfgen::{compute_msdf, recolor_contours, Contour, PathCollector}; use std::coll...
} (contours, transformation) } #[derive(Copy, Clone)] struct Vertex2D { position: [f32; 2], uv: [f32; 2], color: [f32; 3], } glium::implement_vertex!(Vertex2D, position, uv, color); /// All the information required to render a character from a string #[derive(Clone, Copy, Debug)] struct RenderCha...
} }
random_line_split
font_atlas.rs
#[macro_use] extern crate glium; use euclid::Rect; use font_kit::font::Font; use glium::backend::Facade; use glium::texture::Texture2d; use glium::{glutin, Surface}; use lyon_path::math::{Angle, Point, Vector}; use lyon_path::Segment; use msdfgen::{compute_msdf, recolor_contours, Contour, PathCollector}; use std::coll...
/// Get a glyph ID for a character, its contours, and the typographic bounds for that glyph /// TODO: this should also return font.origin() so we can offset the EM-space /// computations by it. However, on freetype that always returns 0 so for the /// moment we'll get away without it fn get_glyph(font: &Font, chr: ch...
{ use font_kit::family_name::FamilyName; use font_kit::properties::{Properties, Style}; use font_kit::source::SystemSource; let source = SystemSource::new(); source .select_best_match( &[FamilyName::Serif], Properties::new().style(Style::Normal), ) .e...
identifier_body
font_atlas.rs
#[macro_use] extern crate glium; use euclid::Rect; use font_kit::font::Font; use glium::backend::Facade; use glium::texture::Texture2d; use glium::{glutin, Surface}; use lyon_path::math::{Angle, Point, Vector}; use lyon_path::Segment; use msdfgen::{compute_msdf, recolor_contours, Contour, PathCollector}; use std::coll...
{ position: [f32; 2], uv: [f32; 2], color: [f32; 3], } glium::implement_vertex!(Vertex2D, position, uv, color); /// All the information required to render a character from a string #[derive(Clone, Copy, Debug)] struct RenderChar { /// The position of the vertices verts: Rect<f32>, /// The UV ...
Vertex2D
identifier_name
conpty.rs
use failure::Error; use std::io::{self, Error as IoError, Result as IoResult}; extern crate winapi; use crate::pty::conpty::winapi::shared::minwindef::DWORD; use crate::pty::conpty::winapi::shared::winerror::{HRESULT, S_OK}; use crate::pty::conpty::winapi::um::fileapi::{ReadFile, WriteFile}; use crate::pty::conpty::win...
fn cmdline(&self) -> Result<(Vec<u16>, Vec<u16>), Error> { let mut cmdline = Vec::<u16>::new(); let exe = Self::search_path(&self.args[0]); Self::append_quoted(&exe, &mut cmdline); // Ensure that we nul terminate the module name, otherwise we'll // ask CreateProcessW to s...
{ self.input.replace(input); self.output.replace(output); self.hpc.replace(con); self }
identifier_body
conpty.rs
use failure::Error; use std::io::{self, Error as IoError, Result as IoResult}; extern crate winapi; use crate::pty::conpty::winapi::shared::minwindef::DWORD; use crate::pty::conpty::winapi::shared::winerror::{HRESULT, S_OK}; use crate::pty::conpty::winapi::um::fileapi::{ReadFile, WriteFile}; use crate::pty::conpty::win...
(exe: &OsStr) -> OsString { if let Some(path) = env::var_os("PATH") { let extensions = env::var_os("PATHEXT").unwrap_or(".EXE".into()); for path in env::split_paths(&path) { // Check for exactly the user's string in this path dir let candidate = path.join(...
search_path
identifier_name
conpty.rs
use failure::Error; use std::io::{self, Error as IoError, Result as IoResult}; extern crate winapi; use crate::pty::conpty::winapi::shared::minwindef::DWORD; use crate::pty::conpty::winapi::shared::winerror::{HRESULT, S_OK}; use crate::pty::conpty::winapi::um::fileapi::{ReadFile, WriteFile}; use crate::pty::conpty::win...
} } impl OwnedHandle { fn try_clone(&self) -> Result<Self, IoError> { if self.handle == INVALID_HANDLE_VALUE || self.handle.is_null() { return Ok(OwnedHandle { handle: self.handle, }); } let proc = unsafe { GetCurrentProcess() }; let mut...
{ unsafe { CloseHandle(self.handle) }; }
conditional_block
conpty.rs
use failure::Error; use std::io::{self, Error as IoError, Result as IoResult}; extern crate winapi; use crate::pty::conpty::winapi::shared::minwindef::DWORD; use crate::pty::conpty::winapi::shared::winerror::{HRESULT, S_OK}; use crate::pty::conpty::winapi::um::fileapi::{ReadFile, WriteFile}; use crate::pty::conpty::win...
&mut bytes_required, ) }; let mut data = Vec::with_capacity(bytes_required); // We have the right capacity, so force the vec to consider itself // that length. The contents of those bytes will be maintained // by the win32 apis used in this impl. ...
unsafe { InitializeProcThreadAttributeList( ptr::null_mut(), num_attributes, 0,
random_line_split
lfp_session.py
import os import probe_functions as ProbeF import pdc_functions as PDCF import _pickle as cPickle import pandas as pd import numpy as np from functools import reduce import dynet_statespace as dsspace import dynet_con as dcon import xarray as xr import matplotlib.pyplot as plt from functools import reduce class LFPSe...
cond = self.preprocess[preprocess_ind[0]] for probe_id in self.probes.keys(): # first prepare the file name filename = os.path.join(self.result_path, 'PrepData', '{}_{}{}_pres{}s.pkl'.format( probe_id, cond['cond_name'], int(cond['srate']),cond['prestim'])) ...
print("no preprocessing with these parameters is done") return
conditional_block
lfp_session.py
import os import probe_functions as ProbeF import pdc_functions as PDCF import _pickle as cPickle import pandas as pd import numpy as np from functools import reduce import dynet_statespace as dsspace import dynet_con as dcon import xarray as xr import matplotlib.pyplot as plt from functools import reduce class LFPSes...
temp.probes = dict.fromkeys(temp.probes.keys()) temp.loaded_cond = None temp.layer_selected = False cPickle.dump(temp.__dict__, filehandler) filehandler.close() return filename def load_session(self): # be careful about this -> result_path filename = os.path....
filename = os.path.join(self.result_path, 'LFPSession_{}.obj'.format(self.session_id)) filehandler = open(filename, "wb") # Do not save the loaded LFP matrices since they are too big temp = self
random_line_split
lfp_session.py
import os import probe_functions as ProbeF import pdc_functions as PDCF import _pickle as cPickle import pandas as pd import numpy as np from functools import reduce import dynet_statespace as dsspace import dynet_con as dcon import xarray as xr import matplotlib.pyplot as plt from functools import reduce class LFPSe...
def LFP_plot(Y, TimeWin, colors, figure_path): """ A general function to plot LFP averages :param Y: LFP data with dimensions :trials x layers x time x conditions :param TimeWin: :param colors: :param figure_path: :return: """ nroi = len(Y.keys()) fig, axs = plt.subplots(nrows...
""" Initializes the colors class :param color_type: 'uni'/'layers' indicate if it should return only one color per ROI ('Uni') or 6 colors per ROI, for 6 layers('Layers') """ roi_colors_rgb = {'VISp': [.43, .25, .63], 'VISl': [0.03, 0.29, 0.48], 'VISrl': [0.26...
identifier_body
lfp_session.py
import os import probe_functions as ProbeF import pdc_functions as PDCF import _pickle as cPickle import pandas as pd import numpy as np from functools import reduce import dynet_statespace as dsspace import dynet_con as dcon import xarray as xr import matplotlib.pyplot as plt from functools import reduce class LFPSe...
(self, Filename=None): """ This will be done on the loaded_cond data :return: """ if Filename==None: Filename = os.path.join(self.result_path,'PrepData','Cortical_Layers.xlsx') try: layer_table = pd.read_excel(Filename) # set the layer ...
layer_selection
identifier_name
helpers.rs
//! A module with ide helpers for high-level ide features. pub mod import_assets; pub mod insert_use; pub mod merge_imports; pub mod rust_doc; pub mod generated_lints; use std::collections::VecDeque; use base_db::FileId; use either::Either; use hir::{Crate, Enum, ItemInNs, MacroDef, Module, ModuleDef, Name, ScopeDef,...
(path: &hir::ModPath) -> ast::Path { let _p = profile::span("mod_path_to_ast"); let mut segments = Vec::new(); let mut is_abs = false; match path.kind { hir::PathKind::Plain => {} hir::PathKind::Super(0) => segments.push(make::path_segment_self()), hir::PathKind::Super(n) => seg...
mod_path_to_ast
identifier_name
helpers.rs
//! A module with ide helpers for high-level ide features. pub mod import_assets; pub mod insert_use; pub mod merge_imports; pub mod rust_doc; pub mod generated_lints; use std::collections::VecDeque; use base_db::FileId; use either::Either; use hir::{Crate, Enum, ItemInNs, MacroDef, Module, ModuleDef, Name, ScopeDef,...
let mut path = path.split(':'); let trait_ = path.next_back()?; let std_crate = path.next()?; let std_crate = self.find_crate(std_crate)?; let mut module = std_crate.root_module(db); for segment in path { module = module.children(db).find_map(|child| { ...
Some(res) } fn find_def(&self, path: &str) -> Option<ScopeDef> { let db = self.0.db;
random_line_split
helpers.rs
//! A module with ide helpers for high-level ide features. pub mod import_assets; pub mod insert_use; pub mod merge_imports; pub mod rust_doc; pub mod generated_lints; use std::collections::VecDeque; use base_db::FileId; use either::Either; use hir::{Crate, Enum, ItemInNs, MacroDef, Module, ModuleDef, Name, ScopeDef,...
pub fn core_convert_Into(&self) -> Option<Trait> { self.find_trait("core:convert:Into") } pub fn core_option_Option(&self) -> Option<Enum> { self.find_enum("core:option:Option") } pub fn core_result_Result(&self) -> Option<Enum> { self.find_enum("core:result:Result") ...
{ self.find_trait("core:convert:From") }
identifier_body
nanolog.go
// Copyright 2017 Scott Mansfield // // 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...
if idx >= MaxLoggers { panic("Too many loggers") } l := parseLogLine(fmt) lw.loggers[idx] = l lw.writeLogLineHeader(idx, l.Kinds, l.Segs) return Handle(idx) } func parseLogLine(gold string) Logger { // make a copy we can destroy tmp := gold f := &tmp var kinds []reflect.Kind var segs []string var cur...
func (lw *logWriter) AddLogger(fmt string) Handle { // save some kind of string format to the file idx := atomic.AddUint32(lw.curLoggersIdx, 1) - 1
random_line_split
nanolog.go
// Copyright 2017 Scott Mansfield // // 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...
} segs = append(segs, string(curseg)) return Logger{ Kinds: kinds, Segs: segs, } } func peek(s *string) rune { r, _ := utf8.DecodeRuneInString(*s) if r == utf8.RuneError { panic("Malformed log string") } return r } func next(s *string) rune { r, n := utf8.DecodeRuneInString(*s) *s = (*s)[n:] i...
{ if len(*f) == 0 { logpanic("Missing '}' character at end of line", gold) } if next(f) != '}' { logpanic("Missing '}' character", gold) } }
conditional_block
nanolog.go
// Copyright 2017 Scott Mansfield // // 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...
(gold string) Logger { // make a copy we can destroy tmp := gold f := &tmp var kinds []reflect.Kind var segs []string var curseg []rune for len(*f) > 0 { if r := next(f); r != '%' { curseg = append(curseg, r) continue } // Literal % sign if peek(f) == '%' { next(f) curseg = append(curseg, '...
parseLogLine
identifier_name
nanolog.go
// Copyright 2017 Scott Mansfield // // 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...
// AddLogger calls LogWriter.AddLogger on the default log writer. func AddLogger(fmt string) Handle { return defaultLogWriter.AddLogger(fmt) } func (lw *logWriter) AddLogger(fmt string) Handle { // save some kind of string format to the file idx := atomic.AddUint32(lw.curLoggersIdx, 1) - 1 if idx >= MaxLoggers ...
{ // grab write lock to ensure no prblems lw.writeLock.Lock() defer lw.writeLock.Unlock() return lw.w.Flush() }
identifier_body
storageos.go
package main import ( "errors" "fmt" "io/ioutil" "os" "strings" "github.com/dnephin/cobra" "github.com/sirupsen/logrus" "github.com/spf13/pflag" "github.com/docker/docker/pkg/term" "github.com/storageos/go-api/serror" "github.com/storageos/go-api/types/versions" "github.com/storageos/go-cli/cli" "github...
cmdArgs := ccmd.Args ccmd.Args = func(cmd *cobra.Command, args []string) error { initializeStorageOSCli(storageosCli, flags, opts) if err := isSupported(cmd, storageosCli.Client().ClientVersion(), storageosCli.HasExperimental()); err != nil { return err } return cmdArgs(cmd, args) } }) } func ...
{ return }
conditional_block
storageos.go
package main import ( "errors" "fmt" "io/ioutil" "os" "strings" "github.com/dnephin/cobra" "github.com/sirupsen/logrus" "github.com/spf13/pflag" "github.com/docker/docker/pkg/term" "github.com/storageos/go-api/serror" "github.com/storageos/go-api/types/versions" "github.com/storageos/go-cli/cli" "github...
func isCoreOS() (bool, error) { f, err := ioutil.ReadFile("/etc/lsb-release") if err != nil { return false, err } return strings.Contains(string(f), "DISTRIB_ID=CoreOS"), nil } func isInContainer() (bool, error) { f, err := ioutil.ReadFile("/proc/1/cgroup") if err != nil { return false, err } // TODO: ...
{ debug.Disable() }
identifier_body
storageos.go
package main import ( "errors" "fmt" "io/ioutil" "os" "strings" "github.com/dnephin/cobra" "github.com/sirupsen/logrus" "github.com/spf13/pflag" "github.com/docker/docker/pkg/term" "github.com/storageos/go-api/serror" "github.com/storageos/go-api/types/versions" "github.com/storageos/go-cli/cli" "github...
(storageosCli *command.StorageOSCli) *cobra.Command { opts := cliflags.NewClientOptions() var flags *pflag.FlagSet cmd := &cobra.Command{ Use: "storageos [OPTIONS] COMMAND [ARG...]", Short: shortDesc, SilenceUsage: true, SilenceErrors: true, TraverseChildren: true, Args: ...
newStorageOSCommand
identifier_name
storageos.go
package main import ( "errors" "fmt" "io/ioutil" "os" "strings" "github.com/dnephin/cobra" "github.com/sirupsen/logrus" "github.com/spf13/pflag" "github.com/docker/docker/pkg/term" "github.com/storageos/go-api/serror" "github.com/storageos/go-api/types/versions" "github.com/storageos/go-cli/cli" "github...
// } return nil } func getFlagVersion(f *pflag.Flag) string { if flagVersion, ok := f.Annotations["version"]; ok && len(flagVersion) == 1 { return flagVersion[0] } return "" } func isFlagSupported(f *pflag.Flag, clientVersion string) bool { if v := getFlagVersion(f); v != "" { return versions.GreaterThanOr...
// if len(errs) > 0 { // return errors.New(strings.Join(errs, "\n"))
random_line_split
pool.rs
use std::collections::BinaryHeap; use std::iter::IntoIterator; use std::{marker, mem}; use std::sync::{mpsc, atomic, Mutex, Arc}; use std::thread; use fnbox::FnBox; use crossbeam::{self, Scope}; type JobInner<'b> = Box<for<'a> FnBox<&'a [mpsc::Sender<Work>]> + Send + 'b>; struct Job { func: JobInner<'static>, } ...
Ok(false) => { // ignore return, because we // need to wait until the // workers have exited (i.e, // the Err arm above...
// closed, done! Ok(true) | Err(_) => break,
random_line_split
pool.rs
use std::collections::BinaryHeap; use std::iter::IntoIterator; use std::{marker, mem}; use std::sync::{mpsc, atomic, Mutex, Arc}; use std::thread; use fnbox::FnBox; use crossbeam::{self, Scope}; type JobInner<'b> = Box<for<'a> FnBox<&'a [mpsc::Sender<Work>]> + Send + 'b>; struct Job { func: JobInner<'static>, } ...
{ func: WorkInner<'static> } struct JobStatus { wait: bool, job_finished: mpsc::Receiver<Result<(), ()>>, } /// A token representing a job submitted to the thread pool. /// /// This helps ensure that a job is finished before borrowed resources /// in the job (and the pool itself) are invalidated. /// ///...
Work
identifier_name
pool.rs
use std::collections::BinaryHeap; use std::iter::IntoIterator; use std::{marker, mem}; use std::sync::{mpsc, atomic, Mutex, Arc}; use std::thread; use fnbox::FnBox; use crossbeam::{self, Scope}; type JobInner<'b> = Box<for<'a> FnBox<&'a [mpsc::Sender<Work>]> + Send + 'b>; struct Job { func: JobInner<'static>, } ...
} } } }, move |(needwork_tx, shared)| { let mut iter = iter.into_iter().fuse().enumerate(); drop(needwork_tx); ...
{ break }
conditional_block
needless_pass_by_ref_mut.rs
use super::needless_pass_by_value::requires_exact_signature; use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::source::snippet; use clippy_utils::{get_parent_node, is_from_proc_macro, is_self}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_errors::Applicability; use rustc_hir:...
fn copy(&mut self, _cmt: &euv::PlaceWithHirId<'tcx>, _id: HirId) { self.prev_bind = None; } fn fake_read( &mut self, cmt: &rustc_hir_typeck::expr_use_visitor::PlaceWithHirId<'tcx>, cause: FakeReadCause, _id: HirId, ) { if let euv::Place { ba...
{ self.prev_bind = None; if let euv::Place { projections, base: euv::PlaceBase::Local(vid), .. } = &cmt.place { if !projections.is_empty() { self.add_mutably_used_var(*vid); } } }
identifier_body
needless_pass_by_ref_mut.rs
use super::needless_pass_by_value::requires_exact_signature; use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::source::snippet; use clippy_utils::{get_parent_node, is_from_proc_macro, is_self}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_errors::Applicability; use rustc_hir:...
( &mut self, cmt: &rustc_hir_typeck::expr_use_visitor::PlaceWithHirId<'tcx>, cause: FakeReadCause, _id: HirId, ) { if let euv::Place { base: euv::PlaceBase::Upvar(UpvarId { var_path: UpvarPath { hir_id: vid }, ...
fake_read
identifier_name
needless_pass_by_ref_mut.rs
use super::needless_pass_by_value::requires_exact_signature; use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::source::snippet; use clippy_utils::{get_parent_node, is_from_proc_macro, is_self}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_errors::Applicability; use rustc_hir:...
} } } } #[derive(Default)] struct MutablyUsedVariablesCtxt { mutably_used_vars: HirIdSet, prev_bind: Option<HirId>, prev_move_to_closure: HirIdSet, aliases: HirIdMap<HirId>, async_closures: FxHashSet<LocalDefId>, } impl MutablyUsedVariablesCtxt { fn add_mutably_used_va...
{ span_lint_hir_and_then( cx, NEEDLESS_PASS_BY_REF_MUT, cx.tcx.hir().local_def_id_to_hir_id(*fn_def_id), sp, "this argument is a mutable reference, but not used mutably", ...
conditional_block
needless_pass_by_ref_mut.rs
use super::needless_pass_by_value::requires_exact_signature; use clippy_utils::diagnostics::span_lint_hir_and_then; use clippy_utils::source::snippet; use clippy_utils::{get_parent_node, is_from_proc_macro, is_self}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_errors::Applicability; use rustc_hir:...
&mut self, cx: &LateContext<'tcx>, kind: FnKind<'tcx>, decl: &'tcx FnDecl<'tcx>, body: &'tcx Body<'_>, span: Span, fn_def_id: LocalDefId, ) { if span.from_expansion() { return; } let hir_id = cx.tcx.hir().local_def_id_to_hi...
impl<'tcx> LateLintPass<'tcx> for NeedlessPassByRefMut<'tcx> { fn check_fn(
random_line_split
transform.ts
/** * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ import {Message, makeMessageIdMap} from '../messages.js'; import {writeLocaleCodesModule} from '../locales.js'; import type {Locale} from '../types/locale.js'; import type {Config} from '../types/config.js'; import type {Transfor...
if (eventSymbol.flags & ts.SymbolFlags.Alias) { // Symbols will be aliased in the case of // `import {LOCALE_STATUS_EVENT} ...` // but not in the case of `import * as ...`. eventSymbol = this.typeChecker.getAliasedSymbol(eventSymbol); } for (const decl of eventSymbol.de...
// that it was declared in the lit-localize module. let eventSymbol = this.typeChecker.getSymbolAtLocation(node); if (eventSymbol && eventSymbol.name === 'LOCALE_STATUS_EVENT') {
random_line_split
transform.ts
/** * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ import {Message, makeMessageIdMap} from '../messages.js'; import {writeLocaleCodesModule} from '../locales.js'; import type {Locale} from '../types/locale.js'; import type {Config} from '../types/config.js'; import type {Transfor...
() { this.assertTranslationsAreValid(); const {translations} = this.readTranslationsSync(); await transformOutput( translations, this.config, this.config.output, this.program ); } /** * Make a map from each locale code to a function that takes a TypeScript * Program an...
build
identifier_name
transform.ts
/** * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ import {Message, makeMessageIdMap} from '../messages.js'; import {writeLocaleCodesModule} from '../locales.js'; import type {Locale} from '../types/locale.js'; import type {Config} from '../types/config.js'; import type {Transfor...
// If translations are available, replace the source template from the // second argument with the corresponding translation. if (this.translations !== undefined) { const translation = this.translations.get(id); if (translation !== undefined) { const templateLiteralBody = translation.c...
{ for (const span of template.templateSpans) { // TODO(aomarks) Support less brittle/more readable placeholder keys. const key = this.sourceFile.text.slice( span.expression.pos, span.expression.end ); sourceExpressions.set(key, span.expression); } }
conditional_block
messenger.rs
// This file is Copyright its original authors, visible in version control // history. // // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // You may...
(&self, _peer_node_id: &PublicKey, msg: &msgs::OnionMessage) { let control_tlvs_ss = match self.keys_manager.ecdh(Recipient::Node, &msg.blinding_point, None) { Ok(ss) => ss, Err(e) => { log_error!(self.logger, "Failed to retrieve node secret: {:?}", e); return } }; let onion_decode_ss = { let...
handle_onion_message
identifier_name
messenger.rs
// This file is Copyright its original authors, visible in version control // history. // // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // You may...
public_key: new_pubkey, hop_data: new_packet_bytes, hmac: next_hop_hmac, }; let onion_message = msgs::OnionMessage { blinding_point: match next_blinding_override { Some(blinding_point) => blinding_point, None => { let blinding_factor = { let mut sha = Sha256::engin...
version: 0,
random_line_split
messenger.rs
// This file is Copyright its original authors, visible in version control // history. // // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // You may...
} /// Errors that may occur when [sending an onion message]. /// /// [sending an onion message]: OnionMessenger::send_onion_message #[derive(Debug, PartialEq)] pub enum SendError { /// Errored computing onion message packet keys. Secp256k1(secp256k1::Error), /// Because implementations such as Eclair will drop oni...
{ match self { Destination::Node(_) => 1, Destination::BlindedRoute(BlindedRoute { blinded_hops, .. }) => blinded_hops.len(), } }
identifier_body
joint_feldman.rs
//! Implements the Distributed Key Generation protocol from //! [Pedersen](https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_21.pdf). //! The protocol runs at minimum in two phases and at most in three phases. use super::common::*; use crate::primitives::{ group::Group, phases::{Phase0, Phase1, Phas...
qual: group, public: add_public, share: ds, }) } } #[cfg(test)] pub mod tests { use super::*; use crate::primitives::{ common::tests::{check2, full_dkg, id_out, id_resp, invalid2, invalid_shares, setup_group}, default_threshold, }; use std...
random_line_split
joint_feldman.rs
//! Implements the Distributed Key Generation protocol from //! [Pedersen](https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_21.pdf). //! The protocol runs at minimum in two phases and at most in three phases. use super::common::*; use crate::primitives::{ group::Group, phases::{Phase0, Phase1, Phas...
// check if the public key is part of the group let index = group .index(&public_key) .ok_or(DKGError::PublicKeyNotFound)?; // Generate a secret polynomial and commit to it let secret = PrivatePoly::<C>::new_from(group.threshold - 1, rng); let public = ...
{ return Err(DKGError::PrivateKeyInvalid); }
conditional_block
joint_feldman.rs
//! Implements the Distributed Key Generation protocol from //! [Pedersen](https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_21.pdf). //! The protocol runs at minimum in two phases and at most in three phases. use super::common::*; use crate::primitives::{ group::Group, phases::{Phase0, Phase1, Phas...
} #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(bound = "C::Scalar: DeserializeOwned")] /// DKG Stage which waits to receive the shares from the previous phase's participants /// as input. After processing the shares, if there were any complaints it will generate /// a bundle of responses for the next phase...
{ let bundle = create_share_bundle( self.info.index, &self.info.secret, &self.info.public, &self.info.group, rng, )?; let dw = DKGWaitingShare { info: self.info }; Ok((dw, Some(bundle))) }
identifier_body
joint_feldman.rs
//! Implements the Distributed Key Generation protocol from //! [Pedersen](https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_21.pdf). //! The protocol runs at minimum in two phases and at most in three phases. use super::common::*; use crate::primitives::{ group::Group, phases::{Phase0, Phase1, Phas...
<R: RngCore>( private_key: C::Scalar, group: Group<C>, rng: &mut R, ) -> Result<DKG<C>, DKGError> { // get the public key let mut public_key = C::Point::one(); public_key.mul(&private_key); // make sure the private key is not identity element nor neutral elem...
new_rand
identifier_name
paging.rs
// Copyright (c) 2017 Colin Finck, RWTH Aachen University // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distribute...
else { None } } fn drop_user_space(&mut self) { let last = 1 << PAGE_MAP_BITS; let table_address = self as *const PageTable<L> as usize; for index in 0..last { if self.entries[index].is_present() && self.entries[index].is_user() { // currently, the user space uses only 4KB pages if L::LEVEL >...
{ if L::LEVEL > S::MAP_LEVEL { let subtable = self.subtable::<S>(page); subtable.get_page_table_entry::<S>(page) } else { Some(self.entries[index]) } }
conditional_block
paging.rs
// Copyright (c) 2017 Colin Finck, RWTH Aachen University // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distribute...
{} impl PageSize for BasePageSize { const SIZE: usize = 0x1000; const MAP_LEVEL: usize = 0; const MAP_EXTRA_FLAG: PageTableEntryFlags = PageTableEntryFlags::BLANK; } /// A 2 MiB page mapped in the PD. #[derive(Clone, Copy)] pub enum LargePageSize {} impl PageSize for LargePageSize { const SIZE: usize = 0x200000; ...
BasePageSize
identifier_name
paging.rs
// Copyright (c) 2017 Colin Finck, RWTH Aachen University // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distribute...
pub fn get_physical_address<S: PageSize>(virtual_address: usize) -> usize { debug!("Getting physical address for {:#X}", virtual_address); let page = Page::<S>::including_address(virtual_address); let root_pagetable = unsafe { &mut *PML4_ADDRESS }; let address = root_pagetable .get_page_table_entry(page) .ex...
{ debug!("Looking up Page Table Entry for {:#X}", virtual_address); let page = Page::<S>::including_address(virtual_address); let root_pagetable = unsafe { &mut *PML4_ADDRESS }; root_pagetable.get_page_table_entry(page) }
identifier_body
paging.rs
// Copyright (c) 2017 Colin Finck, RWTH Aachen University // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distribute...
/// A Page Directory (PD), with numeric level 1 and PT subtables. enum PD {} impl PageTableLevel for PD { const LEVEL: usize = 1; } impl PageTableLevelWithSubtables for PD { type SubtableLevel = PT; } /// A Page Table (PT), with numeric level 0 and no subtables. enum PT {} impl PageTableLevel for PT { const LEVEL...
}
random_line_split
inherents.rs
use nimiq_account::StakingContract; use nimiq_block::{ForkProof, MacroBlock, MacroHeader, SkipBlockInfo}; use nimiq_blockchain_interface::AbstractBlockchain; use nimiq_database as db; use nimiq_keys::Address; use nimiq_primitives::{ account::AccountType, coin::Coin, policy::Policy, slots_allocation::{Ja...
(&self) -> Inherent { // Create the FinalizeEpoch inherent. Inherent::FinalizeEpoch } }
finalize_previous_epoch
identifier_name
inherents.rs
use nimiq_account::StakingContract; use nimiq_block::{ForkProof, MacroBlock, MacroHeader, SkipBlockInfo}; use nimiq_blockchain_interface::AbstractBlockchain; use nimiq_database as db; use nimiq_keys::Address; use nimiq_primitives::{ account::AccountType, coin::Coin, policy::Policy, slots_allocation::{Ja...
None }; // Create the JailedValidator struct. let jailed_validator = JailedValidator { slots: proposer_slot.validator.slots, validator_address: proposer_slot.validator.address, offense_event_block: fork_proof.header1.block_number, }; ...
} else {
random_line_split
inherents.rs
use nimiq_account::StakingContract; use nimiq_block::{ForkProof, MacroBlock, MacroHeader, SkipBlockInfo}; use nimiq_blockchain_interface::AbstractBlockchain; use nimiq_database as db; use nimiq_keys::Address; use nimiq_primitives::{ account::AccountType, coin::Coin, policy::Policy, slots_allocation::{Ja...
/// Creates the inherent to finalize an epoch. The inherent is for updating the StakingContract. pub fn finalize_previous_epoch(&self) -> Inherent { // Create the FinalizeEpoch inherent. Inherent::FinalizeEpoch } }
{ let prev_macro_info = &state.macro_info; // Special case for first batch: Batch 0 is finalized by definition. if Policy::batch_at(macro_header.block_number) - 1 == 0 { return vec![]; } // Get validator slots // NOTE: Fields `current_slots` and `previous_sl...
identifier_body
inherents.rs
use nimiq_account::StakingContract; use nimiq_block::{ForkProof, MacroBlock, MacroHeader, SkipBlockInfo}; use nimiq_blockchain_interface::AbstractBlockchain; use nimiq_database as db; use nimiq_keys::Address; use nimiq_primitives::{ account::AccountType, coin::Coin, policy::Policy, slots_allocation::{Ja...
else { break; } } // Compute reward from slot reward and number of eligible slots. Also update the burned // reward from the number of penalized slots. let reward = slot_reward .checked_mul(num_eligible_slots as u64) ...
{ assert!(num_eligible_slots > 0); penalized_set_iter.next(); num_eligible_slots -= 1; num_penalized_slots += 1; }
conditional_block
variable_def.py
''' variable_def.py Copyright 2012 Andres Riancho This file is part of w3af, w3af.sourceforge.net . w3af is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. w3af is distributed in the hope...
for vulnty, count in safe_for.iteritems(): if count == len(vars): self._safe_for.append(vulnty) return vars def set_clean(self): self._controlled_by_user = None self._taint_source = None self._is_...
if fc in self.funccall_nodes and hasattr(fc, '_obj') and fc._obj.get_called_obj(): vars.remove(n) continue vulnty = get_vulnty_for_sec(fc.name) if vulnty: if vulnty not in safe_for: ...
conditional_block
variable_def.py
''' variable_def.py Copyright 2012 Andres Riancho This file is part of w3af, w3af.sourceforge.net . w3af is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. w3af is distributed in the hope...
@property def taint_source(self): ''' Return the taint source for this Variable Definition if any; otherwise return None. $a = $_GET['test']; $b = $a . $_GET['ok']; print $b; $b taint source is ['test', 'ok'] ''' tai...
''' Returns bool that indicates if this variable is tainted. ''' #cbusr = self._controlled_by_user #cbusr = None # no cache #if cbusr is None: cbusr = False #todo look at this if self.is_root: if self._name in VariableDef.USER_VARS: ...
identifier_body
variable_def.py
''' variable_def.py Copyright 2012 Andres Riancho This file is part of w3af, w3af.sourceforge.net . w3af is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. w3af is distributed in the hope...
'file_name': self.get_file_name(), 'lineno': self.lineno, 'status': self.controlled_by_user and \ ("'Tainted'. Source: '%s'" % self.taint_source) or \ "'Clean'" } def is_tainted_for(self, vulnty): if vuln...
def __str__(self): return ("Line %(lineno)s in '%(file_name)s'. Declaration of variable '%(name)s'." " Status: %(status)s") % \ {'name': self.name,
random_line_split
variable_def.py
''' variable_def.py Copyright 2012 Andres Riancho This file is part of w3af, w3af.sourceforge.net . w3af is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. w3af is distributed in the hope...
(self, is_root): self._is_root = is_root @property def parents(self): ''' Get this var's parent variable ''' if self._is_root: return None if not self._parents: # Function calls - add return values of functions as parents ...
is_root
identifier_name
index.js
$(function () { //---------- Initializing plugins ---------- //------------------------------------------ var galleryGrid = $('#gallery-grid'), reviews = $('.reviews'), preloader = $('.preloader'), calendar = $('#calendarContainer'), ...
eading, text, icon) { return { heading: heading, text : text, showHideTransition : 'fade', textColor : '#fff', icon: icon, hideAfter : 5000, stack : 5, textAlign : 'left', position : 'bottom-rig...
ight / 3) { $('.arrow-down svg').css({ 'transform': 'rotate(180deg)' }); $('.arrow-down a').attr('href', '#home'); } else { $('.arrow-down svg').css({ 'transform': 'rotate(0)' }); $('.arrow-...
identifier_body
index.js
$(function () { //---------- Initializing plugins ---------- //------------------------------------------ var galleryGrid = $('#gallery-grid'), reviews = $('.reviews'), preloader = $('.preloader'), calendar = $('#calendarContainer'), ...
// Magnific Popup YouTube $('.popup-youtube').magnificPopup({ type: 'iframe', closeBtnInside: false, closeMarkup: closeMarkup, mainClass: 'mfp-fade', removalDelay: 300 }); // Magnific Popup Reviews $('.reviews__link').magnificPopup({ type: ...
'lastRow': 'justify', 'margins': 10, 'target': '_blank' });
random_line_split
index.js
$(function () { //---------- Initializing plugins ---------- //------------------------------------------ var galleryGrid = $('#gallery-grid'), reviews = $('.reviews'), preloader = $('.preloader'), calendar = $('#calendarContainer'), ...
form').submit(function () { //Change var th = $(this), confident = $('#confident'); action = 'send_mail'; nonce = th.data("nonce"); if (!phoneFlag) { $.toast(toast_create( 'Внимание...', 'Введите корректный ...
ayscale(0)' }); } }); //E-mail Ajax Send $('.contact-form__
conditional_block
index.js
$(function () { //---------- Initializing plugins ---------- //------------------------------------------ var galleryGrid = $('#gallery-grid'), reviews = $('.reviews'), preloader = $('.preloader'), calendar = $('#calendarContainer'), ...
= '', text = '', content = '', time = '', startTime = '', endTime = '', location = '', address = '', country = '', city = '', fullAddress = '', phone = '', meta = '...
var title
identifier_name
Housing.py
import os import tarfile from six.moves import urllib import pandas as pd from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt import numpy as np from zlib import crc32 #For compressing data... from sklearn.model_selection import train_test_split, StratifiedShuffleSplit, cross_val_score, GridSearc...
#Train a Machine Learning model using linear regression lin_reg = LinearRegression() lin_reg.fit(housing_prepared, housing_labels) #Try linear regression model out on a few instances from teh training set! some_data = housing.iloc[:5] some_labels = housing_labels.iloc[:5] some_data_prepare...
#2.) Categorical columns should be transformed using a OneHotEncoder #Apply this ColumnTransformer to the housing data --> applies each transformer to the appropriate columns and #concatenates the outputs along the second axis housing_prepared = full_pipeline.fit_transform(housing)
random_line_split
Housing.py
import os import tarfile from six.moves import urllib import pandas as pd from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt import numpy as np from zlib import crc32 #For compressing data... from sklearn.model_selection import train_test_split, StratifiedShuffleSplit, cross_val_score, GridSearc...
(self, X, y=None): room_per_household = X[:, rooms_ix] / X[:, households_ix] population_per_household = X[:, population_ix] / X[:, households_ix] if self.add_bedrooms_per_room: bedrooms_per_room = X[:, bedrooms_ix] / X[:, rooms_ix] return np.c_[X, room_per_household, popu...
transform
identifier_name
Housing.py
import os import tarfile from six.moves import urllib import pandas as pd from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt import numpy as np from zlib import crc32 #For compressing data... from sklearn.model_selection import train_test_split, StratifiedShuffleSplit, cross_val_score, GridSearc...
#This transformer has one hyperparamter, "add_bedrooms_per_room", set to True by default and can easily allow for the #determination of whether adding this attribute helps the Machine Learning algorithm (gate the data by adding #a hyperparamter you are not %100 sure about def fetch_housing_data(housing_url=HOUSING_U...
def __init__(self, add_bedrooms_per_room = True): #No *args or **kargs self.add_bedrooms_per_room = add_bedrooms_per_room def fit(self, X, y=None): return self #Nothing else to do def transform(self, X, y=None): room_per_household = X[:, rooms_ix] / X[:, households_ix] population...
identifier_body
Housing.py
import os import tarfile from six.moves import urllib import pandas as pd from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt import numpy as np from zlib import crc32 #For compressing data... from sklearn.model_selection import train_test_split, StratifiedShuffleSplit, cross_val_score, GridSearc...
print(strat_test_set["income_cat"].value_counts()/len(strat_test_set)) #Compare to Histogram to See if Ratio of Test Set Data Matches the Height of the Bars train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42) compare_props = pd.DataFrame({ "Overall": housing["income_c...
strat_train_set = housing.loc[train_index] strat_test_set = housing.loc[test_index] #.loc can access a group of rows or columns by label(s)
conditional_block
reader.go
package ppcap import ( "encoding/binary" "io" "os" "reflect" "github.com/OneOfOne/xxhash" ) // DataReadStream is used for streaming packets from a ppcapd (data file). // Can be used with or without the corresponding index file. // If used with an index file, call SetReadRange to iterate inside a /...
memidx := &SimpleInMemoryIndex{} err := ReadIndexFileHeader(indexFd, &memidx.IndexHeader) if err != nil { return nil, err } BuildPacketHeaderLayout(&memidx.Layout, memidx.IndexHeader.Flags) memidx.IndexFileSize, err = getFileSize(indexFd) if err != nil { return nil, err } memidx.BlockCount ...
} func ReadIndexIntoMemory(indexFd *os.File) (*SimpleInMemoryIndex, error) {
random_line_split
reader.go
package ppcap import ( "encoding/binary" "io" "os" "reflect" "github.com/OneOfOne/xxhash" ) // DataReadStream is used for streaming packets from a ppcapd (data file). // Can be used with or without the corresponding index file. // If used with an index file, call SetReadRange to iterate inside a /...
else { // read more unless the underlying file is already EOF if rs.isunderlyingeof { rs.iseof = true } else { err := rs.refillBuffer(wholePacketSize) if err != nil { return err } } } } } func GetNumberOfBlocks(indexFileSize int64, IsTruncated *bool) int { if indexF...
{ rs.bufferAvail -= wholePacketSize rs.bufferUsed += wholePacketSize return nil }
conditional_block
reader.go
package ppcap import ( "encoding/binary" "io" "os" "reflect" "github.com/OneOfOne/xxhash" ) // DataReadStream is used for streaming packets from a ppcapd (data file). // Can be used with or without the corresponding index file. // If used with an index file, call SetReadRange to iterate inside a /...
(output *NextPacketOutput) error { for { // handle EOF if rs.iseof { if rs.bufferAvail == 0 { return io.EOF } return io.ErrUnexpectedEOF } rdbuf := rs.buf[rs.bufferUsed : rs.bufferUsed+rs.bufferAvail] success := NextPacket(&rdbuf, &rs.hdrlay, output) wholePacketSize := output.whol...
ReadNextPacket
identifier_name
reader.go
package ppcap import ( "encoding/binary" "io" "os" "reflect" "github.com/OneOfOne/xxhash" ) // DataReadStream is used for streaming packets from a ppcapd (data file). // Can be used with or without the corresponding index file. // If used with an index file, call SetReadRange to iterate inside a /...
func (rs *DataReadStream) refillBuffer(packetLen int) error { copy(rs.buf, rs.buf[rs.bufferUsed:]) if packetLen*16 > cap(rs.buf) { // make space for 16x the largest packet, so that the // circular buffer scheme doesn't have too much copying overhead newbuf := make([]byte, packetLen*16) copy(newbuf, ...
{ rs := &DataReadStream{} rs.hdrlay = *hdrlay rs.reader = reader rs.buf = make([]byte, 2*PPCAP_DEFAULT_MAX_BLOCK_SIZE) XXX_HACK_autodetect_libpcap_layout(reader, &rs.hdrlay) rs.reset() return rs }
identifier_body
testclient.rs
extern crate byteorder; extern crate clap; extern crate data_encoding; extern crate env_logger; #[macro_use] extern crate log; extern crate qrcodegen; extern crate saltyrtc_client; extern crate saltyrtc_task_relayed_data; extern crate tokio_core; use std::env; use std::io::Write; use std::process; use std::sync::{Arc,...
let pubkey = HEXLOWER.decode(b"4242424242424242424242424242424242424242424242424242424242424242").unwrap(); let auth_token = HEXLOWER.decode(b"2323232323232323232323232323232323232323232323232323232323232323").unwrap(); let server_pubkey = HEXLOWER.decode(b"133713371337133713371337133713371337133...
ake_qrcode_data() {
identifier_name
testclient.rs
extern crate byteorder; extern crate clap; extern crate data_encoding; extern crate env_logger; #[macro_use] extern crate log; extern crate qrcodegen; extern crate saltyrtc_client; extern crate saltyrtc_task_relayed_data; extern crate tokio_core; use std::env; use std::io::Write; use std::process; use std::sync::{Arc,...
g(test)] mod tests { use super::*; #[test] fn test_make_qrcode_data() { let pubkey = HEXLOWER.decode(b"4242424242424242424242424242424242424242424242424242424242424242").unwrap(); let auth_token = HEXLOWER.decode(b"2323232323232323232323232323232323232323232323232323232323232323").unwrap();...
// Set up CLI arguments let arg_srv_host = Arg::with_name(ARG_SRV_HOST) .short('h') .takes_value(true) .value_name("SRV_HOST") .required(true) .default_value("server.saltyrtc.org") .help("The SaltyRTC server hostname"); let arg_srv_port = Arg::with_name(ARG_S...
identifier_body
testclient.rs
extern crate byteorder; extern crate clap; extern crate data_encoding; extern crate env_logger; #[macro_use] extern crate log; extern crate qrcodegen; extern crate saltyrtc_client; extern crate saltyrtc_task_relayed_data; extern crate tokio_core; use std::env; use std::io::Write; use std::process; use std::sync::{Arc,...
client.read().unwrap().auth_token().unwrap().secret_key_bytes(), &server_pubkey, ); // Print connection info println!("\n#====================#"); println!("Host: {}:{}", server_host, server_port); match role { Role::Initiator => { println!("Pubkey: {}", HEXLOWER...
server_host, server_port, pubkey.as_bytes(),
random_line_split
main.rs
mod cmd; mod config; mod edit; mod error; mod fmt; mod opts; use std::env; use std::ffi::OsString; use std::fs; use std::io::{self, BufRead, Write}; use std::path::{Path, PathBuf}; use std::process::{self, Command, Stdio}; use atty::Stream::{Stderr, Stdout}; use prettyprint::{PagingMode, PrettyPrinter}; use quote::qu...
// Based on https://github.com/rsolomo/cargo-check fn apply_args(cmd: &mut Command, args: &Args, outfile: &Path) { let mut line = Line::new("cargo"); line.arg("rustc"); if args.tests && args.test.is_none() { line.arg("--profile=test"); } else { line.arg("--profile=check"); } ...
match env::var_os("RUSTFMT") { Some(which) => { if which.is_empty() { None } else { Some(PathBuf::from(which)) } } None => toolchain_find::find_installed_component("rustfmt"), } }
identifier_body
main.rs
mod cmd; mod config; mod edit; mod error; mod fmt; mod opts; use std::env; use std::ffi::OsString; use std::fs; use std::io::{self, BufRead, Write}; use std::path::{Path, PathBuf}; use std::process::{self, Command, Stdio}; use atty::Stream::{Stderr, Stdout}; use prettyprint::{PagingMode, PrettyPrinter}; use quote::qu...
() -> Result<i32> { const NO_RUN_NIGHTLY: &str = "CARGO_EXPAND_NO_RUN_NIGHTLY"; let maybe_nightly = !definitely_not_nightly(); if maybe_nightly || env::var_os(NO_RUN_NIGHTLY).is_some() { return cargo_expand(); } let mut nightly = Command::new("cargo"); nightly.arg("+nightly"); nigh...
cargo_expand_or_run_nightly
identifier_name
main.rs
mod cmd; mod config; mod edit; mod error; mod fmt; mod opts; use std::env; use std::ffi::OsString; use std::fs; use std::io::{self, BufRead, Write}; use std::path::{Path, PathBuf}; use std::process::{self, Command, Stdio}; use atty::Stream::{Stderr, Stdout}; use prettyprint::{PagingMode, PrettyPrinter}; use quote::qu...
}) } fn definitely_not_nightly() -> bool { let mut cmd = Command::new(cargo_binary()); cmd.arg("--version"); let output = match cmd.output() { Ok(output) => output, Err(_) => return false, }; let version = match String::from_utf8(output.stdout) { Ok(version) => version...
} }
random_line_split
main.rs
mod cmd; mod config; mod edit; mod error; mod fmt; mod opts; use std::env; use std::ffi::OsString; use std::fs; use std::io::{self, BufRead, Write}; use std::path::{Path, PathBuf}; use std::process::{self, Command, Stdio}; use atty::Stream::{Stderr, Stdout}; use prettyprint::{PagingMode, PrettyPrinter}; use quote::qu...
if args.frozen { line.arg("--frozen"); } if args.locked { line.arg("--locked"); } for unstable_flag in &args.unstable_flags { line.arg("-Z"); line.arg(unstable_flag); } line.arg("--"); line.arg("-o"); line.arg(outfile); line.arg("-Zunstable-op...
line.arg(if atty::is(Stderr) { "always" } else { "never" }); }
conditional_block
miner.rs
use crate::network::message::{Message}; use crate::network::server::Handle as ServerHandle; use std::sync::{Arc, Mutex}; use crate::crypto::hash::{H256, Hashable, H160}; use crate::blockchain::Blockchain; use crate::block::{Block,Header,Content}; use crate::crypto::merkle::{MerkleTree}; use crate::transaction::{Transa...
thread::sleep(interval); } } }
thread::sleep(interval); } } let interval = time::Duration::from_micros(1000 as u64);
random_line_split
miner.rs
use crate::network::message::{Message}; use crate::network::server::Handle as ServerHandle; use std::sync::{Arc, Mutex}; use crate::crypto::hash::{H256, Hashable, H160}; use crate::blockchain::Blockchain; use crate::block::{Block,Header,Content}; use crate::crypto::merkle::{MerkleTree}; use crate::transaction::{Transa...
(&self) { self.control_chan.send(ControlSignal::Exit).unwrap(); } pub fn start(&self, lambda: u64) { self.control_chan .send(ControlSignal::Start(lambda)) .unwrap(); } } impl Context { pub fn start(mut self) { thread::Builder::new() .name("m...
exit
identifier_name
miner.rs
use crate::network::message::{Message}; use crate::network::server::Handle as ServerHandle; use std::sync::{Arc, Mutex}; use crate::crypto::hash::{H256, Hashable, H160}; use crate::blockchain::Blockchain; use crate::block::{Block,Header,Content}; use crate::crypto::merkle::{MerkleTree}; use crate::transaction::{Transa...
} } if let OperatingState::Run(i) = self.operating_state { if i != 0 { let interval = time::Duration::from_micros(i as u64); thread::sleep(interval); } } let interval = time::Duratio...
{ let mut contents = newBlock.Content.content.clone(); //let mut state = self.state.lock().unwrap(); let mut stateWitness = self.stateWitness.lock().unwrap(); let mut mempool = self.mempool.lock().unwrap(); ...
conditional_block
graphics.rs
use crate::mthelper::SharedRef; use bedrock as br; use br::{ CommandBuffer, CommandPool, Device, Instance, InstanceChild, PhysicalDevice, Queue, SubmissionBatch, }; use log::{debug, info, warn}; use std::ops::Deref; pub type InstanceObject = SharedRef<br::InstanceObject>; pub type DeviceObject = Shar...
#[cfg(feature = "debug")] { ib.add_extension("VK_EXT_debug_utils"); debug!("Debug reporting activated"); } let instance = SharedRef::new(ib.create()?); #[cfg(feature = "debug")] let _debug_instance = br::DebugUtilsMessengerCreateInfo::new(...
warn!("Validation Layer is not found!"); }
random_line_split
graphics.rs
use crate::mthelper::SharedRef; use bedrock as br; use br::{ CommandBuffer, CommandPool, Device, Instance, InstanceChild, PhysicalDevice, Queue, SubmissionBatch, }; use log::{debug, info, warn}; use std::ops::Deref; pub type InstanceObject = SharedRef<br::InstanceObject>; pub type DeviceObject = Shar...
( &mut self, batches: &[br::vk::VkSubmitInfo], fence: &mut (impl br::Fence + br::VkHandleMut), ) -> br::Result<()> { self.graphics_queue .q .get_mut() .submit_raw(batches, Some(fence)) } /// Submits any commands as transient com...
submit_buffered_commands_raw
identifier_name
graphics.rs
use crate::mthelper::SharedRef; use bedrock as br; use br::{ CommandBuffer, CommandPool, Device, Instance, InstanceChild, PhysicalDevice, Queue, SubmissionBatch, }; use log::{debug, info, warn}; use std::ops::Deref; pub type InstanceObject = SharedRef<br::InstanceObject>; pub type DeviceObject = Shar...
pub const fn visible_from_host(&self) -> bool { self.has_property_flags(br::MemoryPropertyFlags::HOST_VISIBLE) } pub const fn is_host_coherent(&self) -> bool { self.has_property_flags(br::MemoryPropertyFlags::HOST_COHERENT) } pub const fn is_host_cached(&self) -> bool {...
{ self.has_property_flags(br::MemoryPropertyFlags::DEVICE_LOCAL) }
identifier_body
graphics.rs
use crate::mthelper::SharedRef; use bedrock as br; use br::{ CommandBuffer, CommandPool, Device, Instance, InstanceChild, PhysicalDevice, Queue, SubmissionBatch, }; use log::{debug, info, warn}; use std::ops::Deref; pub type InstanceObject = SharedRef<br::InstanceObject>; pub type DeviceObject = Shar...
if self.visible_from_host() { flags.push("HOST VISIBLE"); } if self.is_host_cached() { flags.push("CACHED"); } if self.is_host_coherent() { flags.push("COHERENT"); } if (self.1.propertyFlags & br::vk::VK_MEMORY_PR...
{ flags.push("DEVICE LOCAL"); }
conditional_block
screen_block.rs
use euclid::*; use std::cmp; use std::iter::FusedIterator; use crate::geometry::*; /// Coordinates of chunks in the image. The scaling factor is potentially different for every chunk /// iterator. struct ChunkSpace; pub trait ScreenBlockExt { fn internal_points(&self) -> InternalPoints; fn spiral_chunks(&sel...
} /// Tests that pixel iterator is a well behaved exact length iterator #[proptest] fn spiral_iterator_exact_length(block: ScreenBlockWrapper, chunk_size_minus_one: u8) { let it = block.spiral_chunks(chunk_size_minus_one as u32 + 1); check_exact_length(it, it.len()); // Using first rep...
{ let mut prev_distance = 0; for subblock in it { let distance = cmp::max( abs_difference(first.min.x, subblock.min.x), abs_difference(first.min.y, subblock.min.y), ); assert!(distance >= prev_distance); ...
conditional_block
screen_block.rs
use euclid::*; use std::cmp; use std::iter::FusedIterator; use crate::geometry::*; /// Coordinates of chunks in the image. The scaling factor is potentially different for every chunk /// iterator. struct ChunkSpace; pub trait ScreenBlockExt { fn internal_points(&self) -> InternalPoints; fn spiral_chunks(&sel...
(block: ScreenBlockWrapper, chunk_size_minus_one: u8) { let mut it = block.spiral_chunks(chunk_size_minus_one as u32 + 1); if let Some(first) = it.next() { let mut prev_distance = 0; for subblock in it { let distance = cmp::max( abs_difference...
spiral_iterator_is_spiral
identifier_name
screen_block.rs
use euclid::*; use std::cmp; use std::iter::FusedIterator; use crate::geometry::*; /// Coordinates of chunks in the image. The scaling factor is potentially different for every chunk /// iterator. struct ChunkSpace; pub trait ScreenBlockExt { fn internal_points(&self) -> InternalPoints; fn spiral_chunks(&sel...
/// Tests that pixel iterator is a well behaved exact length iterator #[proptest] fn pixel_iterator_exact_length(block: ScreenBlockWrapper) { check_exact_length(block.internal_points(), safe_area(*block) as usize); } /// Tests that sub blocks of a spiral chunk iterator when iterated over ...
{ check_pixel_iterator_covers_block(block.internal_points(), *block); }
identifier_body
screen_block.rs
use euclid::*; use std::cmp; use std::iter::FusedIterator; use crate::geometry::*; /// Coordinates of chunks in the image. The scaling factor is potentially different for every chunk /// iterator. struct ChunkSpace; pub trait ScreenBlockExt { fn internal_points(&self) -> InternalPoints; fn spiral_chunks(&sel...
#[should_panic] fn zero_sized_chunks(block: ScreenBlockWrapper) { block.spiral_chunks(0); } }
random_line_split
importer.go
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package srcimporter implements importing directly // from source files rather than installed packages. package imports import ( "fmt" "github.com/JohnWall...
// context-controlled file system operations func (p *Importer) absPath(path string) (string, error) { // TODO(gri) This should be using p.ctxt.AbsPath which doesn't // exist but probably should. See also issue #14282. return filepath.Abs(path) } func (p *Importer) isAbsPath(path string) bool { if f := p.ctxt.I...
{ open := p.ctxt.OpenFile // possibly nil files := make([]*ast.File, len(filenames)) errors := make([]error, len(filenames)) var wg sync.WaitGroup wg.Add(len(filenames)) for i, filename := range filenames { go func(i int, filepath string) { defer wg.Done() file, cached := p.astPkgs.cachedFile(filepath) ...
identifier_body
importer.go
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package srcimporter implements importing directly // from source files rather than installed packages. package imports import ( "fmt" "github.com/JohnWall...
astPkgs *astPkgCache info *types.Info IncludeTests func(pkg string) bool mode parser.Mode } type astPkgCache struct { sync.RWMutex packages map[string]*ast.Package } func (c *astPkgCache) cachedFile(name string) (*ast.File, bool) { c.RLock() defer c.RUnlock() for _, pkg := range c.packag...
typPkgs map[string]*types.Package
random_line_split
importer.go
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package srcimporter implements importing directly // from source files rather than installed packages. package imports import ( "fmt" "github.com/JohnWall...
(path string) (string, error) { // TODO(gri) This should be using p.ctxt.AbsPath which doesn't // exist but probably should. See also issue #14282. return filepath.Abs(path) } func (p *Importer) isAbsPath(path string) bool { if f := p.ctxt.IsAbsPath; f != nil { return f(path) } return filepath.IsAbs(path) } f...
absPath
identifier_name
importer.go
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package srcimporter implements importing directly // from source files rather than installed packages. package imports import ( "fmt" "github.com/JohnWall...
p.typPkgs[bp.ImportPath] = pkg return pkg, nil } func (p *Importer) parseFiles(dir string, filenames []string, mode parser.Mode, parseFuncBodies parser.InFuncBodies) ([]*ast.File, error) { open := p.ctxt.OpenFile // possibly nil files := make([]*ast.File, len(filenames)) errors := make([]error, len(filenames))...
{ // this can only happen if we have a bug in go/types panic("package is not safe yet no error was returned") }
conditional_block
springbootapp_controller.go
/* 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, software distributed under the License...
(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&appv1.SpringBootApp{}). Complete(r) } func (r *SpringBootAppReconciler) createOrUpdateDeployment( ctx context.Context, springBootApp *appv1.SpringBootApp, labels map[string]string, ) error { // Define the desired Deployment object deplo...
SetupWithManager
identifier_name
springbootapp_controller.go
/* 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, software distributed under the License...
const ( DefaultFailureThreshold = 5 DefaultSuccessThreshold = 1 DefaultTimeoutSeconds = 5 ) func buildProbe(path string, delay, timeout int32) *corev1.Probe { return &corev1.Probe{ Handler: corev1.Handler{ HTTPGet: &corev1.HTTPGetAction{ Path: path, Port: intstr.IntOrString{IntVal: 8080}, ...
{ container := corev1.Container{ Name: springBootApp.Name, Image: fmt.Sprintf("%s:%s", springBootApp.Spec.ImageRepo, springBootApp.Spec.AppImage), Ports: springBootApp.Spec.Ports, Env: springBootApp.Spec.Env, } if len(springBootApp.Spec.LivenessProbePath) > 0 { container.LivenessProbe = buildProbe(spri...
identifier_body
springbootapp_controller.go
/* 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, software distributed under the License...
return affinity } func imagePullSecrets(imagePullSecrets string) []corev1.LocalObjectReference { if len(imagePullSecrets) == 0 { return nil } return []corev1.LocalObjectReference{ {Name: imagePullSecrets}, } }
{ affinity.PodAntiAffinity = podAntiAffinity }
conditional_block
springbootapp_controller.go
/* 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, software distributed under the License...
labels map[string]string, ) error { // Define the desired Deployment object deployment := &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf("%s-%s", springBootApp.Name, springBootApp.Spec.Version), Namespace: springBootApp.Namespace, }, Spec: appsv1.DeploymentSpec{ Selector: &m...
ctx context.Context, springBootApp *appv1.SpringBootApp,
random_line_split