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 |
|---|---|---|---|---|
payment.component.ts | , 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 '../alert.service';
import { LoaderService } from '../loader.service';
imp... |
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 | , target, fstype string, options []string) []string {
// Build mount command as follows:
// mount [-t $fstype] [-o $options] [$source] $target
mountArgs := []string{}
if len(fstype) > 0 {
mountArgs = append(mountArgs, "-t", fstype)
}
if len(options) > 0 {
mountArgs = append(mountArgs, "-o", strings.Join(opt... | 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 | , target, fstype string, options []string) []string {
// Build mount command as follows:
// mount [-t $fstype] [-o $options] [$source] $target
mountArgs := []string{}
if len(fstype) > 0 {
mountArgs = append(mountArgs, "-t", fstype)
}
if len(options) > 0 {
mountArgs = append(mountArgs, "-o", strings.Join(opt... | (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 | , target, fstype string, options []string) []string {
// Build mount command as follows:
// mount [-t $fstype] [-o $options] [$source] $target
mountArgs := []string{}
if len(fstype) > 0 {
mountArgs = append(mountArgs, "-t", fstype)
}
if len(options) > 0 |
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 | .Errorf("findmnt failed: %v\narguments: %s\nOutput: %v\n", err, mountArgs, string(output))
}
sources := strings.Fields(string(output))
return sources, nil
}
func IsFipsEnabled(mounter Interface) (string, error) {
command := exec.Command(CAT_COMMAND, FIPS_ENABLED_FILE_PATH)
output, err := command.CombinedOutput()... | {
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 | 0.1], 'prob of new_whale')
tf.app.flags.DEFINE_string(
'ref_images_set', None,
'reference set')
tf.app.flags.DEFINE_string(
'dut_images_set', None,
'images set for test')
tf.app.flags.DEFINE_bool(
'save_features', False,
'whether save features before compare, mainly for debugging')
FLAGS = tf.a... |
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 | 0.1], 'prob of new_whale')
tf.app.flags.DEFINE_string(
'ref_images_set', None,
'reference set')
tf.app.flags.DEFINE_string(
'dut_images_set', None,
'images set for test')
tf.app.flags.DEFINE_bool(
'save_features', False,
'whether save features before compare, mainly for debugging')
FLAGS = tf.a... | (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 | _variables:
flag = True
for es in ec_scopes:
if mv.op.name.startswith(es):
flag = False
break
if flag:
vars_to_restore.append(mv)
return vars_to_restore
def _cfg_from_file(filename):
"""Load a config file and merge it into the def... | 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 | 0.1], 'prob of new_whale')
tf.app.flags.DEFINE_string(
'ref_images_set', None,
'reference set')
tf.app.flags.DEFINE_string(
'dut_images_set', None,
'images set for test')
tf.app.flags.DEFINE_bool(
'save_features', False,
'whether save features before compare, mainly for debugging')
FLAGS = tf.a... |
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 | ::NoMipmap,
alloced_size,
alloced_size,
)?;
println!("Allocated {0:?}x{0:?} texture", alloced_size);
Ok(Self {
locations: Default::default(),
next_x: 0,
next_y: 0,
font,
facade,
char_dim,
... | {} | conditional_block | |
font_atlas.rs | contours: Vec<Contour>,
initial_bounds: Rect<f32>,
bounds: lyon_path::math::Rect,
) -> (Vec<Contour>, euclid::Transform2D<f32>) {
let initial_scale = initial_bounds.size.width.max(initial_bounds.size.height);
let bounds_scale = bounds.size.width.max(bounds.size.height);
let transformation =
... | }
(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 |
/// 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 | contours: Vec<Contour>,
initial_bounds: Rect<f32>,
bounds: lyon_path::math::Rect,
) -> (Vec<Contour>, euclid::Transform2D<f32>) {
let initial_scale = initial_bounds.size.width.max(initial_bounds.size.height);
let bounds_scale = bounds.size.width.max(bounds.size.height);
let transformation =
... | {
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 | pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
// FIXME: quoting!
self.args.push(arg.as_ref().to_owned());
self
}
pub fn args<I, S>(&mut self, args: I) -> &mut Command
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
for arg in args ... |
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 | (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 | }={:?} for child; FIXME: implement this!",
key.as_ref(),
val.as_ref()
);
self
}
fn set_pty(&mut self, input: OwnedHandle, output: OwnedHandle, con: HPCON) -> &mut Command {
self.input.replace(input);
self.output.replace(output);
self.hpc.replace(c... | {
unsafe { CloseHandle(self.handle) };
} | conditional_block | |
conpty.rs | pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
// FIXME: quoting!
self.args.push(arg.as_ref().to_owned());
self
}
pub fn args<I, S>(&mut self, args: I) -> &mut Command
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
for arg in ar... | &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 | .session, lfp, probe_id, self.result_path, do_RF)
self.RF = True
elif not self.RF or do_probe:
ProbeF.extract_probeinfo(self.session, lfp, probe_id, self.result_path, False)
# CSD plot for the probe
if (not self.CSD) and do_CSD:
... |
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 | 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 | select the conditions and pool their trials together
Result_pool = self.pool_data(preproc_params=preproc_params, stim_params= stim_params, ROI_list = ROI_list)
Y = Result_pool['Y']
Srate = Result_pool['Srate']
# pull together and ROI-layer index
srate = np.unique(np.array(list(... | """
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 | , lfp, probe_id, self.result_path, do_RF)
self.RF = True
elif not self.RF or do_probe:
ProbeF.extract_probeinfo(self.session, lfp, probe_id, self.result_path, False)
# CSD plot for the probe
if (not self.CSD) and do_CSD:
... | (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 | ().text_range().contains_range(cursor.text_range()) =>
{
tt
}
_ => return None,
};
let tokens: Vec<_> = cursor
.siblings_with_tokens(Direction::Prev)
.flat_map(SyntaxElement::into_token)
.take_while(|tok| tok.kind() != T!['('] && tok.kind() != T![,])
... | (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 | ().text_range().contains_range(cursor.text_range()) =>
{
tt
}
_ => return None,
};
let tokens: Vec<_> = cursor
.siblings_with_tokens(Direction::Prev)
.flat_map(SyntaxElement::into_token)
.take_while(|tok| tok.kind() != T!['('] && tok.kind() != T![,])
... | 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 | text_range().contains_range(cursor.text_range()) =>
{
tt
}
_ => return None,
};
let tokens: Vec<_> = cursor
.siblings_with_tokens(Direction::Prev)
.flat_map(SyntaxElement::into_token)
.take_while(|tok| tok.kind() != T!['('] && tok.kind() != T![,])
... |
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 |
// - int8: 1 byte
// - int16: 2 bytes - int16 as little endian uint16
// - int32: 4 bytes - int32 as little endian uint32
// - int64: 8 bytes - int64 as little endian uint64
//
// - uint family:
// - uint: 8 bytes - little endian uint64
// - uint8: 1 byte
// - uint16: 2 bytes - little end... |
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 | // - Real: 4 bytes as little endian uint32 from float32 bits
// - Complex: 4 bytes as little endian uint32 from float32 bits
//
// - complex128:
// - Real: 8 bytes as little endian uint64 from float64 bits
// - Complex: 8 bytes as little endian uint64 from float64 bits
package nanolog
import (
"buf... | {
if len(*f) == 0 {
logpanic("Missing '}' character at end of line", gold)
}
if next(f) != '}' {
logpanic("Missing '}' character", gold)
}
} | conditional_block | |
nanolog.go |
// - int8: 1 byte
// - int16: 2 bytes - int16 as little endian uint16
// - int32: 4 bytes - int32 as little endian uint32
// - int64: 8 bytes - int64 as little endian uint64
//
// - uint family:
// - uint: 8 bytes - little endian uint64
// - uint8: 1 byte
// - uint16: 2 bytes - little end... | (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 | // - int8: 1 byte
// - int16: 2 bytes - int16 as little endian uint16
// - int32: 4 bytes - int32 as little endian uint32
// - int64: 8 bytes - int64 as little endian uint64
//
// - uint family:
// - uint: 8 bytes - little endian uint64
// - uint8: 1 byte
// - uint16: 2 bytes - little endi... |
// 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 | /stderr.
func init() {
debug.Disable()
}
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 !=... |
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 | /stderr.
func init() |
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 | /stderr.
func init() {
debug.Disable()
}
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 !=... | (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 | err != nil {
return err
}
// flags must be the top-level command flags, not cmd.Flags()
opts.Common.SetDefaultOptions(flags)
preRun(opts)
if err := storageosCli.Initialize(opts); err != nil {
return err
}
return isSupported(cmd, storageosCli.Client().ClientVersion(), storageosCli.HasExper... | // if len(errs) > 0 {
// return errors.New(strings.Join(errs, "\n")) | random_line_split | |
pool.rs | Drop for JobHandle<'pool, 'f> {
fn drop(&mut self) {
self.wait();
self.pool.job_status = None;
}
}
impl Drop for Pool {
fn drop(&mut self) {
let (tx, rx) = mpsc::channel();
self.job_queue.send((None, tx)).unwrap();
rx.recv().unwrap().unwrap();
}
}
struct PanicCa... | // closed, done!
Ok(true) | Err(_) => break, | random_line_split | |
pool.rs | {
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 | the job panics, this handle will ensure the main thread also
/// panics (either via `wait` or in the destructor).
pub struct JobHandle<'pool, 'f> {
pool: &'pool mut Pool,
status: Arc<Mutex<JobStatus>>,
_funcs: marker::PhantomData<&'f ()>,
}
impl JobStatus {
fn wait(&mut self) {
if self.wait {
... | {
break
} | conditional_block | |
needless_pass_by_ref_mut.rs | _def_ids_to_maybe_unused_mut: FxIndexMap::default(),
}
}
}
impl_lint_pass!(NeedlessPassByRefMut<'_> => [NEEDLESS_PASS_BY_REF_MUT]);
fn should_skip<'tcx>(
cx: &LateContext<'tcx>,
input: rustc_hir::Ty<'tcx>,
ty: Ty<'_>,
arg: &rustc_hir::Param<'_>,
) -> bool {
// We check if this a `&mut`... | {
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 | should_skip<'tcx>(
cx: &LateContext<'tcx>,
input: rustc_hir::Ty<'tcx>,
ty: Ty<'_>,
arg: &rustc_hir::Param<'_>,
) -> bool {
// We check if this a `&mut`. `ref_mutability` returns `None` if it's not a reference.
if !matches!(ty.ref_mutability(), Some(Mutability::Mut)) {
return true;
}... | fake_read | identifier_name | |
needless_pass_by_ref_mut.rs | /// fn foo(y: &mut i32) -> i32 {
/// 12 + *y
/// }
/// ```
/// Use instead:
/// ```rust
/// fn foo(y: &i32) -> i32 {
/// 12 + *y
/// }
/// ```
#[clippy::version = "1.72.0"]
pub NEEDLESS_PASS_BY_REF_MUT,
suspicious,
"using a `&mut` argument when it's not mutat... |
}
}
}
}
#[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 | /// fn foo(y: &mut i32) -> i32 {
/// 12 + *y
/// }
/// ```
/// Use instead:
/// ```rust
/// fn foo(y: &i32) -> i32 {
/// 12 + *y
/// }
/// ```
#[clippy::version = "1.72.0"]
pub NEEDLESS_PASS_BY_REF_MUT,
suspicious,
"using a `&mut` argument when it's not mutat... | &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 | {
await writeLocaleCodesModule(
config.sourceLocale,
config.targetLocales,
transformConfig.localeCodesModule
);
}
// TODO(aomarks) It doesn't seem that it's possible for a TypeScript
// transformer to emit a new file, so we just have to emit for each locale.
// Need to do some more in... | 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 | () {
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 | await writeLocaleCodesModule(
config.sourceLocale,
config.targetLocales,
transformConfig.localeCodesModule
);
}
// TODO(aomarks) It doesn't seem that it's possible for a TypeScript
// transformer to emit a new file, so we just have to emit for each locale.
// Need to do some more inves... |
// 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 | ::BlindedRoute(blinded_route), reply_path);
/// ```
///
/// [offers]: <https://github.com/lightning/bolts/pull/798>
/// [`OnionMessenger`]: crate::onion_message::OnionMessenger
pub struct OnionMessenger<Signer: Sign, K: Deref, L: Deref>
where K::Target: KeysInterface<Signer = Signer>,
L::Target: Logger,
{
keys... | (&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 | 56k1::All>,
// Coming soon:
// invoice_handler: InvoiceHandler,
// custom_handler: CustomHandler, // handles custom onion messages
}
/// The destination of an onion message.
pub enum Destination {
/// We're sending this onion message to a node.
Node(PublicKey),
/// We're sending this onion message to a blinded r... | version: 0, | random_line_split | |
messenger.rs | ::BlindedRoute(blinded_route), reply_path);
/// ```
///
/// [offers]: <https://github.com/lightning/bolts/pull/798>
/// [`OnionMessenger`]: crate::onion_message::OnionMessenger
pub struct OnionMessenger<Signer: Sign, K: Deref, L: Deref>
where K::Target: KeysInterface<Signer = Signer>,
L::Target: Logger,
{
keys... |
}
/// 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 | <C>>)> {
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)))
}
}
#[derive(Debug, Clone, Se... | random_line_split | ||
joint_feldman.rs | "C::Scalar: DeserializeOwned")]
pub struct DKG<C: Curve> {
/// Metadata about the DKG
info: DKGInfo<C>,
}
impl<C: Curve> DKG<C> {
/// Creates a new DKG instance from the provided private key and group.
///
/// The private key must be part of the group, otherwise this will return an error.
pub ... |
// 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 | "C::Scalar: DeserializeOwned")]
pub struct DKG<C: Curve> {
/// Metadata about the DKG
info: DKGInfo<C>,
}
impl<C: Curve> DKG<C> {
/// Creates a new DKG instance from the provided private key and group.
///
/// The private key must be part of the group, otherwise this will return an error.
pub ... |
}
#[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 | = "C::Scalar: DeserializeOwned")]
pub struct DKG<C: Curve> {
/// Metadata about the DKG
info: DKGInfo<C>,
}
impl<C: Curve> DKG<C> {
/// Creates a new DKG instance from the provided private key and group.
///
/// The private key must be part of the group, otherwise this will return an error.
pu... | <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 | (always)]
fn flush_from_tlb(&self) {
unsafe {
asm!("invlpg [{}]", in(reg) self.virtual_address, options(preserves_flags, nostack));
}
}
/// Returns whether the given virtual address is a valid one in the x86-64 memory model.
///
/// Current x86-64 supports only 48-bit for virtual memory addresses.
/// Thi... | {
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 | B page boundary (physical_address = {:#X})",
physical_address
);
}
// Verify that the physical address does not exceed the CPU's physical address width.
assert!(
CheckedShr::checked_shr(
&physical_address,
processor::get_physical_address_bits() as u32
) == Some(0),
"Physical address excee... | {}
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 | PT).
default fn map_page<S: PageSize>(
&mut self,
page: Page<S>,
physical_address: usize,
flags: PageTableEntryFlags,
) -> bool {
self.map_page_in_this_table::<S>(page, physical_address, flags)
}
}
impl<L: PageTableLevelWithSubtables> PageTableMethods for PageTable<L>
where
L::SubtableLevel: PageTableLe... | {
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 | B page boundary (physical_address = {:#X})",
physical_address
);
}
// Verify that the physical address does not exceed the CPU's physical address width.
assert!(
CheckedShr::checked_shr(
&physical_address,
processor::get_physical_address_bits() as u32
) == Some(0),
"Physical address excee... |
/// 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 | is still a validator in this epoch
// and retrieve its new slots.
let new_epoch_slot_range = if Policy::epoch_at(reporting_block)
> Policy::epoch_at(fork_proof.header1.block_number)
{
self.current_validators()
.expect("We need to have validators")
... | finalize_previous_epoch | identifier_name | |
inherents.rs | self.finalize_previous_batch(macro_block));
// If this block is an election block, we also need to finalize the epoch.
if Policy::is_election_block_at(macro_block.block_number()) {
// On election the previous epoch needs to be finalized.
// We can rely on `state` here, since we... | 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 | .finalize_previous_batch(macro_block));
// If this block is an election block, we also need to finalize the epoch.
if Policy::is_election_block_at(macro_block.block_number()) {
// On election the previous epoch needs to be finalized.
// We can rely on `state` here, since we cann... | };
// Calculate the slots that will receive rewards.
// Rewards are for the previous batch (to give validators time to report misbehavior)
let penalized_set = staking_contract
.punished_slots
.previous_batch_punished_slots();
// Total reward for the prev... | {
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 | .finalize_previous_batch(macro_block));
// If this block is an election block, we also need to finalize the epoch.
if Policy::is_election_block_at(macro_block.block_number()) {
// On election the previous epoch needs to be finalized.
// We can rely on `state` here, since we cann... | 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 | ._parents = []
# Ancestors AST FunctionCall nodes
self.funccall_nodes = []
# Ancestors AST Variable nodes
self.var_nodes = []
# Is this var controlled by user?
self._controlled_by_user = None
# Vulns this variable is safe for.
self._safe_for = []
... | 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 | have received a copy of the GNU General Public License
along with w3af; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
'''
import itertools
import phply.phpast as phpast
from core.nodes.node_rep import NodeRep
from core.vulnerabilities.definitions import... | #self._controlled_by_user = cbusr
return cbusr
@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;
... | '''
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 | should have received a copy of the GNU General Public License
along with w3af; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
'''
import itertools
import phply.phpast as phpast
from core.nodes.node_rep import NodeRep
from core.vulnerabilities.definitions... | '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 | have received a copy of the GNU General Public License
along with w3af; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
'''
import itertools
import phply.phpast as phpast
from core.nodes.node_rep import NodeRep
from core.vulnerabilities.definitions import... | (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 | " viewBox="0 0 407.437 407.437" style="enable-background:new 0 0 407.437 407.437;" xml:space="preserve" width="512px" height="512px">' +
'<polygon points="386.258,91.567 203.718,273.512 21.179,91.567 0,112.815 203.718,315.87 407.437,112.815 "></polygon>' +
'</svg>' +
'</button>';
... | 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 | " viewBox="0 0 407.437 407.437" style="enable-background:new 0 0 407.437 407.437;" xml:space="preserve" width="512px" height="512px">' +
'<polygon points="386.258,91.567 203.718,273.512 21.179,91.567 0,112.815 203.718,315.87 407.437,112.815 "></polygon>' +
'</svg>' +
'</button>';
... | // 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 | onKeyValidation: function (result, opts) {
if (this.id === "phone" && $(this).inputmask("getmetadata")) {
console.log($(this).inputmask("getmetadata")["cd"]);
}
}
});
//------------------------------------------
//------------------------------------... | ayscale(0)'
});
}
});
//E-mail Ajax Send
$('.contact-form__ | conditional_block | |
index.js | " viewBox="0 0 407.437 407.437" style="enable-background:new 0 0 407.437 407.437;" xml:space="preserve" width="512px" height="512px">' +
'<polygon points="386.258,91.567 203.718,273.512 21.179,91.567 0,112.815 203.718,315.87 407.437,112.815 "></polygon>' +
'</svg>' +
'</button>';
... | = '',
text = '',
content = '',
time = '',
startTime = '',
endTime = '',
location = '',
address = '',
country = '',
city = '',
fullAddress = '',
phone = '',
meta = '... | var
title | identifier_name |
Housing.py | ())
# print(housing.describe())
#Look at Correlation Matrix Again with Median House Value as the Target Value
corr_matrix = housing.corr()
corr_matrix["median_house_value"].sort_values(ascending=False)
#The Result: "bedrooms_per_room" is more correlated than "total_room" or "total_bedrooms" with M... | #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 | (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 |
#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 |
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 | *output = NextPacketOutput{}
if len(read) < hdrlay.Size {
return false
}
wholePacketSize := hdrlay.Size + ReadPacketSize(read, hdrlay)
output.wholePacketSize = wholePacketSize
if len(read) < wholePacketSize {
return false
}
// advance stream
*stream = read[wholePacketSize:]
output.WholePacket = ... | 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 | *output = NextPacketOutput{}
if len(read) < hdrlay.Size {
return false
}
wholePacketSize := hdrlay.Size + ReadPacketSize(read, hdrlay)
output.wholePacketSize = wholePacketSize
if len(read) < wholePacketSize {
return false
}
// advance stream
*stream = read[wholePacketSize:]
output.WholePacket = ... | 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 | *output = NextPacketOutput{}
if len(read) < hdrlay.Size {
return false
}
wholePacketSize := hdrlay.Size + ReadPacketSize(read, hdrlay)
output.wholePacketSize = wholePacketSize
if len(read) < wholePacketSize {
return false
}
// advance stream
*stream = read[wholePacketSize:]
output.WholePacket = ... | (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 | *output = NextPacketOutput{}
if len(read) < hdrlay.Size {
return false
}
wholePacketSize := hdrlay.Size + ReadPacketSize(read, hdrlay)
output.wholePacketSize = wholePacketSize
if len(read) < wholePacketSize {
return false
}
// advance stream
*stream = read[wholePacketSize:]
output.WholePacket = ... |
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 | .default_value("server.saltyrtc.org")
.help("The SaltyRTC server hostname");
let arg_srv_port = Arg::with_name(ARG_SRV_PORT)
.short('p')
.takes_value(true)
.value_name("SRV_PORT")
.required(true)
.default_value("443")
.help("The SaltyRTC server port");... | ake_qrcode_data() {
| identifier_name | |
testclient.rs | with type erasure.
macro_rules! boxed {
($future:expr) => {{
Box::new($future) as BoxedFuture<_, _>
}}
}
/// Create the QR code payload
fn make_qrcode_payload(version: u16, permanent: bool, host: &str, port: u16, pubkey: &[u8], auth_token: &[u8], server_pubkey: &[u8]) -> Vec<u8> {
let mut data: Ve... | .required(true)
.default_value("f77fe623b6977d470ac8c7bf7011c4ad08a1d126896795db9d2b4b7a49ae1045")
.help("The SaltyRTC server public permanent key");
let arg_ping_interval = Arg::with_name(ARG_PING_INTERVAL)
.short('i')
.takes_value(true)
.value_name("SECONDS")
... |
// 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 | box with type erasure.
macro_rules! boxed {
($future:expr) => {{
Box::new($future) as BoxedFuture<_, _>
}}
}
/// Create the QR code payload
fn make_qrcode_payload(version: u16, permanent: bool, host: &str, port: u16, pubkey: &[u8], auth_token: &[u8], server_pubkey: &[u8]) -> Vec<u8> {
let mut data... | 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 | Err(err) => {
let _ = writeln!(io::stderr(), "{}", err);
1
}
});
}
fn cargo_expand_or_run_nightly() -> 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_NIGHTL... |
// 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 | Err(err) => {
let _ = writeln!(io::stderr(), "{}", err);
1
}
});
}
fn | () -> 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 | Err(err) => {
let _ = writeln!(io::stderr(), "{}", err);
1
}
});
}
fn cargo_expand_or_run_nightly() -> 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... | })
}
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 | Err(err) => {
let _ = writeln!(io::stderr(), "{}", err);
1
}
});
}
fn cargo_expand_or_run_nightly() -> 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_NIGHTL... |
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 | //stateSet: &Arc<Mutex<StateSet>>,
blockchain: &Arc<Mutex<Blockchain>>,
local_public_key: &[u8],
local_address: &H160,
ifArchival: bool,
) -> (Context, Handle) {
let (signal_chan_sender, signal_chan_receiver) = unbounded();
let ctx = Context {
local_address: *local_address,
loc... | thread::sleep(interval);
}
}
let interval = time::Duration::from_micros(1000 as u64); | random_line_split | |
miner.rs | };
use crossbeam::channel::{unbounded, Receiver, Sender, TryRecvError};
use std::{time, fs};
use std::time::{SystemTime, UNIX_EPOCH};
use std::thread;
use ring::signature::Ed25519KeyPair;
enum ControlSignal {
Start(u64), // the number controls the lambda of interval between block generation
Exit,
}
enum Ope... | (&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 crossbeam::channel::{unbounded, Receiver, Sender, TryRecvError};
use std::{time, fs};
use std::time::{SystemTime, UNIX_EPOCH};
use std::thread;
use ring::signature::Ed25519KeyPair;
enum ControlSignal {
Start(u64), // the number controls the lambda of interval between block generation
Exit,
}
enum Ope... | if check {
let mut blockchain = self.blockchain.lock().unwrap();
let tip_hash = blockchain.insert(&newBlock);
//info!("MINER: NEW BLOCK | {
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 | Self::NoSuitableGraphicsQueue => {
write!(f, "no suitable graphics queue found on device")
}
}
}
}
impl std::error::Error for GraphicsInitializationError {}
/// Graphics manager
pub struct Graphics {
pub(crate) adapter: br::PhysicalDeviceObject<Instance... | #[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 | Self::NoSuitableGraphicsQueue => {
write!(f, "no suitable graphics queue found on device")
}
}
}
}
impl std::error::Error for GraphicsInitializationError {}
/// Graphics manager
pub struct Graphics {
pub(crate) adapter: br::PhysicalDeviceObject<Instance... | (
&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 | Self::NoSuitableGraphicsQueue => {
write!(f, "no suitable graphics queue found on device")
}
}
}
}
impl std::error::Error for GraphicsInitializationError {}
/// Graphics manager
pub struct Graphics {
pub(crate) adapter: br::PhysicalDeviceObject<Instance... |
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 | }
}
}
}
impl std::error::Error for GraphicsInitializationError {}
/// Graphics manager
pub struct Graphics {
pub(crate) adapter: br::PhysicalDeviceObject<InstanceObject>,
pub(crate) device: DeviceObject,
pub(crate) graphics_queue: QueueSet<DeviceObject>,
cp_onetime_su... | {
flags.push("DEVICE LOCAL");
} | conditional_block | |
screen_block.rs | Point,
cursor: ScreenPoint,
}
impl InternalPoints {
// Construct an iterator over internal points that returns no points
fn empty() -> Self {
InternalPoints {
min_x: 1,
max: Point2D::zero(),
cursor: Point2D::zero(),
}
}
}
impl Iterator for Internal... | {
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 | -1);
let direction = Vector2D::new(dx, -1 - dx);
SpiralChunks {
block: *self,
chunk_scale,
size,
cursor,
direction,
segment: 2,
segment_remaining: 1,
remaining: size.area() as u32,
}
}
}
#[de... | spiral_iterator_is_spiral | identifier_name | |
screen_block.rs | roughly) spiral order, starting in the middle of the block.
/// Chunks are chunk_size * chunk_size large, except on the bottom and right side of the
/// block, where they may be clipped if chunk size doesn't evenly divide block size.
/// Chunk size must be larger than zero. May panic if chunk size is small ... |
/// Tests that pixel iterator is a well behaved exact length iterator
#[proptest]
fn pixel_iterator_exact_length(block | {
check_pixel_iterator_covers_block(block.internal_points(), *block);
} | identifier_body |
screen_block.rs | <usize>) {
let len = self.len();
(len, Some(len))
}
fn next(&mut self) -> Option<Self::Item> {
if self.cursor.y >= self.max.y {
return None;
}
let ret = self.cursor;
debug_assert!(self.cursor.x < self.max.x);
self.cursor.x += 1;
if s... | random_line_split | ||
importer.go | .Package
}
func (c *astPkgCache) cachedFile(name string) (*ast.File, bool) {
c.RLock()
defer c.RUnlock()
for _, pkg := range c.packages {
f, cached := pkg.Files[name]
if cached {
return f, cached
}
}
return nil, false
}
func (c *astPkgCache) cacheFile(name string, file *ast.File) {
c.Lock()
defer c.Un... | }
files[i], errors[i] = parser.ParseFile(p.fset, filepath, src, mode, parseFuncBodies)
src.Close() // ignore Close error - parsing may have succeeded which is all we need
} else {
// Special-case when ctxt doesn't provide a custom OpenFile and use the
// parser's file reading mechanism dire... | {
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 | 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 | .Package
}
func (c *astPkgCache) cachedFile(name string) (*ast.File, bool) {
c.RLock()
defer c.RUnlock()
for _, pkg := range c.packages {
f, cached := pkg.Files[name]
if cached {
return f, cached
}
}
return nil, false
}
func (c *astPkgCache) cacheFile(name string, file *ast.File) {
c.Lock()
defer c.Un... | (path string) (string, error) {
// TODO(gri) This should be using p | absPath | identifier_name |
importer.go |
}
func (c *astPkgCache) cachedFile(name string) (*ast.File, bool) {
c.RLock()
defer c.RUnlock()
for _, pkg := range c.packages {
f, cached := pkg.Files[name]
if cached {
return f, cached
}
}
return nil, false
}
func (c *astPkgCache) cacheFile(name string, file *ast.File) {
c.Lock()
defer c.Unlock()
... |
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 | +kubebuilder:rbac:groups=app.k8s.airparking.cn,resources=springbootapps/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps,resources=deployments/status,verbs=get
// +kubebuilder:rbac:groups="",resources=s... | (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 | App, labels)
if err != nil {
return ctrl.Result{}, err
}
err = r.createOrUpdaterService(ctx, springBootApp, labels)
if err != nil {
return ctrl.Result{}, err
}
err = r.createOrUpdateHPA(ctx, springBootApp, labels)
if err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
func (r *Spring... | {
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 | AntiAffinity)
if affinity != nil {
deployment.Spec.Template.Spec.Affinity = affinity
}
if err := controllerutil.SetControllerReference(springBootApp, deployment, r.Scheme); err != nil {
return err
}
// check if deployment is existed
foundedDep := &appsv1.Deployment{}
if err := r.Get(
ctx,
types.Namespa... | {
affinity.PodAntiAffinity = podAntiAffinity
} | conditional_block | |
springbootapp_controller.go | +kubebuilder:rbac:groups=app.k8s.airparking.cn,resources=springbootapps/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps,resources=deployments/status,verbs=get
// +kubebuilder:rbac:groups="",resources=s... | 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 |
flap.py | = 30
# tweak this to change how quickly the bird falls
GRAVITY = 1
# how big the gaps between the pipes are
GAP = 100
# how frequently the pipes spawn (sec)
FREQ = 2
# how fast the bird flies at the pipes
PIPE_SPEED = 3
# how powerful is a flap?
FLAP_SPEED = 15
# set up asset folders
game_dir = path.dirname(__file__)... |
def draw_ground():
# draw the ground tiles, moving at the same speed as pipes
for image in ground_list:
image.x -= PIPE_SPEED
if image.right <= 0:
# if the image has completely moved off the screen, move it to the right
image.left = 2 * ground.get_width() + image.right
... | background_rect.bottom = HEIGHT + 20
background_rect.left = 0
screen.blit(background, background_rect)
if background_rect.width < WIDTH:
background_rect.left = background_rect.width
screen.blit(background, background_rect) | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.