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 |
|---|---|---|---|---|
Z_normal_8_2.py | 1.15]),
9: np.array([ -1.22, -0.76, -0.43, -0.14, 0.14, 0.43, 0.76, 1.22]),
10: np.array([ -1.28, -0.84, -0.52, -0.25, 0, 0.25, 0.52, 0.84, 1.28]),
11: np.array([ -1.34, -0.91, -0.6, -0.35, -0.11, 0.11, 0.35, 0.6, 0.91, 1.34]),
12: np.array([ -1.38, -0.97, -0.67, -0.4... |
"""------------- Index to Letter conversion ------------- """
def index_to_letter(idx):
"""Convert a numerical index to a char."""
if 0 <= idx < 20:
return chr(97 + idx)
else:
raise ValueError('A wrong idx value supplied.')
def normalize(x):
X = n... | mean=np.mean(series)
#median=sorted(series)[len(series) // 2]
return mean | identifier_body |
Z_normal_8_2.py | 1.15]),
9: np.array([ -1.22, -0.76, -0.43, -0.14, 0.14, 0.43, 0.76, 1.22]),
10: np.array([ -1.28, -0.84, -0.52, -0.25, 0, 0.25, 0.52, 0.84, 1.28]),
11: np.array([ -1.34, -0.91, -0.6, -0.35, -0.11, 0.11, 0.35, 0.6, 0.91, 1.34]),
12: np.array([ -1.38, -0.97, -0.67, -0.4... | (size):
options=np.linspace(0, 1, size+1)[1:]
return options
#y_alphabets = break_points_quantiles(y_alphabet_size).tolist()
y_alphabets = break_points_gaussian(y_alphabet_size).tolist()
def hamming_distance1(string1, string2):
distance = 0
L = len(string1)
for i in range(L):
... | break_points_quantiles | identifier_name |
genstate.go | () *genState {
return &genState{
// Mark the name that is used for the binary type as a reserved name
// within the output structs.
definedGlobals: map[string]bool{
ygot.BinaryTypeName: true,
ygot.EmptyTypeName: true,
},
uniqueDirectoryNames: make(map[string]string),
uniqueEnumeratedTypedefN... | newGenState | identifier_name | |
genstate.go | var en *yangEnum
switch {
case t.IdentityBase != nil:
en = &yangEnum{
name: s.identityrefBaseTypeFromIdentity(t.IdentityBase, noUnderscores),
entry: &yang.Entry{
Name: e.Name,
Type: &yang.YangType{
Name: e.Type.Name,
Kind: yang.Yidentityref,
IdentityBase: t.I... |
}
case e.Type.Name == "identityref":
// This is an identityref - we do not want to generate code for an
// identityref but rather for the base identity. This means that we reduce
// duplication across different enum types. Re-map the "path" that is to
// be used to the new identityref name.
if e.Ty... | {
genEnums[en.name] = en
} | conditional_block |
genstate.go | }
case e.Type.Name == "identityref":
// This is an identityref - we do not want to generate code for an
// identityref but rather for the base identity. This means that we reduce
// duplication across different enum types. Re-map the "path" that is to
// be used to the new identityref name.
if e.Type.... | uniqueName := makeNameUnique(nbuf.String(), s.definedGlobals)
s.uniqueEnumeratedLeafNames[identifierPath] = uniqueName | random_line_split | |
genstate.go | e.IsList() || e.IsDir() || isRoot(e) {
// This should be mapped to a struct in the generated code since it has
// child elements in the YANG schema.
elem := &yangDirectory{
entry: e,
}
// Encode the name of the struct according to the language specified
// within the input arguments.
switch l... | {
return s.identityrefBaseTypeFromIdentity(idr.Type.IdentityBase, noUnderscores)
} | identifier_body | |
flappybird.js | Frame = parent.lastJumpFrame;
}
this.b.y += this.v;
if(this.b.y < 0) this.b.v = 0;
if(this.b.y - Const.BIRD_RADIUS >= Const.SCREEN_HEIGHT) this.valid = false;
this.g = parent.h + this.b.dis(parent.b);
this.h = nextCenter.dis(this.b) + (nextCenter.y - this.b.y)*(nextCenter.y - this.b.y)*0.01;
this... | if(this.isCOM) {
if(this.ops.length == 0 && this.lastFound) {
this.lastFound = this.AStar();
}
if(this.ops.length != 0) {
while(this.ops[0].frame < this.frame) this.ops.shift();
if(this.ops[0].frame == this.frame) {
this.ops.shift();
this.bird.jump();
}
}
}
this.fram... | random_line_split | |
flappybird.js |
if(this.bird.y >= Const.SCREEN_HEIGHT - this.bird.r) return true;
// at most 3*2 obstacles in the view
var passed = false;
for(var i=0;i<3*2;i++)
{
var obst = this.obsts[this.obstIndex + i];
if(obst.hit(this.bird)) {
console.log('obst ' + (this.obstIndex + i) + ' hitted the bird!');
retu... | {
this.start(false);
this.bird.jump();
} | conditional_block | |
raft.go | // configuration change (if any). Config changes are only allowed to
// be proposed if the leader's applied index is greater than this
// value.
// (Used in 3A conf change)
PendingConfIndex uint64
actualElectionTimeout int
//// only will be useful if self is a leader
//appendCount map[uint64]uint64
}
func (r... | pb.Message) {
r.Vote = 0
r.Lead = 0
r.Term = m.Term
r.State = StateFollower
}
func (r *Raft) handleVoting(m pb.Message) {
//DPrintf("current Term %d, current Index %d, message Term %d, message Index %d", r.Term, r.RaftLog.LastIndex(), m.LogTerm, m.Index)
// ensure the candidate has all committed logs
//if r.h... | dateFollowerState(m | identifier_name |
raft.go | r.Prs {
// skip self
if p == r.id {
continue
}
r.sendHeartbeat(p)
}
}
// the message will go over the network
func (r *Raft) sendMsg(m pb.Message) {
r.msgs = append(r.msgs, m)
}
// the message will NOT go over the network
func (r *Raft) sendMsgLocally(m pb.Message) {
r.Step(m)
}
func (r *Raft) grantVo... | // r.Prs[r.id].Next = r.RaftLog.LastIndex() + 1
//}
// convert array of objects to array of pointers
entriesToAppend := r.RaftLog.entries[nextLogIndex-1:] | random_line_split | |
raft.go | // configuration change (if any). Config changes are only allowed to
// be proposed if the leader's applied index is greater than this
// value.
// (Used in 3A conf change)
PendingConfIndex uint64
actualElectionTimeout int
//// only will be useful if self is a leader
//appendCount map[uint64]uint64
}
func (r... | lse {
if r.hasEarlierLogThanCandidate(m) && !r.hasMoreCommittedLogsThanCandidate(m){
r.grantVoting(m)
return
} else {
r.rejectVoting(m)
return
| r.rejectVoting(m)
return
} e | conditional_block |
raft.go | // configuration change (if any). Config changes are only allowed to
// be proposed if the leader's applied index is greater than this
// value.
// (Used in 3A conf change)
PendingConfIndex uint64
actualElectionTimeout int
//// only will be useful if self is a leader
//appendCount map[uint64]uint64
}
func (r... | func (r *Raft) handleBeat() {
r.broadcastMsgHeartbeat()
}
func (r *Raft) initializeProgressFirstTime() {
for _, p := range r.Prs {
p.Match = 0
p.Next = r.RaftLog.LastIndex() + 1
}
}
func (r *Raft) initializeProgressSecondTime() {
for i, p := range r.Prs {
if i != r.id {
p.Next++
}
}
}
func (r *Raft) ... | r.State = StateCandidate
r.Term++
r.Lead = 0
r.electionElapsed = 0
r.actualElectionTimeout = r.generateElectionTimeout()
r.votes = map[uint64]bool{}
}
| identifier_body |
SEODWARF_S2_TURB_fMask.py | required=True,
help="path to folder where results are stored",
metavar='<string>')
params = vars(parser.parse_args())
inFolder = params['inFolder']
outFolder = params['outFolder']
# recover list of bands to be processed
bandNum10m = [4,3,2,8]
bandNumAll = ['B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07... | help="path to folder containing S2 data (first folder, not IMG_DATA)",
metavar='<string>')
parser.add_argument("-outFolder", | random_line_split | |
SEODWARF_S2_TURB_fMask.py | , not IMG_DATA)",
metavar='<string>')
parser.add_argument("-outFolder",
required=True,
help="path to folder where results are stored",
metavar='<string>')
params = vars(parser.parse_args())
inFolder = params['inFolder']
outFolder = params['outFolder']
# recover list of bands to be processed
bandNu... |
DOS_red = outFolder2+'/TOC/' + imageName + '_B04_TOC.tif'
if not os.path.isfile(DOS_red): # if outFile does not already exist
pathMaskShp = 'C:/Users/ucfadko/Desktop/Coastline_EUROPE_UTMZ33N/Coastline_EUROPE_UTMZ33N.shp'
outLW_Mask = outFolder2 + '/LW_mask.tif'
# check if shapefile exists
if not os.path.isfile... | os.mkdir(outFolder2 + '/TOC') | conditional_block |
canvas.go | },
}
c.SetBounds(bounds)
var shader *glhf.Shader
mainthread.Call(func() {
var err error
shader, err = glhf.NewShader(
canvasVertexFormat,
canvasUniformFormat,
canvasVertexShader,
canvasFragmentShader,
)
if err != nil {
panic(errors.Wrap(err, "failed to create Canvas, there's a bug in the sh... |
type canvasTriangles struct {
*GLTriangles
dst *Canvas
}
func (ct *canvasTriangles) draw(tex *glhf.Texture, bounds pixel.Rect) {
ct.dst.gf.Dirty()
// save the current state vars to avoid race condition
cmp := ct.dst.cmp
mat := ct.dst.mat
col := ct.dst.col
smt := ct.dst.smooth
mainthread.CallNonBlock(func(... | {
c.sprite.DrawColorMask(t, matrix, mask)
} | identifier_body |
canvas.go | 1},
}
c.SetBounds(bounds)
var shader *glhf.Shader
mainthread.Call(func() {
var err error
shader, err = glhf.NewShader(
canvasVertexFormat,
canvasUniformFormat,
canvasVertexShader,
canvasFragmentShader,
)
if err != nil {
panic(errors.Wrap(err, "failed to create Canvas, there's a bug in the s... | func (c *Canvas) Color(at pixel.Vec) pixel.RGBA {
return c.gf.Color(at)
}
// Texture returns the underlying OpenGL Texture of this Canvas.
//
// Implements GLPicture interface.
func (c *Canvas) Texture() *glhf.Texture {
return c.gf.Texture()
}
// Frame returns the underlying OpenGL Frame of this Canvas.
func (c *Ca... | })
}
// Color returns the color of the pixel over the given position inside the Canvas. | random_line_split |
canvas.go | 1},
}
c.SetBounds(bounds)
var shader *glhf.Shader
mainthread.Call(func() {
var err error
shader, err = glhf.NewShader(
canvasVertexFormat,
canvasUniformFormat,
canvasVertexShader,
canvasFragmentShader,
)
if err != nil {
panic(errors.Wrap(err, "failed to create Canvas, there's a bug in the s... | (t pixel.Target, matrix pixel.Matrix, mask color.Color) {
c.sprite.DrawColorMask(t, matrix, mask)
}
type canvasTriangles struct {
*GLTriangles
dst *Canvas
}
func (ct *canvasTriangles) draw(tex *glhf.Texture, bounds pixel.Rect) {
ct.dst.gf.Dirty()
// save the current state vars to avoid race condition
cmp := ct... | DrawColorMask | identifier_name |
canvas.go | },
}
c.SetBounds(bounds)
var shader *glhf.Shader
mainthread.Call(func() {
var err error
shader, err = glhf.NewShader(
canvasVertexFormat,
canvasUniformFormat,
canvasVertexShader,
canvasFragmentShader,
)
if err != nil {
panic(errors.Wrap(err, "failed to create Canvas, there's a bug in the sh... |
}
// SetColorMask sets a color that every color in triangles or a picture will be multiplied by.
func (c *Canvas) SetColorMask(col color.Color) {
rgba := pixel.Alpha(1)
if col != nil {
rgba = pixel.ToRGBA(col)
}
c.col = mgl32.Vec4{
float32(rgba.R),
float32(rgba.G),
float32(rgba.B),
float32(rgba.A),
}
}... | {
c.mat[i] = float32(m[i])
} | conditional_block |
mod.rs | builder for a fletcher.
///
/// One can use it for specifying a fletcher algorithm, which can be used for checksumming.
///
/// Example:
/// ```
/// # use delsum_lib::fletcher::Fletcher;
/// let adler32 = Fletcher::<u32>::with_options()
/// .width(32)
/// .init(1)
/// .module(65521)
/// .check(0x091e01... |
/// The endian of the words of the input file
pub fn inendian(&mut self, e: Endian) -> &mut Self {
self.input_endian = Some(e);
self
}
/// The number of bits in a word of the input file
pub fn wordsize(&mut self, n: usize) -> &mut Self {
self.wordsize = Some(n);
self... | {
self.swap = Some(s);
self
} | identifier_body |
mod.rs | A builder for a fletcher.
///
/// One can use it for specifying a fletcher algorithm, which can be used for checksumming.
///
/// Example:
/// ```
/// # use delsum_lib::fletcher::Fletcher;
/// let adler32 = Fletcher::<u32>::with_options()
/// .width(32)
/// .init(1)
/// .module(65521)
/// .check(0x091e... | (&mut self, e: Endian) -> &mut Self {
self.input_endian = Some(e);
self
}
/// The number of bits in a word of the input file
pub fn wordsize(&mut self, n: usize) -> &mut Self {
self.wordsize = Some(n);
self
}
/// The endian of the checksum
pub fn outendian(&mut se... | inendian | identifier_name |
mod.rs | fmt::Formatter<'_>) -> std::fmt::Result {
match &self.name {
Some(n) => write!(f, "{}", n),
None => {
write!(
f,
"fletcher width={} module={:#x} init={:#x} addout={:#x} swap={}",
2 * self.hwidth,
... | }
} | random_line_split | |
mod.rs | builder for a fletcher.
///
/// One can use it for specifying a fletcher algorithm, which can be used for checksumming.
///
/// Example:
/// ```
/// # use delsum_lib::fletcher::Fletcher;
/// let adler32 = Fletcher::<u32>::with_options()
/// .width(32)
/// .init(1)
/// .module(65521)
/// .check(0x091e01... | ;
fletch.addout = fletch.to_compact((s, c));
match self.check {
Some(chk) => {
if fletch.digest(&b"123456789"[..]).unwrap() != chk {
println!("{:x?}", fletch.digest(&b"123456789"[..]).unwrap());
Err(CheckBuilderErr::CheckFail)
... | {
fletch.init = init;
} | conditional_block |
RF.py | (300000/1000 - 0.5 + 0.25)/0.25 = 1199
pop1 = dg_finger1; pop2 = dg_finger2; pop3 = dg_finger3; pop4 = dg_finger4; pop5 = dg_finger5
windows1 = []; windows2 = []; windows3 = []; windows4 = []; windows5 = []
while len(pop1) >= 500:
temp1 = pop1[0:500]; temp2 = pop2[0:500]; temp3 = pop3[0:500]
temp4 = pop4[0:5... | for chan in range(n_channels):
for feat in range(n_feats):
features_2d[idx, chan + feat*n_channels] = features[idx,chan,feat]
# scale
scl = MinMaxScaler()
features_2d = scl.fit_transform(pd.DataFrame(features_2d))
"""Final Preprocessing and Train Test Split """
X_train = features_2d[0:960]
Y... | features_2d = np.zeros((batch_ct, n_channels*n_feats))
for idx in range(batch_ct): | random_line_split |
RF.py | 300000/1000 - 0.5 + 0.25)/0.25 = 1199
pop1 = dg_finger1; pop2 = dg_finger2; pop3 = dg_finger3; pop4 = dg_finger4; pop5 = dg_finger5
windows1 = []; windows2 = []; windows3 = []; windows4 = []; windows5 = []
while len(pop1) >= 500:
temp1 = pop1[0:500]; temp2 = pop2[0:500]; temp3 = pop3[0:500]
temp4 = pop4[0:500... |
def variance(x):
return(np.std(x)**2)
feat_names = ['BP 8-12', 'BP 18-24', 'BP 75-115', 'BP 125-159', 'BP 160-180', 'Line Length', 'Area', 'Energy', 'DC Gain', 'Zero Crossings', 'Peak Voltage', 'Variance']
n_feats = 12
n_channels = 62
batch_size = 40
batch_ct = len(change1);
features = np.zeros((batch_ct, n_chann... | return(np.max(x)) | identifier_body |
RF.py | 300000/1000 - 0.5 + 0.25)/0.25 = 1199
pop1 = dg_finger1; pop2 = dg_finger2; pop3 = dg_finger3; pop4 = dg_finger4; pop5 = dg_finger5
windows1 = []; windows2 = []; windows3 = []; windows4 = []; windows5 = []
while len(pop1) >= 500:
temp1 = pop1[0:500]; temp2 = pop2[0:500]; temp3 = pop3[0:500]
temp4 = pop4[0:500... | (x):
return(sum(abs(np.diff(x))))
def area(x):
return(sum(abs(x)))
def energy(x):
return(sum(np.square(x)))
def dc_gain(x):
return(np.mean(x))
def zero_crossings(x):
return(sum(x > np.mean(x)))
def peak_volt(x):
return(np.max(x))
def variance(x):
return(np.std(x)**2)
feat_names = ['BP 8-12'... | line_length | identifier_name |
RF.py | 300000/1000 - 0.5 + 0.25)/0.25 = 1199
pop1 = dg_finger1; pop2 = dg_finger2; pop3 = dg_finger3; pop4 = dg_finger4; pop5 = dg_finger5
windows1 = []; windows2 = []; windows3 = []; windows4 = []; windows5 = []
while len(pop1) >= 500:
temp1 = pop1[0:500]; temp2 = pop2[0:500]; temp3 = pop3[0:500]
temp4 = pop4[0:500... |
channel_changes.append(temp)
# all channels have similar change over entire time scale
# filter the data
numerator, denominator = scipy.signal.butter(5,(2*200)/1000)
for i in range(62):
ecog_df[i] = scipy.signal.lfilter(numerator,denominator,ecog_df[i].tolist())
# get into arrays consistent with outputs
f... | temp += abs(channel[i+1] - channel[i]) | conditional_block |
cmake_templates.py | ${${files}})\n')
#for outputting an executable
TExecutable = Template("add_executable(${project} $${SOURCES} $${HEADERS})\n")
#for outputting a shared library
TSharedLib = Template("add_library(${project} SHARED $${SOURCES} $${HEADERS})\n")
#for outputting a static library
TStaticLib = Template("add_library(${projec... |
#-----Write Functions-----
#Puts innerbody into TIfGuard template with the given condition
#then returns the string
def WrapInGuard(condition, innerbody):
return TIfGuard.substitute(dict(condition=condition, innerbody=innerbody))
def WriteProjectSettings(f, section):
#defaults
if "UseFolders" not in section.data... | chars = "${}"
for i in range(0,len(chars)):
s=s.replace(chars[i],"")
return s | identifier_body |
cmake_templates.py | ${${files}})\n')
#for outputting an executable
TExecutable = Template("add_executable(${project} $${SOURCES} $${HEADERS})\n")
#for outputting a shared library
TSharedLib = Template("add_library(${project} SHARED $${SOURCES} $${HEADERS})\n")
#for outputting a static library
TStaticLib = Template("add_library(${projec... | (f, rootDir, sections):
#first write the one which is not platform specific
for s in sections:
dirs = s.data[":"]
output = ""
for d in dirs:
localDir = d if d.startswith("/") else "/"+d
sourceID = Strip(localDir.replace('/','_'))
#insert any environment variables
if ContainsEnvVariable(d):
... | WriteSourceDirectories | identifier_name |
cmake_templates.py | #template for exectuable output
TExecutableOutput = Template('set(EXECUTABLE_OUTPUT_PATH "${dir}")\n')
#template for exectuable output
TRuntimeOutput = Template('set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${dir}")\n')
#template for library output
TLibraryoutput = Template('set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${dir}")\nset(L... | f.write(TObjectLib.substitute(dict(project=name)))
f.write(TTargetLinkLibs.substitute(dict(name=name))) | conditional_block | |
cmake_templates.py | ${${files}})\n')
#for outputting an executable
TExecutable = Template("add_executable(${project} $${SOURCES} $${HEADERS})\n")
#for outputting a shared library
TSharedLib = Template("add_library(${project} SHARED $${SOURCES} $${HEADERS})\n")
#for outputting a static library
TStaticLib = Template("add_library(${projec... | else:
runtime = runtime if runtime.startswith('/') else "/"+runtime
runtime = rootDir + | runtime = InsertEnvVariable(runtime) | random_line_split |
__init__.py | (flag):
"""
Turn debugging on or off.
@param flag (boolean) True means output debugging, False means no.
"""
global debug
debug = flag
XLM.XLM_Object.debug = flag
XLM.xlm_library.debug = flag
XLM.ms_stack_transformer.debug = flag
XLM.stack_transformer.debug = flag
XLM.excel2... | set_debug | identifier_name | |
__init__.py | (cmd, shell=True, stderr=FNULL)
except Exception as e:
color_print.output('r', "ERROR: Running olevba on " + str(maldoc) + " failed. " + str(e))
return None
# Not handling encrypted Excel files.
if (b"FILEPASS record: file is password protected" in olevba_out):
color_print.output('y... | random_line_split | ||
__init__.py | # Not handling encrypted Excel files.
if (b"FILEPASS record: file is password protected" in olevba_out):
color_print.output('y', "WARNING: " + str(maldoc) + " is password protected. Not emulating.")
return None
# Pull out the chunks containing the XLM lines.
chunk_pat = b"in file: x... | """
Run olevba on the given file and extract the XLM macro code lines.
@param maldoc (str) The fully qualified name of the Excel file to
analyze.
@return (str) The XLM macro cells extracted from running olevba on the
given file. None will be returned on error.
"""
# Run olevba on the give... | identifier_body | |
__init__.py | ba on the
given file. None will be returned on error.
"""
# Run olevba on the given file.
olevba_out = None
FNULL = open(os.devnull, 'w')
try:
cmd = "timeout 30 olevba -c \"" + str(maldoc) + "\""
olevba_out = subprocess.check_output(cmd, shell=True, stderr=FNULL)
except Exce... |
cell_index = (row, col)
xlm_sheet.cells[cell_index] = xlm_cell
xlm_cell_indices.append(cell_index)
# Debug.
if debug:
print("=========== DONE MERGE ==============")
print(workbook)
# Done. Return the indices of the added XLM cells and the up... | print((row, col))
print(xlm_cell) | conditional_block |
rainstorm.rs | c_float;
pub fn frexpf(n: c_float, value: &mut c_int) -> c_float;
pub fn fmaxf(a: c_float, b: c_float) -> c_float;
pub fn fminf(a: c_float, b: c_float) -> c_float;
pub fn fmodf(a: c_float, b: c_float) -> c_float;
pub fn nextafterf(x: c_float, y: c_float) -> c_float;
pub ... | #[no_mangle]
pub unsafe extern "C" fn rainstorm_extramousesample(input_sample_frametime: libc::c_float, active: bool) {
if cheats::CHEAT_MANAGER.is_not_null() {
(*cheats::CHEAT_MANAGER).extramousesample(input_sample_frametime, active);
} else {
quit!("Cheat manager not found!\n");
};
}
#[no_mangle]
pub extern "... | }
| random_line_split |
rainstorm.rs | angle]
pub extern "C" fn rainstorm_getivengineclient() -> sdk::raw::IVEngineClientPtr {
unsafe { (*(cheats::CHEAT_MANAGER)).get_gamepointers().ivengineclient.get_ptr() }
}
pub struct GamePointers {
ivengineclient: sdk::IVEngineClient,
icliententitylist: sdk::IClientEntityList,
ibaseclientdll: sdk::IBaseClientDLL,
... | {
log!("Failed at line {} of {}!\n", line, file);
let _ = logging::log_fmt(fmt).ok(); // if we fail here, god help us
unsafe { libc::exit(42); }
} | identifier_body | |
rainstorm.rs | _float;
pub fn frexpf(n: c_float, value: &mut c_int) -> c_float;
pub fn fmaxf(a: c_float, b: c_float) -> c_float;
pub fn fminf(a: c_float, b: c_float) -> c_float;
pub fn fmodf(a: c_float, b: c_float) -> c_float;
pub fn nextafterf(x: c_float, y: c_float) -> c_float;
pub fn... | (c_arguments: *const libc::c_char) {
let arguments_str = unsafe { core::str::raw::c_str_to_static_slice(c_arguments) };
log!("Command callback: {}\n", arguments_str);
let mut parts_iter = arguments_str.split(' ');
let command = parts_iter.next().expect("No command type specified!");
let parts: collections::Vec<&... | rainstorm_command_cb | identifier_name |
rainstorm.rs | _float;
pub fn frexpf(n: c_float, value: &mut c_int) -> c_float;
pub fn fmaxf(a: c_float, b: c_float) -> c_float;
pub fn fminf(a: c_float, b: c_float) -> c_float;
pub fn fmodf(a: c_float, b: c_float) -> c_float;
pub fn nextafterf(x: c_float, y: c_float) -> c_float;
pub fn... | else {
quit!("Cheat manager not found!\n");
};
}
#[no_mangle]
pub unsafe extern "C" fn rainstorm_process_usercmd(cmd: &mut sdk::CUserCmd) {
if cheats::CHEAT_MANAGER.is_not_null() {
maybe_hook_inetchannel((*cheats::CHEAT_MANAGER).get_gamepointers());
(*cheats::CHEAT_MANAGER).process_usercmd(cmd);
} else {
q... | {
(*cheats::CHEAT_MANAGER).pre_createmove(sequence_number, input_sample_frametime, active);
} | conditional_block |
ImageMap-dbg.js | >Properties
* <ul>
* <li>{@link #getName name} : string</li></ul>
* </li>
* <li>Aggregations
* <ul>
* <li>{@link #getAreas areas} : sap.ui.commons.Area[]</li></ul>
* </li>
* <li>Associations
* <ul></ul>
* </li>
* <li>Events
* <ul>
* <li>{@link sap.ui.commons.ImageMap#event:press press} : fnListenerFunction... | * @public
*/
// Start of sap\ui\commons\ImageMap.js
jQuery.sap.require("sap.ui.core.delegate.ItemNavigation");
/**
* Adds areas to the Image Map. Each argument must be either a | * @type void | random_line_split |
ImageMap-dbg.js | param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Combination of image areas where at runtime these areas are starting points for hyperlinks or actions
* @extends sap.ui.core.Control
*
* @author ... | {
oArea = new sap.ui.commons.Area(oContent);
} | conditional_block | |
app-engine.js | ': '2950 Camozzi Rd',
'cityState': 'Revelstoke, BC',
'display_phone': '250 814 0087',
'url': 'www.revelstokemountainresort.com/',
'location': {
'coordinate': {
'latitude': 50.9583028,
'longitude': -118.1637752,
},
'display_address': ['2950 Camozzi Rd'],
... | yJax | identifier_name | |
app-engine.js | --- Display the error message + Beacon --- */
errorResponses.forEach(function(place) {
resultList.push(new placeCard(place));
});
/* --- clean up the view --- */
initMap(); // refresh and reconstruct map
OpenInfowindowForMarker(0); // open first infoWindow
forceTop(); // ensure... | { // check if two distances are close
OpenInfowindowForMarker(resultCard); // open Infowindow for placeCard being viewed in DOM
} | conditional_block | |
app-engine.js | img: data.snippet_image_url,
txt: data.snippet_text
};
this.stars = {
count: ko.observable(data.rating),
standard: ko.observable(data.rating_img_url),
large: ko.observable(data.rating_img_url_large),
small: ko.observable(data.rating_img_url_small)
};
this.... | {
/* --- Clean up the old lists --- */
resultList.removeAll(); // empty the resultList
clearAllMarkers(); // clears marker array
/* --- Display the error message + Beacon --- */
errorResponses.forEach(function(place) {
resultList.push(new placeCard(place));
});
/* --- clea... | identifier_body | |
app-engine.js | mzvonWnDvII96o0Zx8Z--i64lArA';
/* --- var to track data set --- */
var currentMarkers = [];
/* --- clear currentMarkers set --- */
function clearAllMarkers() {
currentMarkers = [];
}
/*
* ---------------------------------------------------------------
* build the map and place markers, listeners an... | up: 0
}; | random_line_split | |
aml.py |
def fullLink(child, parent):
linkNodes(child, parent)
linkNodes(parent.dual, child.dual)
def deleteNode(node, layers, layer, dlayer):
for parent in node.parents:
parent.removeChild(node)
parent.dual.removeParent(node)
for child in node.children:
child.removeParent(node)
... | linkDuals(phi, dphi)
fullLink(phi, c)
graph["atoms"].add(phi)
graph["atoms*"].add(dphi)
return
# Algorithm 3
def sparseCrossing(a, b, graph, count):
psiCount = 1
A = getConstrainedLower(a, graph["atoms"]).difference(... | c = Gamma.pop()
phi = Node(name="phi"+str(phiCount))
dphi = Node(name="[phi"+str(phiCount)+"]")
phiCount += 1 | random_line_split |
aml.py | def fullLink(child, parent):
linkNodes(child, parent)
linkNodes(parent.dual, child.dual)
def deleteNode(node, layers, layer, dlayer):
for parent in node.parents:
parent.removeChild(node)
parent.dual.removeParent(node)
for child in node.children:
child.removeParent(node)
... |
return layers
def getLower(node):
lowerset = set([node])
for child in node.children:
lowerset = lowerset.union(getLower(child))
return lowerset
def getConstrainedLower(node, layer):
return getLower(node).intersection(layer)
def getUpper(node):
upperset = set()
for par... | for parent in node.parents:
fullLink(child, parent) | conditional_block |
aml.py | (node, dual):
node.dual = dual
dual.dual = node
def fullLink(child, parent):
linkNodes(child, parent)
linkNodes(parent.dual, child.dual)
def deleteNode(node, layers, layer, dlayer):
for parent in node.parents:
parent.removeChild(node)
parent.dual.removeParent(node)
for child in... | linkDuals | identifier_name | |
aml.py | def fullLink(child, parent):
linkNodes(child, parent)
linkNodes(parent.dual, child.dual)
def deleteNode(node, layers, layer, dlayer):
for parent in node.parents:
parent.removeChild(node)
parent.dual.removeParent(node)
for child in node.children:
child.removeParent(node)
... |
def classify(dataList, labels, graph):
consts = {}
for const in graph["constants"]:
consts[const.name] = const.children
atoms = set()
for i in range(1, len(dataList)):
attr = labels[i] + "_" + dataList[i]
if attr in consts:
atoms = atoms.union(consts[attr])
... | with open(file, 'r') as data:
labels = list(map(lambda x: x.strip(), data.readline().split(",")))
records = []
for line in data:
records.append(list(map(lambda x: x.strip(),line.split(","))))
return labels, records | identifier_body |
table.go | .Rank), 4, " "),
pad.Right(coin.Name, 22, " "),
pad.Right(coin.Symbol, 6, " "),
pad.Left(humanize.Commaf(coin.PriceUsd), 12, " "),
pad.Left(humanize.Commaf(coin.MarketCapUsd), 17, " "),
pad.Left(humanize.Commaf(coin.Usd24hVolume), 15, " "),
pad.Left(fmt.Sprintf("%.2f%%", coin.PercentChange1h), 9, " ")... | s.helpwin.MovePrint(17, 1, "<p> to sort by price") | random_line_split | |
table.go | ymbol", 8, " "),
pad.Left("[p]rice", 10, " "),
pad.Left("[m]arket cap", 17, " "),
pad.Left("24H [v]olume", 15, " "),
pad.Left("[1]H%", 9, " "),
pad.Left("[2]4H%", 9, " "),
pad.Left("[7]D%", 9, " "),
pad.Left("[t]otal supply", 20, " "),
pad.Left("[a]vailable supply", 19, " "),
pad.Left("[l]ast updated"... | {
s.menuwinWidth = s.screenCols
s.menuwinHeight = s.screenRows - 1
s.menuWidth = s.screenCols
s.menuHeight = s.screenRows - 2
//if len(s.menuItems) == 0 {
items := make([]*gc.MenuItem, len(s.menuData))
var err error
for i, val := range s.menuData {
items[i], err = gc.NewItem(val, "")
if err != nil {
ret... | identifier_body | |
table.go | str == "106": // "j"
if s.currentItem < len(s.menuItems)-1 {
s.currentItem = s.currentItem + 1
s.menu.Current(s.menuItems[s.currentItem])
}
form.Driver(gc.REQ_NEXT_FIELD)
form.Driver(gc.REQ_END_LINE)
case ch == gc.KEY_UP, chstr == "107": // "k"
if s.currentItem > 0 {
s.currentItem = s.cur... | else {
s.sortBy = name
s.sortDesc = desc
}
s.setMenuData()
err := s.renderMenu()
if err != nil {
panic(err)
}
}
func (s *Service) setMenuData() {
slice.Sort(s.coins[:], func(i, j int) bool {
if s.sortDesc == true {
i, j = j, i
}
switch s.sortBy {
case "rank":
return s.coins[i].Rank < s.coins... | {
s.sortDesc = !s.sortDesc
} | conditional_block |
table.go | = append(s.coins, &coin)
}
return nil
}
func (s *Service) handleClick(idx int) {
slug := strings.ToLower(strings.Replace(s.coins[idx].Name, " ", "-", -1))
exec.Command("open", fmt.Sprintf("https://coinmarketcap.com/currencies/%s", slug)).Output()
}
func (s *Service) handleSort(name string, desc bool) {
if s.so... | renderHelpWindow | identifier_name | |
cli.rs | use std::path::Path;
use std::process;
use ansi_term::Colour::{Cyan, Green, White};
use hcore::crypto::SigKeyPair;
use hcore::env;
use analytics;
use command;
use config;
use error::Result;
pub fn start(cache_path: &Path, analytics_path: &Path) -> Result<()> {
let mut ... | else {
para(&format!("You might want to create an origin key later with: `hab \
origin key generate {}'",
&origin));
}
}
} else {
para("Okay, maybe another time.");
}
... | {
try!(create_origin(&origin, cache_path));
generated_origin = true;
} | conditional_block |
cli.rs | use std::path::Path;
use std::process;
use ansi_term::Colour::{Cyan, Green, White};
use hcore::crypto::SigKeyPair;
use hcore::env;
use analytics;
use command;
use config;
use error::Result;
pub fn start(cache_path: &Path, analytics_path: &Path) -> Result<()> {
let mut ... | (origin: &str, cache_path: &Path) -> bool {
match SigKeyPair::get_latest_pair_for(origin, cache_path) {
Ok(pair) => {
match pair.secret() {
Ok(_) => true,
_ => false,
}
}
_ => false,
}
}
... | is_origin_in_cache | identifier_name |
cli.rs | : &Path, analytics_path: &Path) -> Result<()> {
let mut generated_origin = false;
println!("");
title("Habitat CLI Setup");
para("Welcome to hab setup. Let's get started.");
heading("Set up a default origin");
para("Every package in Habitat belongs to an origin, which i... | let mut response = String::new(); | random_line_split | |
cli.rs | use std::path::Path;
use std::process;
use ansi_term::Colour::{Cyan, Green, White};
use hcore::crypto::SigKeyPair;
use hcore::env;
use analytics;
use command;
use config;
use error::Result;
pub fn start(cache_path: &Path, analytics_path: &Path) -> Result<()> {
let mut ... |
fn opt_in_analytics(analytics_path: &Path, generated_origin: bool) -> Result<()> {
let result = analytics::opt_in(analytics_path, generated_origin);
println!("");
result
}
fn opt_out_analytics(analytics_path: &Path) -> Result<()> {
let result = analytics::opt_out(analytics... | {
let default = match analytics::is_opted_in(analytics_path) {
Some(val) => Some(val),
None => Some(true),
};
prompt_yes_no("Enable analytics?", default)
} | identifier_body |
main.go | TERM, syscall.SIGSTOP, syscall.SIGINT:
shutdownServer()
case syscall.SIGHUP:
// TODO reload
default:
return
}
}
}
func initConfig(configFile, entrypoint, starthash string) error {
conf, err := globalconf.NewWithOptions(&globalconf.Options{
Filename: configFile,
})
if err != nil {
return err
}
... |
if sh, err := hex.DecodeString(starthash); err != nil {
return err
} else if len(sh) != Config.HashBits/8 {
return fmt.Errorf("error starthash hex string length %d, should be %d",
len(starthash), Config.HashBits/8*2)
} else {
Config.StartHash = sh[:]
}
return nil
}
func initLog(logFile, serfLogFile, lo... | {
starthash = "0" + starthash
} | conditional_block |
main.go | {
conf, err := globalconf.NewWithOptions(&globalconf.Options{
Filename: configFile,
})
if err != nil {
return err
}
basicFlagSet := flag.NewFlagSet("basic", flag.PanicOnError)
basicFlagSet.String("bind_ip", "127.0.0.1", "server bind ip")
basicFlagSet.String("workdir", ".", "server working dir")
basicFlagS... | {
log.Info("Datanode stop...")
unRegisterDN(Config, ChordNode, EtcdCliPool)
os.Exit(0)
} | identifier_body | |
main.go | TERM, syscall.SIGSTOP, syscall.SIGINT:
shutdownServer()
case syscall.SIGHUP:
// TODO reload
default:
return
}
}
}
func initConfig(configFile, entrypoint, starthash string) error {
conf, err := globalconf.NewWithOptions(&globalconf.Options{
Filename: configFile,
})
if err != nil {
return err
}
... | (logFile, serfLogFile, logLevel string) error {
var format = logging.MustStringFormatter(
"%{time:2006-01-02 15:04:05.000} [%{level:.4s}] %{id:03x} [%{shortfunc}] %{message}",
)
f, err := os.OpenFile(logFile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
if err != nil {
return err
}
backend1 := logging.NewLogBac... | initLog | identifier_name |
main.go | TERM, syscall.SIGSTOP, syscall.SIGINT:
shutdownServer()
case syscall.SIGHUP:
// TODO reload
default:
return
}
}
}
func initConfig(configFile, entrypoint, starthash string) error {
conf, err := globalconf.NewWithOptions(&globalconf.Options{
Filename: configFile,
})
if err != nil {
return err
}
... | Config.RedisMaxIdle, err =
strconv.Atoi(redisFlagSet.Lookup("max_idle").Value.String())
Config.RedisMaxActive, err =
strconv.Atoi(redisFlagSet.Lookup("max_active").Value.String())
Config.RedisIdleTimeout, err =
strconv.Atoi(redisFlagSet.Lookup("timeout").Value.String())
Config.Entrypoint = entrypoint
if len... |
Config.MetaRedisAddr = redisFlagSet.Lookup("meta_redis_addr").Value.String()
attrAddrs := redisFlagSet.Lookup("attr_redis_addr").Value.String()
Config.AttrRedisAddrs = strings.Split(attrAddrs, ";") | random_line_split |
hypsometry_plots.py | # sum areas
elev_range_area_sum = elev_range_area.sum()
return elev_range_area_sum
# function from pybob
def bin_data(bins, data2bin, bindata, mode='mean', nbinned=False):
| if nbinned:
numbinned = np.zeros(len(bins))
if mode == 'mean':
for i, _ in enumerate(bins):
binned[i] = np.nanmean(data2bin[np.logical_and(np.isfinite(bindata), digitized == i+1)])
if nbinned:
numbinned[i] = np.count_nonzero(np.logical_and(np.isfinite(d... | """
Place data into bins based on a secondary dataset, and calculate statistics on them.
:param bins: array-like structure indicating the bins into which data should be placed.
:param data2bin: data that should be binned.
:param bindata: secondary dataset that decides how data2bin should be binned. Shou... | identifier_body |
hypsometry_plots.py | GI60-05.02087', 'RGI60-05.02297', 'RGI60-05.02280_1', 'RGI60-05.02309', 'RGI60-05.02328_1', 'RGI60-05.02108', 'RGI60-05.02303', 'RGI60-05.01920', 'RGI60-05.01987_1', 'RGI60-05.02213', 'RGI60-05.02126'] # observed and probable surge
# exclude and select certain glaciers
#gdf = excludeByID(excludelist, gdf, 'RGIId')
# ... | axes[1].legend(loc=1) | random_line_split | |
hypsometry_plots.py | bindata, mode='mean', nbinned=False):
"""
Place data into bins based on a secondary dataset, and calculate statistics on them.
:param bins: array-like structure indicating the bins into which data should be placed.
:param data2bin: data that should be binned.
:param bindata: secondary dataset that ... | tifflist.append(t) | conditional_block | |
hypsometry_plots.py | (outline, elevation_bin):
"""
Function to calculate area in an elevation bin
Parameters
----------
outline : Polygon
Polygon containing outlines.
elevation_bin : Polygon
Polygon containing elevation ranges
contour_range : String
Elevation range to be selected
Re... | areaDiff | identifier_name | |
keras_spark_rossmann_estimator.py |
# %% [markdown]
# ## Downloading the Data
#
# We define a task to download the data into a `FlyteDirectory`.
# %%
@task(
cache=True,
cache_version="0.1",
)
def download_data(dataset: str) -> FlyteDirectory:
# create a directory named 'data'
print("==============")
print("Downloading data")
pr... | batch_size: int = 100
sample_rate: float = 0.01
learning_rate: float = 0.0001
num_proc: int = 2
epochs: int = 100
local_checkpoint_file: str = "checkpoint.h5"
local_submission_csv: str = "submission.csv" | identifier_body | |
keras_spark_rossmann_estimator.py | an embedding layer in our Keras model.
# %%
def build_vocabulary(df: pyspark.sql.DataFrame) -> Dict[str, List[Any]]:
vocab = {}
for col in CATEGORICAL_COLS:
values = [r[0] for r in df.select(col).distinct().collect()]
col_type = type([x for x in values if x is not None][0])
default_valu... | inputs = {col: Input(shape=(1,), name=col) for col in all_cols}
embeddings = [
Embedding(len(vocab[col]), 10, input_length=1, name="emb_" + col)(inputs[col]) for col in CATEGORICAL_COLS
] | random_line_split | |
keras_spark_rossmann_estimator.py | google_trend_all = google_trend_all.withColumn(
"State",
F.when(google_trend_all.State == "NI", "HB,NI").otherwise(google_trend_all.State),
)
# expand dates
return expand_date(google_trend_all)
# %% [markdown]
# 2. Next, we set a few date-specific values in the DataFrame to analyze the s... |
return df
# %% [markdown]
# The `data_preparation` function consolidates all the aforementioned data processing functions.
# %%
def data_preparation(
data_dir: FlyteDirectory, hp: Hyperparameters
) -> Tuple[float, Dict[str, List[Any]], pyspark.sql.DataFrame, pyspark.sql.DataFrame]:
print("===============... | df = df.withColumn(col, lookup(mapping)(df[col])) | conditional_block |
keras_spark_rossmann_estimator.py | google_trend_all = google_trend_all.withColumn(
"State",
F.when(google_trend_all.State == "NI", "HB,NI").otherwise(google_trend_all.State),
)
# expand dates
return expand_date(google_trend_all)
# %% [markdown]
# 2. Next, we set a few date-specific values in the DataFrame to analyze the s... | (rows):
last_store, last_date = None, None
for r in rows:
if last_store != r.Store:
last_store = r.Store
last_date = r.Date
if r[col]:
last_date = r.Date
fields = r.asDict().copy()
... | fn | identifier_name |
container.go | ()
}
// Stop stops a container.
//
func (c *Container) Stop(kill bool) error {
ctx := context.Background()
task, err := c.container.Task(ctx, cio.Load)
if err != nil {
return fmt.Errorf("task lookup: %w", err)
}
behaviour := KillGracefully
if kill {
behaviour = KillUngracefully
}
err = c.killer.Kill(ctx... |
return nil
}
// RemoveProperty - Not Implemented
func (c *Container) RemoveProperty(name string) (err error) {
err = ErrNotImplemented
return
}
// Info - Not Implemented
func (c *Container) Info() (info garden.ContainerInfo, err error) {
err = ErrNotImplemented
return
}
// Metrics - Not Implemented
func (c *C... | {
return fmt.Errorf("set label: %w", err)
} | conditional_block |
container.go | ()
}
// Stop stops a container.
//
func (c *Container) Stop(kill bool) error {
ctx := context.Background()
task, err := c.container.Task(ctx, cio.Load)
if err != nil {
return fmt.Errorf("task lookup: %w", err)
}
behaviour := KillGracefully
if kill {
behaviour = KillUngracefully
}
err = c.killer.Kill(ctx... |
proc, err := task.LoadProcess(ctx, pid, cio.NewAttach(cioOpts...))
if err != nil {
return nil, fmt.Errorf("load proc: %w", err)
}
status, err := proc.Status(ctx)
if err != nil {
return nil, fmt.Errorf("proc status: %w", err)
}
if status.Status != containerd.Running {
return nil, fmt.Errorf("proc not run... | return nil, fmt.Errorf("task: %w", err)
}
cioOpts := containerdCIO(processIO, false) | random_line_split |
container.go | ()
}
// Stop stops a container.
//
func (c *Container) Stop(kill bool) error {
ctx := context.Background()
task, err := c.container.Task(ctx, cio.Load)
if err != nil {
return fmt.Errorf("task lookup: %w", err)
}
behaviour := KillGracefully
if kill {
behaviour = KillUngracefully
}
err = c.killer.Kill(ctx... |
// Metrics - Not Implemented
func (c *Container) Metrics() (metrics garden.Metrics, err error) {
err = ErrNotImplemented
return
}
// StreamIn - Not Implemented
func (c *Container) StreamIn(spec garden.StreamInSpec) (err error) {
err = ErrNotImplemented
return
}
// StreamOut - Not Implemented
func (c *Container)... | {
err = ErrNotImplemented
return
} | identifier_body |
container.go | ()
}
// Stop stops a container.
//
func (c *Container) Stop(kill bool) error {
ctx := context.Background()
task, err := c.container.Task(ctx, cio.Load)
if err != nil {
return fmt.Errorf("task lookup: %w", err)
}
behaviour := KillGracefully
if kill {
behaviour = KillUngracefully
}
err = c.killer.Kill(ctx... | (name string) (string, error) {
properties, err := c.Properties()
if err != nil {
return "", err
}
v, found := properties[name]
if !found {
return "", ErrNotFound(name)
}
return v, nil
}
// Set a named property on a container to a specified value.
//
func (c *Container) SetProperty(name string, value stri... | Property | identifier_name |
k8s.go | }
if opts.K8SNamespace == "" {
opts.K8SNamespace = apiv1.NamespaceDefault
}
cloud := &K8SCloud{
name: opts.Name,
host: opts.Host,
bearerToken: opts.K8SBearerToken,
namespace: opts.K8SNamespace,
insecure: opts.Insecure,
}
config := &rest.Config{
Host: opts.Host,
BearerToke... | () (*Resource, error) {
quotas, err := cloud.client.CoreV1().ResourceQuotas(cloud.namespace).List(meta_v1.ListOptions{})
if err != nil {
return nil, err
}
resource := &Resource{
Limit: ZeroQuota.DeepCopy(),
Used: ZeroQuota.DeepCopy(),
}
if len(quotas.Items) == 0 {
// TODO get quota from metrics
retur... | Resource | identifier_name |
k8s.go | if opts.K8SNamespace == "" {
opts.K8SNamespace = apiv1.NamespaceDefault
}
cloud := &K8SCloud{
name: opts.Name,
host: opts.Host,
bearerToken: opts.K8SBearerToken,
namespace: opts.K8SNamespace,
insecure: opts.Insecure,
}
config := &rest.Config{
Host: opts.Host,
BearerToken:... |
return resource, nil
}
// CanProvision returns true if the cloud can provision a worker meetting the quota
func (cloud *K8SCloud) CanProvision(quota Quota) (bool, error) {
resource, err := cloud.Resource()
if err != nil {
return false, err
}
if resource.Limit.IsZero() {
return true, nil
}
if resource.Lim... | {
resource.Used[string(k)] = NewQuantityFor(v)
} | conditional_block |
k8s.go |
}
// CanProvision returns true if the cloud can provision a worker meetting the quota
func (cloud *K8SCloud) CanProvision(quota Quota) (bool, error) {
resource, err := cloud.Resource()
if err != nil {
return false, err
}
if resource.Limit.IsZero() {
return true, nil
}
if resource.Limit.Enough(resource.Used... | {
env := []apiv1.EnvVar{
{
Name: WorkerEventID,
Value: id,
},
{
Name: CycloneServer,
Value: opts.WorkerEnvs.CycloneServer,
},
{
Name: ConsoleWebEndpoint,
Value: opts.WorkerEnvs.ConsoleWebEndpoint,
},
{
Name: RegistryLocation,
Value: opts.WorkerEnvs.RegistryLocation,
},
{ | identifier_body | |
k8s.go | }
if opts.K8SNamespace == "" {
opts.K8SNamespace = apiv1.NamespaceDefault
}
cloud := &K8SCloud{
name: opts.Name,
host: opts.Host,
bearerToken: opts.K8SBearerToken,
namespace: opts.K8SNamespace,
insecure: opts.Insecure,
}
config := &rest.Config{
Host: opts.Host,
BearerToke... | return cloud.name
}
// Kind returns cloud type.
func (cloud *K8SCloud) Kind() string {
return KindK8SCloud
}
// Ping returns nil if cloud is accessible
func (cloud *K8SCloud) Ping() error {
_, err := cloud.client.CoreV1().Pods(cloud.namespace).List(meta_v1.ListOptions{})
return err
}
// Resource returns the limi... | func (cloud *K8SCloud) Name() string { | random_line_split |
solve_kami.go | ]bool
}
func newTileSet(id, color int) *TileSet {
return &TileSet{
id: id,
color: color,
tiles: make(map[Tile]bool),
}
}
func (ts *TileSet) add(t Tile) { ts.tiles[t] = true }
func (ts *TileSet) remove(t Tile) { delete(ts.tiles, t) }
func (ts *TileSet) pop() Tile {
var t Tile
for t = range ts.tiles {
... |
// Wait for a solution
for i := 0; i < numWorkers; i++ { | random_line_split | |
solve_kami.go | func extractSwatches(src *image.RGBA, numColors int) []colorful.Color {
const (
W = 400
H = 75
)
var swatches []colorful.Color
b := src.Bounds()
sw := W / numColors
for i := 0; i < numColors; i++ {
m := src.SubImage(trimRect(image.Rect(b.Min.X+i*sw, b.Max.Y-H, b.Min.X+(i+1)*sw, b.Max.Y), 10))
swatches = a... |
}
return regions
}
type Region struct {
id, color int
tile Tile
neighbors intSet
}
func (r *Region) Copy() *Region {
r1 := *r
r1.neighbors = r.neighbors.Copy()
return &r1
}
type Board struct {
regions map[int]*Region
}
func newBoard(grid [][]int) *Board { return &Board{regions: findRegions(grid)} }
... | {
if adjacent(ts1, ts2) {
r2 := regions[ts2.id]
r1.neighbors.add(r2.id)
r2.neighbors.add(r1.id)
}
} | conditional_block |
solve_kami.go | bestIndex = d, s, i
}
}
return fromColorful(best), bestIndex
}
const outputPrefix = "/tmp/kami_" // see savePNG
// Encodes the image as PNG with the filename outputPrefix+name+".png".
func savePNG(name string, img image.Image) {
filename := outputPrefix + name + ".png"
fp, err := os.Create(filename)
if err !=... | {
a := make([]int, len(s))
copy(a, s)
return a
} | identifier_body | |
solve_kami.go | func extractSwatches(src *image.RGBA, numColors int) []colorful.Color {
const (
W = 400
H = 75
)
var swatches []colorful.Color
b := src.Bounds()
sw := W / numColors
for i := 0; i < numColors; i++ {
m := src.SubImage(trimRect(image.Rect(b.Min.X+i*sw, b.Max.Y-H, b.Min.X+(i+1)*sw, b.Max.Y), 10))
swatches = a... | (name string, img image.Image) {
filename := outputPrefix + name + ".png"
fp, err := os.Create(filename)
if err != nil {
log.Fatal(err)
}
err = png.Encode(fp, img)
if err != nil {
log.Fatal(err)
}
}
// Decodes the specified file as a PNG image.
func loadPNG(filename string) image.Image {
fp, err := os.Open... | savePNG | identifier_name |
sexprs.go | receiver and argument are
// identical.
Equal(b Sexp) bool
}
type List []Sexp
type Atom struct {
DisplayHint []byte
Value []byte
}
func (a Atom) Pack() []byte {
buf := bytes.NewBuffer(nil)
a.pack(buf)
return buf.Bytes()
}
func (a Atom) pack(buf *bytes.Buffer) {
if a.DisplayHint != nil && len(a.Displa... |
buf.WriteString(")")
}
func (a List) Equal(b Sexp) bool {
switch b := b.(type) {
case List:
if len(a) != len(b) {
return false
} else {
for i := range a {
if !a[i].Equal(b[i]) {
return false
}
}
return true
}
default:
return false
}
return false
}
func (l List) PackedLen() (siz... | {
datum.string(buf)
if i < len(l)-1 {
buf.WriteString(" ")
}
} | conditional_block |
sexprs.go | .WriteString("\"")
return
}
default:
encoding = base64Enc
break
}
}
switch encoding {
case base64Enc:
buf.WriteString("|" + base64Encoding.EncodeToString(acc) + "|")
case tokenEnc:
buf.Write(acc)
default:
panic("Encoding is neither base64 nor token")
}
}
func (a Atom) string(buf *bytes.Bu... | random_line_split | ||
sexprs.go | }
return false
}
func (l List) Pack() []byte {
buf := bytes.NewBuffer(nil)
l.pack(buf)
return buf.Bytes()
}
func (l List) pack(buf *bytes.Buffer) {
buf.WriteString("(")
for _, datum := range l {
datum.pack(buf)
}
buf.WriteString(")")
}
func (l List) Base64String() string {
return "{" + base64Encoding.Enc... | readQuotedString | identifier_name | |
sexprs.go | receiver and argument are
// identical.
Equal(b Sexp) bool
}
type List []Sexp
type Atom struct {
DisplayHint []byte
Value []byte
}
func (a Atom) Pack() []byte {
buf := bytes.NewBuffer(nil)
a.pack(buf)
return buf.Bytes()
}
func (a Atom) pack(buf *bytes.Buffer) {
if a.DisplayHint != nil && len(a.Displa... |
const (
tokenEnc = iota
quotedEnc
base64Enc
)
// write a string in a legible encoding to buf
func writeString(buf *bytes.Buffer, a []byte) {
// test to see what sort of encoding is best to use
encoding := tokenEnc
acc := make([]byte, len(a), len(a))
for i, c := range a {
acc[i] = c
switch {
case bytes.I... | {
buf := bytes.NewBuffer(nil)
a.string(buf)
return buf.String()
} | identifier_body |
dpfile.go | () {} // turn XML into diffs until you run out
dpw.Close() // write end marker and any etc., flush output
dpr := dpfile.NewReader(in, workingDir, streaming) // streaming=true readinf from stdin
for dpr.ReadSegment {} // turn diffs into XML as long as you can
dpr.Close() // wrap up
The writer implementation does some ... |
var safeFilenamePat *regexp.Regexp
const safeFilenameStr = "^[-a-zA-Z0-9_.]*$"
func panicOnUnsafeName(filename string) string {
if safeFilenamePat == nil {
safeFilenamePat = regexp.MustCompile(safeFilenameStr)
}
if !safeFilenamePat.MatchString(filename) {
panic(fmt.Sprint("unsafe filename: ", filename))
}
... | {
line, err := in.ReadString('\n')
if err != nil {
if err == io.EOF {
panic("Premature EOF reading line")
} else {
panic(err)
}
}
if len(line) > 0 {
return line[:len(line)-1] // chop off \n
}
return line
} | identifier_body |
dpfile.go | () {} // turn XML into diffs until you run out
dpw.Close() // write end marker and any etc., flush output
dpr := dpfile.NewReader(in, workingDir, streaming) // streaming=true readinf from stdin
for dpr.ReadSegment {} // turn diffs into XML as long as you can
dpr.Close() // wrap up
The writer implementation does some ... |
if badFormat {
panic("Didn't see the expected format name in the header. Either the input isn't actually a dltp file or the format has changed you need to download a newer version of this tool.")
}
sourceUrl := readLineOrPanic(d | badFormat = true
} | random_line_split |
dpfile.go | Packer\nno format URL yet\nno source URL\n\n")
if err != nil {
panic(err)
}
for _, name := range sourceNames {
// baseName is right for both URLs + Windows file paths
baseName := path.Base(filepath.Base(name))
niceOutName := zip.UnzippedName(baseName)
fmt.Fprintln(dpw.out, niceOutName)
}
err = dpw.out.Wr... | {
if sourceCksum == 0 { // no source checksum
panicMsg = "checksum mismatch. it's possible you don't have the original file this diff was created against, or it could be a bug in dltp."
} else {
panicMsg = "sorry; it looks like source file you have isn't original file this diff was created against."
}
... | conditional_block | |
dpfile.go | .B // is truncated by Diff
t.source.Write(t.s.Out)
binary.Write(t.s.Out, binary.BigEndian, dpchecksum(t.s.A))
t.s.Diff()
binary.Write(t.s.Out, binary.BigEndian, dpchecksum(bOrig))
select {
case t.done <- 1:
return
default:
panic("same difftask being used twice!")
}
}
func doDiffTasks(tc chan *DiffTask) {
... | Close | identifier_name | |
main.rs | struct Args {
toml_config: String,
print_queue: bool,
print_total_cov: bool,
skip_deterministic: bool,
skip_non_deterministic: bool,
random: bool,
input_directory: Option<String>,
output_directory: String,
test_mode: bool,
jqf: analysis::JQFLevel,
fuzz_server_id: String,
seed_cycles: usize,
}
fn main() {
... | s >= max_children { break; }
}
q.return_test(active_test.id, history);
| { println!("invalid input...."); }
let (info, interesting_input) = server.get_info(feedback.id);
let now = get_time();
statistics.update_new_discovery(info.mutator.id, now, analysis.get_bitmap());
q.add_new_test(interesting_input, info, rr.new_cov,
!rr.is_invalid, now,
... | conditional_block |
main.rs | ::with_name("input_directory")
.long("input-directory").short("i").value_name("DIR")
.takes_value(true)
.help("The output directory of a previous run from which to resume."))
.arg(Arg::with_name("output_directory")
.long("output-directory").short("o").value_name("DIR")
.takes_value(true)
.help("Used... | me();
std::time::Duration::new(raw.sec as u64, raw.nsec as u32)
} | identifier_body | |
main.rs | struct | {
toml_config: String,
print_queue: bool,
print_total_cov: bool,
skip_deterministic: bool,
skip_non_deterministic: bool,
random: bool,
input_directory: Option<String>,
output_directory: String,
test_mode: bool,
jqf: analysis::JQFLevel,
fuzz_server_id: String,
seed_cycles: usize,
}
fn main() {
let matches... | Args | identifier_name |
main.rs | struct Args {
toml_config: String,
print_queue: bool,
print_total_cov: bool,
skip_deterministic: bool,
skip_non_deterministic: bool,
random: bool,
input_directory: Option<String>,
output_directory: String,
test_mode: bool,
jqf: analysis::JQFLevel,
fuzz_server_id: String,
seed_cycles: usize,
}
fn main() {
... | } else {
fuzzer(args, canceled, config, test_size, &mut server);
}
}
fn test_mode(server: &mut FuzzServer, config: &config::Config) {
println!("⚠️ Test mode selected! ⚠️");
test::test_fuzz_server(server, config);
}
fn fuzzer(args: Args, canceled: Arc<AtomicBool>, config: config::Config,
test_size: run... | let server_dir = format!("{}/{}", FPGA_DIR, args.fuzz_server_id);
let mut server = find_one_fuzz_server(&server_dir, srv_config).expect("failed to find a fuzz server");
if args.test_mode {
test_mode(&mut server, &config); | random_line_split |
http_remote.rs | header_map: Headers,
}
impl<'cfg> HttpRegistry<'cfg> {
/// Creates a HTTP-rebased remote registry for `source_id`.
///
/// * `name` --- Name of a path segment where `.crate` tarballs and the
/// registry index are stored. Expect to be unique.
pub fn new(
source_id: SourceId,
c... | (buf: &[u8]) -> Option<(&str, &str)> {
if buf.is_empty() {
return None;
}
let buf = std::str::from_utf8(buf).ok()?.trim_end();
// Don't let server sneak extra lines anywhere.
if buf.contains('\n') {
return None;
}
let (tag, value) = buf.spl... | handle_http_header | identifier_name |
http_remote.rs | self.multi.set_max_host_connections(2)?;
if !self.quiet {
self.config
.shell()
.status("Updating", self.source_id.display_index())?;
}
Ok(())
}
/// Checks the results inside the [`HttpRegistry::multi`] handle, and
/// updates rel... | format!("{}: {}", ETAG, etag)
} else if let Some(lm) = result.header_map.last_modified {
format!("{}: {}", LAST_MODIFIED, lm) | random_line_split | |
http_remote.rs | header_map: Headers,
}
impl<'cfg> HttpRegistry<'cfg> {
/// Creates a HTTP-rebased remote registry for `source_id`.
///
/// * `name` --- Name of a path segment where `.crate` tarballs and the
/// registry index are stored. Expect to be unique.
pub fn new(
source_id: SourceId,
c... | let (mut download, handle) = self.downloads.pending.remove(&token).unwrap();
let was_present = self.downloads.pending_paths.remove(&download.path);
assert!(
was_present,
"expected pending_paths to contain {:?}",
download.path
... | {
assert_eq!(
self.downloads.pending.len(),
self.downloads.pending_paths.len()
);
// Collect the results from the Multi handle.
let results = {
let mut results = Vec::new();
let pending = &mut self.downloads.pending;
self.multi... | identifier_body |
lexer.rs | continuation of the current one
fn more(&mut self);
/// Tells lexer to completely ignore and not emit current token.
fn skip(&mut self);
#[doc(hidden)]
fn reset(&mut self);
#[doc(hidden)]
fn get_interpreter(&self) -> Option<&LexerATNSimulator>;
}
/// **! Usually generated by ANTLR !**
/... |
}
impl<'input, T, Input, TF> DerefMut for BaseLexer<'input, T, Input, TF>
where
T: LexerRecog<'input, Self> + 'static,
Input: CharStream<TF::From>,
TF: TokenFactory<'input>,
{
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.recog
}
}
impl<'input, T, Input, TF> Recognizer<'input> ... | {
&self.recog
} | identifier_body |
lexer.rs | ` to override token that is currently being generated by lexer
pub token: Option<TF::Tok>,
hit_eof: bool,
/// Channel lexer is currently assigning tokens to
pub channel: isize,
/// stack of modes, which is used for pushMode,popMode lexer actions
pub mode_stack: Vec<usize>,
/// Mode lexer is ... | {
self.hit_eof = true;
} | conditional_block | |
lexer.rs | mut self,
_localctx: Option<&<Self::Node as ParserNodeType<'input>>::Type>,
rule_index: isize,
action_index: isize,
) {
<T as Actions<'input, Self>>::action(_localctx, rule_index, action_index, self)
}
}
/// Default lexer mode id
pub const LEXER_DEFAULT_MODE: usize = 0;
/// Spec... | listener.syntax_error(
lexer,
None,
lexer.token_start_line, | random_line_split | |
lexer.rs | a continuation of the current one
fn more(&mut self);
/// Tells lexer to completely ignore and not emit current token.
fn skip(&mut self);
#[doc(hidden)]
fn reset(&mut self);
#[doc(hidden)]
fn get_interpreter(&self) -> Option<&LexerATNSimulator>;
}
/// **! Usually generated by ANTLR !**... | (&mut self, _text: <TF::Data as ToOwned>::Owned) {
self.text = Some(_text);
}
// fn get_all_tokens(&mut self) -> Vec<TF::Tok> { unimplemented!() }
// fn get_char_error_display(&self, _c: char) -> String { unimplemented!() }
/// Add error listener
pub fn add_error_listener(&mut self, liste... | set_text | identifier_name |
app_2_wl.py | down("[Tweetru ministre gui eub walu wergu yaram ](https://twitter.com/MinisteredelaS1)")
st.sidebar.markdown("[Booleb xéeti mbir ak màndargaay jumtukaayu ](https://github.com/maelfabien/COVID-19-Senegal)")
st.sidebar.markdown("---")
st.sidebar.header("Jokko ak wa ministere")
st.sidebar.markdown("Ministre gui e... | st.markdown("---")
st.subheader("Tassarok Jangorogui")
st.write("Ñugui xamé ñeneu ñu jeulé Jangoroji ci ñu jugué bimeu rew, ci niit ñu feebar yigua xamené ño waleu ñeni niit.Limu ñigua xamné ño ameu Jangoroji té jeuléko ci biir rewmi, moye waleu gui geuna ragalu ci walanté Jangoroji..")
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.