file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
Z_normal_8_2.py | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt,mpld3
from collections import defaultdict
from sklearn.metrics.pairwise import euclidean_distances
from flask import Flask, render_template, request
import math
import itertools
"""------------- Intiali... |
"""------------- 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 | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt,mpld3
from collections import defaultdict
from sklearn.metrics.pairwise import euclidean_distances
from flask import Flask, render_template, request
import math
import itertools
"""------------- Intiali... | (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 | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | () *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 | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... |
}
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 | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... | return uniqueName
}
// resolveTypedefEnumeratedName takes a yang.Entry which represents a typedef
// that has an underlying enumerated type (e.g., identityref or enumeration),
// and resolves the name of the enum that will be generated in the corresponding
// Go code.
func (s *genState) resolveTypedefEnumeratedName(e... | uniqueName := makeNameUnique(nbuf.String(), s.definedGlobals)
s.uniqueEnumeratedLeafNames[identifierPath] = uniqueName | random_line_split |
genstate.go | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in... |
// identityrefBaseTypeFromIdentity takes an input yang.Identity pointer and
// determines the name of the identity used within the generated code for it. The value
// returned is based on the defining module followed by the CamelCase-ified version
// of the identity's name. If noUnderscores is set to false, underscor... | {
return s.identityrefBaseTypeFromIdentity(idr.Type.IdentityBase, noUnderscores)
} | identifier_body |
flappybird.js | var Const = {
BIRD_RADIUS : 28,
BIRD_JUMP_SPEED : 10,
OBST_WIDTH : 85,
OBST_MAX_HEIGHT : 400,
OBST_MIN_HEIGHT : 40,
OBST_COUNT : 10000,
OBST_START_X : 600,
OBST_MARGIN : 300,
OBST_HEAD_HEIGHT : 32,
SCREEN_HEIGHT : 640,
SCREEN_WIDTH : 480,
PASS_HEIGHT : 200,
X_VOL : 4,
G : 0.8,
JUMP_INTERVAL: 8 //can jump... | 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 | var Const = {
BIRD_RADIUS : 28,
BIRD_JUMP_SPEED : 10,
OBST_WIDTH : 85,
OBST_MAX_HEIGHT : 400,
OBST_MIN_HEIGHT : 40,
OBST_COUNT : 10000,
OBST_START_X : 600,
OBST_MARGIN : 300,
OBST_HEAD_HEIGHT : 32,
SCREEN_HEIGHT : 640,
SCREEN_WIDTH : 480,
PASS_HEIGHT : 200,
X_VOL : 4,
G : 0.8,
JUMP_INTERVAL: 8 //can jump... | else {
this.isCOM = false;
this.bird.jump();
}
},
onkeydown : function(e) {
var keyCode = ('which' in event) ? event.which : event.keyCode;
switch(keyCode){
case 32: // space
this.jump();
break;
case 68: // d
this.start(true);
break;
}
}
}
| {
this.start(false);
this.bird.jump();
} | conditional_block |
raft.go | // Copyright 2015 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | 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 | // Copyright 2015 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | pointerToEntriesToAppend := make([]*pb.Entry, 0)
for i, _ := range entriesToAppend {
pointerToEntriesToAppend = append(pointerToEntriesToAppend, &entriesToAppend[i])
}
m := pb.Message{MsgType: pb.MessageType_MsgAppend, To: to, From: r.id, Term: r.Term, Index: prevLogIndex, LogTerm: prevLogTerm, Entries: pointerT... | // 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 | // Copyright 2015 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | lse {
if r.hasEarlierLogThanCandidate(m) && !r.hasMoreCommittedLogsThanCandidate(m){
r.grantVoting(m)
return
} else {
r.rejectVoting(m)
return
}
}
} else {
r.rejectVoting(m)
return
}
}
func (r *Raft) startVoting() {
r.becomeCandidate()
r.votes[r.id] = true
r.Vote = r.id
if r.tally... | r.rejectVoting(m)
return
} e | conditional_block |
raft.go | // Copyright 2015 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | 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 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on the 23 March 2017
author : olivier regniers (i-sea)
Application : reads metadata, applies coastline mask, performs atmospheric correction using DOS1 approach and export result in outFolder, estimates Turbidity with method from Dogliotti 2015 based on Red and NIR ... | 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 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on the 23 March 2017
author : olivier regniers (i-sea)
Application : reads metadata, applies coastline mask, performs atmospheric correction using DOS1 approach and export result in outFolder, estimates Turbidity with method from Dogliotti 2015 based on Red and NIR ... |
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 | package pixelgl
import (
"fmt"
"image/color"
"github.com/faiface/glhf"
"github.com/faiface/mainthread"
"github.com/faiface/pixel"
"github.com/go-gl/mathgl/mgl32"
"github.com/pkg/errors"
)
// Canvas is an off-screen rectangular BasicTarget and Picture at the same time, that you can draw
// onto.
//
// It suppo... |
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 | package pixelgl
import (
"fmt"
"image/color"
"github.com/faiface/glhf"
"github.com/faiface/mainthread"
"github.com/faiface/pixel"
"github.com/go-gl/mathgl/mgl32"
"github.com/pkg/errors"
)
// Canvas is an off-screen rectangular BasicTarget and Picture at the same time, that you can draw
// onto.
//
// It suppo... | 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 | package pixelgl
import (
"fmt"
"image/color"
"github.com/faiface/glhf"
"github.com/faiface/mainthread"
"github.com/faiface/pixel"
"github.com/go-gl/mathgl/mgl32"
"github.com/pkg/errors"
)
// Canvas is an off-screen rectangular BasicTarget and Picture at the same time, that you can draw
// onto.
//
// It suppo... | (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 | package pixelgl
import (
"fmt"
"image/color"
"github.com/faiface/glhf"
"github.com/faiface/mainthread"
"github.com/faiface/pixel"
"github.com/go-gl/mathgl/mgl32"
"github.com/pkg/errors"
)
// Canvas is an off-screen rectangular BasicTarget and Picture at the same time, that you can draw
// onto.
//
// It suppo... |
}
// 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 | //! A builder for a Fletcher-like algorithm.
//!
//! The basic functionality of this algorithm is:
//! * there is a sum which is just the bytes summed modulo some number
//! * there is also a second sum which the sum of all of the normal sums (modulo the same number)
//!
//! Note that text word sizes are currently only... |
/// 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-like algorithm.
//!
//! The basic functionality of this algorithm is:
//! * there is a sum which is just the bytes summed modulo some number
//! * there is also a second sum which the sum of all of the normal sums (modulo the same number)
//!
//! Note that text word sizes are currently only... | (&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 | //! A builder for a Fletcher-like algorithm.
//!
//! The basic functionality of this algorithm is:
//! * there is a sum which is just the bytes summed modulo some number
//! * there is also a second sum which the sum of all of the normal sums (modulo the same number)
//!
//! Note that text word sizes are currently only... | }
} | random_line_split | |
mod.rs | //! A builder for a Fletcher-like algorithm.
//!
//! The basic functionality of this algorithm is:
//! * there is a sum which is just the bytes summed modulo some number
//! * there is also a second sum which the sum of all of the normal sums (modulo the same number)
//!
//! Note that text word sizes are currently only... | ;
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 | # -*- coding: utf-8 -*-
"""RandomForest.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1fLF-UltTb6lDISECxqmX_PMPXqH2B7sl
"""
## IMPORTS
import numpy as np
import pandas as pd
import scipy
from scipy import signal
from scipy.io import loadmat
f... | 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 | # -*- coding: utf-8 -*-
"""RandomForest.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1fLF-UltTb6lDISECxqmX_PMPXqH2B7sl
"""
## IMPORTS
import numpy as np
import pandas as pd
import scipy
from scipy import signal
from scipy.io import loadmat
f... |
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 | # -*- coding: utf-8 -*-
"""RandomForest.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1fLF-UltTb6lDISECxqmX_PMPXqH2B7sl
"""
## IMPORTS
import numpy as np
import pandas as pd
import scipy
from scipy import signal
from scipy.io import loadmat
f... | (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 | # -*- coding: utf-8 -*-
"""RandomForest.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1fLF-UltTb6lDISECxqmX_PMPXqH2B7sl
"""
## IMPORTS
import numpy as np
import pandas as pd
import scipy
from scipy import signal
from scipy.io import loadmat
f... |
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 | from string import Template
import os
#-----template objects-----
#for putting a template inside an ifdef guard
TIfGuard = Template("""if(${condition})
${innerbody}
endif()\n""")
#For minimum cmake version and project name
TProjectSettings = Template("""cmake_minimum_required (VERSION ${MinCmakeVer})
project(${Name}... |
#-----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 | from string import Template
import os
#-----template objects-----
#for putting a template inside an ifdef guard
TIfGuard = Template("""if(${condition})
${innerbody}
endif()\n""")
#For minimum cmake version and project name
TProjectSettings = Template("""cmake_minimum_required (VERSION ${MinCmakeVer})
project(${Name}... | (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 | from string import Template
import os
#-----template objects-----
#for putting a template inside an ifdef guard
TIfGuard = Template("""if(${condition})
${innerbody}
endif()\n""")
#For minimum cmake version and project name
TProjectSettings = Template("""cmake_minimum_required (VERSION ${MinCmakeVer})
project(${Name}... |
return None
#writes the include for a submodule
def WriteSubmoduleIncludes(f, rootDir, sections):
for s in sections:
submods = s.data[":"]
for sm in submods:
sm = sm if sm.startswith('/') else "/"+sm
output = TSubmoduleInclude.substitute(dict(dir=rootDir+sm)) + "\n"
WriteToFile(f,output, s.Has... | f.write(TObjectLib.substitute(dict(project=name)))
f.write(TTargetLinkLibs.substitute(dict(name=name))) | conditional_block |
cmake_templates.py | from string import Template
import os
#-----template objects-----
#for putting a template inside an ifdef guard
TIfGuard = Template("""if(${condition})
${innerbody}
endif()\n""")
#For minimum cmake version and project name
TProjectSettings = Template("""cmake_minimum_required (VERSION ${MinCmakeVer})
project(${Name}... | else:
runtime = runtime if runtime.startswith('/') else "/"+runtime
runtime = rootDir + runtime
output = TRuntimeOutput.substitute(dict(dir=runtime))
WriteToFile(f,output, s.HasCondition(), s.condition)
if "Runtime" in s.data:
runtime = s.data["Runtime"]
#insert any environment variables
... | runtime = InsertEnvVariable(runtime) | random_line_split |
__init__.py | """@package XLM
Top level Excel XLM macro emulator interface.
"""
from __future__ import print_function
import subprocess
import sys
import re
import os
import string
# https://github.com/kirk-sayre-work/office_dumper.git
import excel
import XLM.color_print
import XLM.stack_transformer
import XLM.XLM_Object
import ... | (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 | """@package XLM
Top level Excel XLM macro emulator interface.
"""
from __future__ import print_function
import subprocess
import sys
import re
import os
import string
# https://github.com/kirk-sayre-work/office_dumper.git
import excel
import XLM.color_print
import XLM.stack_transformer
import XLM.XLM_Object
import ... |
# Run olevba on the file and extract the XLM macro code lines.
color_print.output('g', "Analyzing Excel 97 file ...")
xlm_code = _extract_xlm(maldoc)
color_print.output('g', "Extracted XLM with olevba.")
if debug:
print("=========== START RAW XLM ==============")
print(xlm_code)
... | random_line_split | |
__init__.py | """@package XLM
Top level Excel XLM macro emulator interface.
"""
from __future__ import print_function
import subprocess
import sys
import re
import os
import string
# https://github.com/kirk-sayre-work/office_dumper.git
import excel
import XLM.color_print
import XLM.stack_transformer
import XLM.XLM_Object
import ... |
####################################################################
def _guess_xlm_sheet(workbook):
"""
Guess the sheet containing the XLM macros by finding the sheet with the
most unresolved "#NAME" cells.
@param workbook (ExcelSheet object) The Excel spreadsheet to check.
@return (str) The na... | """
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 | """@package XLM
Top level Excel XLM macro emulator interface.
"""
from __future__ import print_function
import subprocess
import sys
import re
import os
import string
# https://github.com/kirk-sayre-work/office_dumper.git
import excel
import XLM.color_print
import XLM.stack_transformer
import XLM.XLM_Object
import ... |
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 | #![feature(macro_rules, intrinsics, lang_items, globs)]
#![no_std]
extern crate libc;
extern crate core;
extern crate alloc;
extern crate collections;
extern crate rand;
pub use core::prelude::*;
pub use cheats::{Cheat, CheatManager};
pub use alloc::owned::Box;
pub use collections::Vec;
use core::raw::Repr;
mod log... | #[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 | #![feature(macro_rules, intrinsics, lang_items, globs)]
#![no_std]
extern crate libc;
extern crate core;
extern crate alloc;
extern crate collections;
extern crate rand;
pub use core::prelude::*;
pub use cheats::{Cheat, CheatManager};
pub use alloc::owned::Box;
pub use collections::Vec;
use core::raw::Repr;
mod log... |
#[allow(non_snake_case_functions)]
#[no_mangle]
pub extern "C" fn _imp___onexit() {
}
#[no_mangle]
pub extern "C" fn __dllonexit() {
}
#[no_mangle]
pub extern "C" fn __setusermatherr() {
} | {
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 | #![feature(macro_rules, intrinsics, lang_items, globs)]
#![no_std]
extern crate libc;
extern crate core;
extern crate alloc;
extern crate collections;
extern crate rand;
pub use core::prelude::*;
pub use cheats::{Cheat, CheatManager};
pub use alloc::owned::Box;
pub use collections::Vec;
use core::raw::Repr;
mod log... | (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 | #![feature(macro_rules, intrinsics, lang_items, globs)]
#![no_std]
extern crate libc;
extern crate core;
extern crate alloc;
extern crate collections;
extern crate rand;
pub use core::prelude::*;
pub use cheats::{Cheat, CheatManager};
pub use alloc::owned::Box;
pub use collections::Vec;
use core::raw::Repr;
mod log... | 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 | /*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2014 SAP AG or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
/* ----------------------------------------------------------------------------------
* Hint: This is a derived (generat... | * @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 JSon object or a
* list of objects or the area element or elements.
*
* @param {sap.ui.commons.Area|string} Area to add
* @return {sa... | * @type void | random_line_split |
ImageMap-dbg.js | /*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2014 SAP AG or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
/* ----------------------------------------------------------------------------------
* Hint: This is a derived (generat... |
this.addArea(oArea);
}
return this;
};
/**
* Used for after-rendering initialization.
*
* @private
*/
sap.ui.commons.ImageMap.prototype.onAfterRendering = function() {
this.oDomRef = this.getDomRef();
// Initialize the ItemNavigation if does not exist yet
if (!this.oItemNavigation) {
this.oItemNavigati... | {
oArea = new sap.ui.commons.Area(oContent);
} | conditional_block |
app-engine.js | /*
* -------------------------------------------------------------------------
* This is the data for an errorMessage
* -------------------------------------------------------------------------
*/
var errorResponses = [{
'id': '12309120',
'name': "OH NO!!",
'snippet_text': "You're yelp req... | (url, yData) {
$.ajax({
'timeout': 3000,
'type': 'GET',
'url': url,
'data': yData,
'dataType': 'jsonp',
'global': true,
'cache': true,
'jsonpCallback': 'cb',
'success': function(data) {
makeYelpList(data);
},
'error... | yJax | identifier_name |
app-engine.js | /*
* -------------------------------------------------------------------------
* This is the data for an errorMessage
* -------------------------------------------------------------------------
*/
var errorResponses = [{
'id': '12309120',
'name': "OH NO!!",
'snippet_text': "You're yelp req... |
}
});
}
/** ----------------------------------------------------------------------------
* Handles changing mapShift vars in responsive manner using matchMedia
* ----------------------------------------------------------------------------
*/
function reformatOnSize() {
if (window.matchMedia("(m... | { // check if two distances are close
OpenInfowindowForMarker(resultCard); // open Infowindow for placeCard being viewed in DOM
} | conditional_block |
app-engine.js | /*
* -------------------------------------------------------------------------
* This is the data for an errorMessage
* -------------------------------------------------------------------------
*/
var errorResponses = [{
'id': '12309120',
'name': "OH NO!!",
'snippet_text': "You're yelp req... |
/*
* -------------------------
* Inital Call to Yelp
* -------------------------
*/
yelpAjax(searchFor(), searchNear()); // onload initalize with starting Yelp Results
/*
* -------------------------------------------------------------------------
* This section handles requests to Google Maps ... | {
/* --- 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 | /*
* -------------------------------------------------------------------------
* This is the data for an errorMessage
* -------------------------------------------------------------------------
*/
var errorResponses = [{
'id': '12309120',
'name': "OH NO!!",
'snippet_text': "You're yelp req... | scrollAdjustment = 0;
map.setZoom(11);
$('#map').removeClass("fixed");
}
}
$(window).resize(function() {
reformatOnSize();
});
/* --- force scroll the DOM to the top --- */
function forceTop() {
$('html, body').animate({
scrollTop: $('body').offset().top,
}, 200);
}
/* -... | up: 0
}; | random_line_split |
aml.py | import sys
class Node(object):
def __init__(self, name=""):
self.children = set()
self.parents = set()
self.name = name
self.dual = None
def addChild(self, node):
self.children.add(node)
def removeChild(self, node):
self.children.discard(node)
def... | 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 | import sys
class Node(object):
def __init__(self, name=""):
self.children = set()
self.parents = set()
self.name = name
self.dual = None
def addChild(self, node):
self.children.add(node)
def removeChild(self, node):
self.children.discard(node)
def... |
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 | import sys
class Node(object):
def __init__(self, name=""):
self.children = set()
self.parents = set()
self.name = name
self.dual = None
def addChild(self, node):
self.children.add(node)
def removeChild(self, node):
self.children.discard(node)
def... | (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 | import sys
class Node(object):
def __init__(self, name=""):
self.children = set()
self.parents = set()
self.name = name
self.dual = None
def addChild(self, node):
self.children.add(node)
def removeChild(self, node):
self.children.discard(node)
def... |
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 | package table
import (
"fmt"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
slice "sort"
humanize "github.com/dustin/go-humanize"
cmc "github.com/miguelmota/go-coinmarketcap/pro/v1"
gc "github.com/rthornton128/goncurses"
pad "github.com/willf/pad/utf8"
)
var wg sync.WaitGroup
/... | s.helpwin.MovePrint(18, 1, "<v> to sort by 24 hour volume")
s.helpwin.MovePrint(19, 1, "<q> or <esc> to quit application.")
s.helpwin.Refresh()
return nil
}
// OnWindowResize sends event to channel when resize event occurs
func (s *Service) onWindowResize(channel chan os.Signal) {
//stdScr, _ := gc.Init()
//stdS... | s.helpwin.MovePrint(17, 1, "<p> to sort by price") | random_line_split |
table.go | package table
import (
"fmt"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
slice "sort"
humanize "github.com/dustin/go-humanize"
cmc "github.com/miguelmota/go-coinmarketcap/pro/v1"
gc "github.com/rthornton128/goncurses"
pad "github.com/willf/pad/utf8"
)
var wg sync.WaitGroup
/... | {
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 | package table
import (
"fmt"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
slice "sort"
humanize "github.com/dustin/go-humanize"
cmc "github.com/miguelmota/go-coinmarketcap/pro/v1"
gc "github.com/rthornton128/goncurses"
pad "github.com/willf/pad/utf8"
)
var wg sync.WaitGroup
/... | 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 | package table
import (
"fmt"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
slice "sort"
humanize "github.com/dustin/go-humanize"
cmc "github.com/miguelmota/go-coinmarketcap/pro/v1"
gc "github.com/rthornton128/goncurses"
pad "github.com/willf/pad/utf8"
)
var wg sync.WaitGroup
/... | () error {
if !s.helpVisible {
if s.helpwin != nil {
s.helpwin.ClearOk(true)
s.helpwin.Clear()
s.helpwin.SetBackground(gc.ColorPair(6))
s.helpwin.ColorOn(6)
s.helpwin.Resize(0, 0)
s.helpwin.MoveWindow(200, 200)
s.helpwin.Refresh()
s.renderMenu()
}
return nil
}
var err error
if s.helpw... | renderHelpWindow | identifier_name |
cli.rs | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | 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 | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | (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 | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | try!(io::stdin().read_line(&mut response));
match response.trim().chars().next().unwrap_or('\n') {
'y' | 'Y' => return Ok(true),
'n' | 'N' => return Ok(false),
'q' | 'Q' => process::exit(0),
'\n' => {
match defau... | let mut response = String::new(); | random_line_split |
cli.rs | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... |
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 | package main
import (
"crypto/sha1"
"encoding/hex"
"flag"
"fmt"
"github.com/amyangfei/dynamicmq-go/chord"
dmq "github.com/amyangfei/dynamicmq-go/dynamicmq"
"github.com/op/go-logging"
"github.com/rakyll/globalconf"
"os"
"os/signal"
"runtime"
"strconv"
"strings"
"syscall"
)
// Server basic configuration
v... |
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 | package main
import (
"crypto/sha1"
"encoding/hex"
"flag"
"fmt"
"github.com/amyangfei/dynamicmq-go/chord"
dmq "github.com/amyangfei/dynamicmq-go/dynamicmq"
"github.com/op/go-logging"
"github.com/rakyll/globalconf"
"os"
"os/signal"
"runtime"
"strconv"
"strings"
"syscall"
)
// Server basic configuration
v... |
func chordRoutine() {
conf := &chord.NodeConfig{
Serf: &chord.SerfConfig{
BinPath: Config.SerfBinPath,
NodeName: Config.SerfNodeName,
BindAddr: Config.SerfBindAddr,
RPCAddr: Config.SerfRPCAddr,
EvHandler: Config.SerfEvHandler,
},
Hostname: Config.Hostname,
HostIP: Config.Bi... | {
log.Info("Datanode stop...")
unRegisterDN(Config, ChordNode, EtcdCliPool)
os.Exit(0)
} | identifier_body |
main.go | package main
import (
"crypto/sha1"
"encoding/hex"
"flag"
"fmt"
"github.com/amyangfei/dynamicmq-go/chord"
dmq "github.com/amyangfei/dynamicmq-go/dynamicmq"
"github.com/op/go-logging"
"github.com/rakyll/globalconf"
"os"
"os/signal"
"runtime"
"strconv"
"strings"
"syscall"
)
// Server basic configuration
v... | (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 | package main
import (
"crypto/sha1"
"encoding/hex"
"flag"
"fmt"
"github.com/amyangfei/dynamicmq-go/chord"
dmq "github.com/amyangfei/dynamicmq-go/dynamicmq"
"github.com/op/go-logging"
"github.com/rakyll/globalconf"
"os"
"os/signal"
"runtime"
"strconv"
"strings"
"syscall"
)
// Server basic configuration
v... | 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 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 4 11:57:37 2021
Hypsometry plots
To Do:
select only glaciers where 'RGIId' matches with filtered dissolved outline 'RGIId'
@author: apj
"""
import pandas as pd
import geopandas as gpd
from rasterstats import zonal_stats
import rasterio as r... |
# function to extract data by mask
def glacierMask(fp_raster, features):
with rasterio.open(fp_raster) as src:
glac_mask, glac_out_transform = rasterio.mask.mask(src, shapes, crop=False)
glac_nodata = src.nodata
masked = glac_mask[0]
masked[(masked == glac_nodata)] = np.nan
return... | """
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 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 4 11:57:37 2021
Hypsometry plots
To Do:
select only glaciers where 'RGIId' matches with filtered dissolved outline 'RGIId'
@author: apj
"""
import pandas as pd
import geopandas as gpd
from rasterstats import zonal_stats
import rasterio as r... | axes[1].grid()
textstr = '\n'.join((
'Glacierized area',
asumstr[0],
asumstr[1],
asumstr[2]))
# matplotlib patch properties
props = dict(boxstyle='round', facecolor='white', alpha=1)
# place text box in axes coords
axes[1].text(0.5, 0.05, textstr, transform=axes[1].transAxes, fontsize=10,
... | axes[1].legend(loc=1) | random_line_split |
hypsometry_plots.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 4 11:57:37 2021
Hypsometry plots
To Do:
select only glaciers where 'RGIId' matches with filtered dissolved outline 'RGIId'
@author: apj
"""
import pandas as pd
import geopandas as gpd
from rasterstats import zonal_stats
import rasterio as r... |
# get elevation differences for each elevation bin
for tif in tifflist:
bname = os.path.basename(tif)
# read ddem and mask with selected glaciers
ddem = glacierMask(tif, shapes)
# classify dem to bins
digitized = np.digitize(dem, bins)
# calculate average elevation difference per... | tifflist.append(t) | conditional_block |
hypsometry_plots.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 4 11:57:37 2021
Hypsometry plots
To Do:
select only glaciers where 'RGIId' matches with filtered dissolved outline 'RGIId'
@author: apj
"""
import pandas as pd
import geopandas as gpd
from rasterstats import zonal_stats
import rasterio as r... | (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]
# (spark_horovod_keras)=
#
# # Data-Parallel Distributed Training Using Horovod on Spark
#
# When time- and compute-intensive deep learning workloads need to be trained efficiently, data-parallel distributed training comes to the rescue.
# This technique parallelizes the data and requires sharing of wei... |
# %% [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 | # %% [markdown]
# (spark_horovod_keras)=
#
# # Data-Parallel Distributed Training Using Horovod on Spark
#
# When time- and compute-intensive deep learning workloads need to be trained efficiently, data-parallel distributed training comes to the rescue.
# This technique parallelizes the data and requires sharing of wei... | continuous_bn = Concatenate()([Reshape((1, 1), name="reshape_" + col)(inputs[col]) for col in CONTINUOUS_COLS])
continuous_bn = BatchNormalization()(continuous_bn)
x = Concatenate()(embeddings + [continuous_bn])
x = Flatten()(x)
x = Dense(1000, activation="relu", kernel_regularizer=tf.keras.regulari... | 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 | # %% [markdown]
# (spark_horovod_keras)=
#
# # Data-Parallel Distributed Training Using Horovod on Spark
#
# When time- and compute-intensive deep learning workloads need to be trained efficiently, data-parallel distributed training comes to the rescue.
# This technique parallelizes the data and requires sharing of wei... |
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 | # %% [markdown]
# (spark_horovod_keras)=
#
# # Data-Parallel Distributed Training Using Horovod on Spark
#
# When time- and compute-intensive deep learning workloads need to be trained efficiently, data-parallel distributed training comes to the rescue.
# This technique parallelizes the data and requires sharing of wei... | (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 | package runtime
import (
"context"
"fmt"
"io"
"regexp"
"time"
"code.cloudfoundry.org/garden"
"github.com/containerd/containerd"
"github.com/containerd/containerd/cio"
uuid "github.com/nu7hatch/gouuid"
"github.com/opencontainers/runtime-spec/specs-go"
)
const (
SuperuserPath = "PATH=/usr/local/sbin:/usr/lo... |
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 | package runtime
import (
"context"
"fmt"
"io"
"regexp"
"time"
"code.cloudfoundry.org/garden"
"github.com/containerd/containerd"
"github.com/containerd/containerd/cio"
uuid "github.com/nu7hatch/gouuid"
"github.com/opencontainers/runtime-spec/specs-go"
)
const (
SuperuserPath = "PATH=/usr/local/sbin:/usr/lo... |
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 | package runtime
import (
"context"
"fmt"
"io"
"regexp"
"time"
"code.cloudfoundry.org/garden"
"github.com/containerd/containerd"
"github.com/containerd/containerd/cio"
uuid "github.com/nu7hatch/gouuid"
"github.com/opencontainers/runtime-spec/specs-go"
)
const (
SuperuserPath = "PATH=/usr/local/sbin:/usr/lo... |
// 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 | package runtime
import (
"context"
"fmt"
"io"
"regexp"
"time"
"code.cloudfoundry.org/garden"
"github.com/containerd/containerd"
"github.com/containerd/containerd/cio"
uuid "github.com/nu7hatch/gouuid"
"github.com/opencontainers/runtime-spec/specs-go"
)
const (
SuperuserPath = "PATH=/usr/local/sbin:/usr/lo... | (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 | /*
Copyright 2016 caicloud authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed ... | () (*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 | /*
Copyright 2016 caicloud authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed ... |
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 | /*
Copyright 2016 caicloud authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed ... | {
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 | /*
Copyright 2016 caicloud authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed ... | 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 | // Accepts iPhone screenshots of a Kami gameboard and prints a solution.
// See https://itunes.apple.com/us/app/kami/id710724007
package main
import (
"flag"
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"log"
"math"
"os"
"sort"
"strconv"
colorful "github.com/lucasb-eyer/go-colorful"
)
const (
RO... | moves := <-solutionChan
if moves != nil {
for i, j := 0, len(moves)-1; i < j; i, j = i+1, j-1 {
moves[i], moves[j] = moves[j], moves[i]
}
return moves
}
}
return nil
}
func main() {
flag.Parse()
args := flag.Args()
if len(args) != 3 {
fmt.Printf("usage: gokami <ncolors> <nmoves> <filename>\n"... |
// Wait for a solution
for i := 0; i < numWorkers; i++ { | random_line_split |
solve_kami.go | // Accepts iPhone screenshots of a Kami gameboard and prints a solution.
// See https://itunes.apple.com/us/app/kami/id710724007
package main
import (
"flag"
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"log"
"math"
"os"
"sort"
"strconv"
colorful "github.com/lucasb-eyer/go-colorful"
)
const (
RO... |
}
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 | // Accepts iPhone screenshots of a Kami gameboard and prints a solution.
// See https://itunes.apple.com/us/app/kami/id710724007
package main
import (
"flag"
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"log"
"math"
"os"
"sort"
"strconv"
colorful "github.com/lucasb-eyer/go-colorful"
)
const (
RO... |
func (s intSet) contains(x int) bool {
for _, y := range s {
if x == y {
return true
}
}
return false
}
func (s *intSet) add(x int) {
if !s.contains(x) {
*s = append(*s, x)
}
}
func (s *intSet) remove(x int) {
for i, y := range *s {
if x == y {
(*s)[i] = (*s)[len(*s)-1]
*s = (*s)[:len(*s)-1]
... | {
a := make([]int, len(s))
copy(a, s)
return a
} | identifier_body |
solve_kami.go | // Accepts iPhone screenshots of a Kami gameboard and prints a solution.
// See https://itunes.apple.com/us/app/kami/id710724007
package main
import (
"flag"
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"log"
"math"
"os"
"sort"
"strconv"
colorful "github.com/lucasb-eyer/go-colorful"
)
const (
RO... | (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 | // Copyright 2013 Robert A. Uhl. All rights reserved.
// Use of this source code is governed by an MIT-style license which may
// be found in the LICENSE file.
// Package sexprs implements Ron Rivest's canonical S-expressions
// (c.f. http://people.csail.mit.edu/rivest/Sexp.txt or
// rivest-draft.txt in this package)... |
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 | // Copyright 2013 Robert A. Uhl. All rights reserved.
// Use of this source code is governed by an MIT-style license which may
// be found in the LICENSE file.
// Package sexprs implements Ron Rivest's canonical S-expressions
// (c.f. http://people.csail.mit.edu/rivest/Sexp.txt or
// rivest-draft.txt in this package)... | if bytes.IndexByte(whitespaceChar, c) == -1 {
acc = append(acc, c)
}
}
s = make([]byte, hex.DecodedLen(len(acc)))
n, err := hex.Decode(s, acc)
return s[:n], err
}
func readBase64(r *bufio.Reader) (s []byte, err error) {
raw, err := r.ReadBytes('|')
acc := make([]byte, 0, len(raw)-1)
for _, c := range raw... | random_line_split | |
sexprs.go | // Copyright 2013 Robert A. Uhl. All rights reserved.
// Use of this source code is governed by an MIT-style license which may
// be found in the LICENSE file.
// Package sexprs implements Ron Rivest's canonical S-expressions
// (c.f. http://people.csail.mit.edu/rivest/Sexp.txt or
// rivest-draft.txt in this package)... | (r *bufio.Reader, length int) (s []byte, err error) {
var acc, escape []byte
if length >= 0 {
acc = make([]byte, 0, length)
} else {
acc = make([]byte, 0)
}
escape = make([]byte, 3)
state := inQuote
for c, err := r.ReadByte(); err == nil; c, err = r.ReadByte() {
switch state {
case inQuote:
switch c {... | readQuotedString | identifier_name |
sexprs.go | // Copyright 2013 Robert A. Uhl. All rights reserved.
// Use of this source code is governed by an MIT-style license which may
// be found in the LICENSE file.
// Package sexprs implements Ron Rivest's canonical S-expressions
// (c.f. http://people.csail.mit.edu/rivest/Sexp.txt or
// rivest-draft.txt in this package)... |
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 | // Public domain, Randall Farmer, 2013
package dpfile
import (
"bufio"
"bytes"
"encoding/binary"
"fmt"
"github.com/twotwotwo/dltp/alloc"
"github.com/twotwotwo/dltp/diff"
"github.com/twotwotwo/dltp/mwxmlchunk"
sref "github.com/twotwotwo/dltp/sourceref"
"github.com/twotwotwo/dltp/stream"
"github.com/twotwotwo... |
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 | // Public domain, Randall Farmer, 2013
package dpfile
import (
"bufio"
"bytes"
"encoding/binary"
"fmt"
"github.com/twotwotwo/dltp/alloc"
"github.com/twotwotwo/dltp/diff"
"github.com/twotwotwo/dltp/mwxmlchunk"
sref "github.com/twotwotwo/dltp/sourceref"
"github.com/twotwotwo/dltp/stream"
"github.com/twotwotwo... |
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(dpr.in) // discard source URL
if sourceUrl == "" {
panic("Expected a non-blank sour... | badFormat = true
} | random_line_split |
dpfile.go | // Public domain, Randall Farmer, 2013
package dpfile
import (
"bufio"
"bytes"
"encoding/binary"
"fmt"
"github.com/twotwotwo/dltp/alloc"
"github.com/twotwotwo/dltp/diff"
"github.com/twotwotwo/dltp/mwxmlchunk"
sref "github.com/twotwotwo/dltp/sourceref"
"github.com/twotwotwo/dltp/stream"
"github.com/twotwotwo... | else {
panicMsg = "checksum mismatch. this looks likely to be a bug in dltp."
}
os.Remove("dltp-error-report.txt")
crashReport, err := os.Create("dltp-error-report.txt")
if err == nil {
// wish filenames etc were available here
fmt.Fprintln(crashReport, panicMsg)
fmt.Fprintln(crashReport, "SourceR... | {
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 | // Public domain, Randall Farmer, 2013
package dpfile
import (
"bufio"
"bytes"
"encoding/binary"
"fmt"
"github.com/twotwotwo/dltp/alloc"
"github.com/twotwotwo/dltp/diff"
"github.com/twotwotwo/dltp/mwxmlchunk"
sref "github.com/twotwotwo/dltp/sourceref"
"github.com/twotwotwo/dltp/stream"
"github.com/twotwotwo... | () {
for _, r := range dpr.sources {
if c, ok := r.(io.Closer); ok {
c.Close()
}
}
dpr.out.Flush()
}
| Close | identifier_name |
main.rs | #![allow(dead_code)]
extern crate libc;
extern crate time;
extern crate rand;
extern crate toml;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
extern crate colored;
#[macro_use] extern crate prettytable;
extern crate ctrlc;
extern crate clap;
use clap::{Arg, App};
use std::sync::atomic::{AtomicBool... | s >= max_children { break; }
}
q.return_test(active_test.id, history);
q.save_latest(statistics.take_snapshot());
if canceled.load(Ordering::SeqCst) {
println!("User interrupted fuzzing. Going to shut down....");
break;
}
}
server.sync();
while let Some(feedback) = server.pop_coverage() {
let rr =... | { 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 | #![allow(dead_code)]
extern crate libc;
extern crate time;
extern crate rand;
extern crate toml;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
extern crate colored;
#[macro_use] extern crate prettytable;
extern crate ctrlc;
extern crate clap;
use clap::{Arg, App};
use std::sync::atomic::{AtomicBool... | me();
std::time::Duration::new(raw.sec as u64, raw.nsec as u32)
} | identifier_body | |
main.rs | #![allow(dead_code)]
extern crate libc;
extern crate time;
extern crate rand;
extern crate toml;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
extern crate colored;
#[macro_use] extern crate prettytable;
extern crate ctrlc;
extern crate clap;
use clap::{Arg, App};
use std::sync::atomic::{AtomicBool... | {
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 | #![allow(dead_code)]
extern crate libc;
extern crate time;
extern crate rand;
extern crate toml;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
extern crate colored;
#[macro_use] extern crate prettytable;
extern crate ctrlc;
extern crate clap;
use clap::{Arg, App};
use std::sync::atomic::{AtomicBool... | } 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 | //! Access to a HTTP-based crate registry. See [`HttpRegistry`] for details.
use crate::core::{PackageId, SourceId};
use crate::sources::registry::download;
use crate::sources::registry::MaybeLock;
use crate::sources::registry::{LoadResponse, RegistryConfig, RegistryData};
use crate::util::errors::{CargoResult, HttpNo... | (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 | //! Access to a HTTP-based crate registry. See [`HttpRegistry`] for details.
use crate::core::{PackageId, SourceId};
use crate::sources::registry::download;
use crate::sources::registry::MaybeLock;
use crate::sources::registry::{LoadResponse, RegistryConfig, RegistryData};
use crate::util::errors::{CargoResult, HttpNo... | } else {
UNKNOWN.to_string()
};
trace!("index file version: {}", response_index_version);
return Poll::Ready(Ok(LoadResponse::Data {
raw_data: result.data,
index_versio... | format!("{}: {}", ETAG, etag)
} else if let Some(lm) = result.header_map.last_modified {
format!("{}: {}", LAST_MODIFIED, lm) | random_line_split |
http_remote.rs | //! Access to a HTTP-based crate registry. See [`HttpRegistry`] for details.
use crate::core::{PackageId, SourceId};
use crate::sources::registry::download;
use crate::sources::registry::MaybeLock;
use crate::sources::registry::{LoadResponse, RegistryConfig, RegistryData};
use crate::util::errors::{CargoResult, HttpNo... |
/// Constructs the full URL to download a index file.
fn full_url(&self, path: &Path) -> String {
// self.url always ends with a slash.
format!("{}{}", self.url, path.display())
}
/// Check if an index file of `path` is up-to-date.
///
/// The `path` argument is the same as in... | {
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 | //! Lexer implementation
use std::borrow::Cow::Borrowed;
use std::borrow::{Borrow, Cow};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use crate::char_stream::{CharStream, InputData};
use crate::error_listener::{ConsoleErrorListener, ErrorListener};
use crate::errors::ANTLRError;
use crate::int_stream::IntStream;
... |
}
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 | //! Lexer implementation
use std::borrow::Cow::Borrowed;
use std::borrow::{Borrow, Cow};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use crate::char_stream::{CharStream, InputData};
use crate::error_listener::{ConsoleErrorListener, ErrorListener};
use crate::errors::ANTLRError;
use crate::int_stream::IntStream;
... |
if self.token_type == TOKEN_INVALID_TYPE {
self.token_type = ttype;
}
if self.token_type == LEXER_SKIP {
continue 'outer;
}
if self.token_type != LEXER_MORE {
break;
... | {
self.hit_eof = true;
} | conditional_block |
lexer.rs | //! Lexer implementation
use std::borrow::Cow::Borrowed;
use std::borrow::{Borrow, Cow};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use crate::char_stream::{CharStream, InputData};
use crate::error_listener::{ConsoleErrorListener, ErrorListener};
use crate::errors::ANTLRError;
use crate::int_stream::IntStream;
... | lexer.token_start_column,
&text,
Some(e),
)
}
}
impl<'input, T, Input, TF> Lexer<'input> for BaseLexer<'input, T, Input, TF>
where
T: LexerRecog<'input, Self> + 'static,
Input: CharStream<TF::From>,
TF: TokenFactory<'input>,
{
type Input = Input;
fn ... | listener.syntax_error(
lexer,
None,
lexer.token_start_line, | random_line_split |
lexer.rs | //! Lexer implementation
use std::borrow::Cow::Borrowed;
use std::borrow::{Borrow, Cow};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use crate::char_stream::{CharStream, InputData};
use crate::error_listener::{ConsoleErrorListener, ErrorListener};
use crate::errors::ANTLRError;
use crate::int_stream::IntStream;
... | (&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 | import streamlit as st
# Base packages
import pandas as pd
import numpy as np
import datetime
import altair as alt
import matplotlib.pyplot as plt
# Find coordinates
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="myapp2")
import time
# Plot static maps
import cartopy.crs as c... |
facteur = df[['Date', 'Facteur']].dropna()
facteur['Count'] = 1
importe = facteur[facteur['Facteur'] == "Importé"].groupby("Date").sum().cumsum().reset_index()
voyage = facteur[facteur['Facteur'] == "Contact"].groupby("Date").sum().cumsum().reset_index()
communaute = facteur[facteur['Facteur'] == "Communauté"].... | 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.