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 |
|---|---|---|---|---|
main.rs |
/// easily remove all the neighbors of a vertex from a state very efficiently.
neighbors: Vec<BitSet>,
/// For each vertex 'i', the value of 'weight[i]' denotes the weight associated
/// to vertex i in the problem instance. The goal of MISP is to select the nodes
/// from the underlying graph such ... | (&self, variable: Variable, state: &Self::State, f: &mut dyn DecisionCallback) {
if state.contains(variable.id()) {
f.apply(Decision{variable, value: YES});
f.apply(Decision{variable, value: NO });
} else {
f.apply(Decision{variable, value: NO });
}
}
... | for_each_in_domain | identifier_name |
main.rs | .", | }
}
writeln_report!();
writeln_report!(r"その上で$a \leqq c, c > 0$となるような$a, c$を求める.");
writeln_report!(r"\begin{{itemize}}");
// 条件を満たす a, c を求める.
let mut res = Vec::new();
for b in bs {
let do_report = b >= 0;
if do_report {
writeln_report!(
... | if has_zero { "0$, " } else { "$" },
nonzero.format(r"$, $\pm ")
); | random_line_split |
main.rs | .",
if has_zero { "0$, " } else { "$" },
nonzero.format(r"$, $\pm ")
);
}
}
writeln_report!();
writeln_report!(r"その上で$a \leqq c, c > 0$となるような$a, c$を求める.");
writeln_report!(r"\begin{{itemize}}");
// 条件を満たす a, c を求める.
let mut res = Vec::new();
... | a,
c
);
return true;
}
let left_failure = if !(-a < b) {
format!(r"$-a < b$について${} \not< {}$", -a, b)
} else if !(b <= a) {
format!(r"$b \leqq a$について${} \not\leqq {}$", b, a)
} else if !(a < c) {
format!(r"$a < ... | writeln_report!(
r"これは右側の不等式$0 \leqq {} \leqq {} = {}$満たす.",
b,
| conditional_block |
main.rs | b, c) = $ ${:?}$.", res.iter().format("$, $"));
// 条件 (B) を確認する
fn cond(&(a, b, c): &(i64, i64, i64)) -> bool {
writeln_report!(r"\item $(a, b, c) = ({}, {}, {})$のとき \\", a, b, c);
let g = gcd(gcd(a, b), c);
if g != 1 {
writeln_report!("最大公約数が${}$となるので不適.", g);
... | rue;
| identifier_name | |
main.rs | ",
if has_zero { "0$, " } else { "$" },
nonzero.format(r"$, $\pm ")
);
}
}
writeln_report!();
writeln_report!(r"その上で$a \leqq c, c > 0$となるような$a, c$を求める.");
writeln_report!(r"\begin{{itemize}}");
// 条件を満たす a, c を求める.
let mut res = Vec::new();
... | let ac4 = b * b - disc;
if ac4 % 4 != 0 {
writeln_report!("$4ac = {}$となり,これは整数解を持たない.", ac4);
continue;
}
let ac = ac4 / 4;
writeln_report!("$4ac = {}$より$ac = {}$.", ac4, ac);
write_report!("よって$(a, c) = $");
let mut first = true;
... | b$は{}であるから,",
disc,
if disc % 2 == 0 { "偶数" } else { "奇数" }
);
let bs = ((minb + 1)..0).filter(|x| x.abs() % 2 == disc % 2);
if bs.clone().collect_vec().is_empty() {
writeln_report!(r"条件を満たす$b$はない.");
return Err("no cands".to_string());
}
writeln_report!(r"条件を満たす$b$は... | identifier_body |
csr.rs | -> usize {
self.e
}
pub fn get_offsets(&self) -> &Vec<usize> {
&self.offsets
}
pub fn get_neighbs(&self) -> &[usize] {
&self.neighbs
}
/// Build a random edge list
/// This method returns a tuple of the number of vertices seen and the edge list
/// el.len() is... |
}
/// Take an edge list in and produce a CSR out
/// (u,v)
pub fn new(numv: usize, ref el: Vec<(usize, usize)>) -> CSR {
const NUMCHUNKS: usize = 16;
let chunksz: usize = if numv > NUMCHUNKS {
numv / NUMCHUNKS
} else {
1
};
/*TODO: Para... |
/*return the graph, g*/
g | random_line_split |
csr.rs | {
v: usize,
e: usize,
vtxprop: Vec<f64>,
offsets: Vec<usize>,
neighbs: Vec<usize>,
}
impl CSR {
pub fn get_vtxprop(&self) -> &[f64] {
&self.vtxprop
}
pub fn get_mut_vtxprop(&mut self) -> &mut [f64] {
&mut self.vtxprop
}
pub fn get_v(&self) -> usize {
s... | CSR | identifier_name | |
csr.rs |
pub fn get_v(&self) -> usize {
self.v
}
pub fn get_e(&self) -> usize {
self.e
}
pub fn get_offsets(&self) -> &Vec<usize> {
&self.offsets
}
pub fn get_neighbs(&self) -> &[usize] {
&self.neighbs
}
/// Build a random edge list
/// This method re... | {
&mut self.vtxprop
} | identifier_body | |
main.rs |
null_separator: bool,
/// The maximum search depth, or `None` if no maximum search depth should be set.
///
/// A depth of `1` includes all files under the current directory, a depth of `2` also includes
/// all files under subdirectories of the current directory, etc.
max_depth: Option<usize>... |
let r = write!(&mut std::io::stdout(), "{}{}{}", prefix, path_str, separator);
if r.is_err() {
// Probably a broken pipe. Exit gracefully.
process::exit(0);
}
}
}
/// Recursively scan the given search path and search for files / pathnames matching the pattern.
fn s... | random_line_split | |
main.rs |
null_separator: bool,
/// The maximum search depth, or `None` if no maximum search depth should be set.
///
/// A depth of `1` includes all files under the current directory, a depth of `2` also includes
/// all files under subdirectories of the current directory, etc.
max_depth: Option<usize>... | else if is_directory {
&ls_colors.directory
} else if is_executable(metadata.as_ref()) {
&ls_colors.executable
} else {
// Look up file name
let o_style =
component_path.file_name()
... | {
&ls_colors.symlink
} | conditional_block |
main.rs |
null_separator: bool,
/// The maximum search depth, or `None` if no maximum search depth should be set.
///
/// A depth of `1` includes all files under the current directory, a depth of `2` also includes
/// all files under subdirectories of the current directory, etc.
max_depth: Option<usize>... | (root: &Path, pattern: Arc<Regex>, base: &Path, config: Arc<FdOptions>) {
let (tx, rx) = channel();
let walker = WalkBuilder::new(root)
.hidden(config.ignore_hidden)
.ignore(config.read_ignore)
.git_ignore(config.read_ignore)
.... | scan | identifier_name |
doc_upsert.rs | (&self) -> Signature {
Signature::build("doc upsert")
.optional("id", SyntaxShape::String, "the document id")
.optional("content", SyntaxShape::Any, "the document content")
.named(
"id-column",
SyntaxShape::String,
"the name of ... | }
if let Some(i) = id {
if let Some(c) = content {
return Some((i, c));
}
}
}
None
});
let mut all_items = vec![];
for item in filtered.chain(input_args) {
let value =
serde_json::to_... | random_line_split | |
doc_upsert.rs | self) -> Signature {
Signature::build("doc upsert")
.optional("id", SyntaxShape::String, "the document id")
.optional("content", SyntaxShape::Any, "the document content")
.named(
"id-column",
SyntaxShape::String,
"the name of th... | (
state: Arc<Mutex<State>>,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let results = run_kv_store_ops(state, engine_state, stack, call, input, build_req)?;
Ok(Value::List {
vals: results,
span: cal... | run_upsert | identifier_name |
doc_upsert.rs | self) -> Signature {
Signature::build("doc upsert")
.optional("id", SyntaxShape::String, "the document id")
.optional("content", SyntaxShape::Any, "the document content")
.named(
"id-column",
SyntaxShape::String,
"the name of th... |
fn run_upsert(
state: Arc<Mutex<State>>,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let results = run_kv_store_ops(state, engine_state, stack, call, input, build_req)?;
Ok(Value::List {
vals: results,
... | {
KeyValueRequest::Set { key, value, expiry }
} | identifier_body |
doc_upsert.rs | self) -> Signature {
Signature::build("doc upsert")
.optional("id", SyntaxShape::String, "the document id")
.optional("content", SyntaxShape::Any, "the document content")
.named(
"id-column",
SyntaxShape::String,
"the name of th... |
if k.clone() == content_column {
content = convert_nu_value_to_json_value(&v, span).ok();
}
}
if let Some(i) = id {
if let Some(c) = content {
return Some((i, c));
}
}
}
... | {
id = v.as_string().ok();
} | conditional_block |
pipeline.fromIlastik.py | circularity=","meanIntensity=","totalIntensity=","pos="])
except getopt.GetoptError as err:
# print help information and exit:
print(str(err)) # will print something like "option -a not recognized"
usage()
sys.exit(2)
print(opts)
usecols = ()
for o, a in opts:
if o in ("-i", "--input"):
fil... |
print('Topological graph ready!')
print('...the graph has '+str(A.shape[0])+' nodes')
####################################################################################################
# Select the morphological features,
# and set the min number of nodes per subgraph
# Features list:
# fov_name x_centroid y_... | random_line_split | |
pipeline.fromIlastik.py | circularity=","meanIntensity=","totalIntensity=","pos="])
except getopt.GetoptError as err:
# print help information and exit:
print(str(err)) # will print something like "option -a not recognized"
usage()
sys.exit(2)
print(opts)
usecols = ()
for o, a in opts:
if o in ("-i", "--input"):
fil... |
else:
print('The graph does not exists yet and I am going to create one...')
pos = np.loadtxt(filename, delimiter="\t",skiprows=True,usecols=(1,2))
A = space2graph(pos,nn) # create the topology graph
sparse.save_npz(path, A)
G = nx.from_scipy_sparse_matrix(A, edge_attribute='weight')
d = g... | print('The graph exists already and I am now loading it...')
A = sparse.load_npz(path)
pos = np.loadtxt(filename, delimiter="\t",skiprows=True,usecols=(1,2)) # chose x and y and do not consider header
G = nx.read_gpickle(os.path.join(dirname, basename_graph) + ".graph.pickle")
d = getdegree(G)
cc =... | conditional_block |
save_hist.py | ')
# Timing
mjd_day = t.root.I3EventHeader.col('time_start_mjd_day')
mjd_sec = t.root.I3EventHeader.col('time_start_mjd_sec')
mjd_ns = t.root.I3EventHeader.col('time_start_mjd_ns')
q['mjd'] = np.zeros(len(mjd_day), dtype=np.float64)
for i in range(len(mjd_day)):
day = int(mjd_day[i])
... | (config, file, outfile):
nside = 64
npix = hp.nside2npix(nside)
# Binning for various parameters
sbins = np.arange(npix+1, dtype=int)
ebins = np.arange(5, 9.501, 0.05)
dbins = np.linspace(0, 700, 141)
lbins = np.linspace(-20, 20, 151)
# Get desired information from hdf5 file
d = h... | skyWriter | identifier_name |
save_hist.py | .getNode('/'+filtermask).col(fname)
f[fname] = f[fname][:,0].astype(float)
filterArray = np.array([f[fname] * df.it_weights(fname)
for fname in f.keys()])
filterArray[filterArray == 0] = 100.
q['weights'] = np.amin(filterArray, axis=0)
# Other reconstruction info
q['NStations']... | weights=w[ecut])[0] | random_line_split | |
save_hist.py | = ''
for key in ['x','y','energy']:
q['ML_'+key][badVals] = np.nan
# Calculate sky positions
q['dec'], q['ra'] = getDecRA(q, verbose=False)
# Containment cut
it_geo = df.it_geo(config)
q['cuts'] = {}
q['cuts']['llh'] = inPoly(q['ML_x'], q['ML_y'], 0, config=it_geo)
return q
... | if args.sky:
skyWriter(args.config, infile, outfile)
else:
histWriter(args.config, infile, outfile) | conditional_block | |
save_hist.py | for comp in compList:
r = rDict[comp]
for value in ['x','y','energy']:
q[r+'ML_'+value] = t.getNode('/ShowerLLH_'+comp).col(value)
q[r+'LLH'] = t.getNode('/ShowerLLHParams_'+comp).col('maxLLH')
# Timing
mjd_day = t.root.I3EventHeader.col('time_start_mjd_day')
mjd_sec... | rDict = {'proton':'p','helium':'h','oxygen':'o','iron':'f'}
t1 = astro.Time()
print 'Building arrays from %s...' % file
t = tables.openFile(file)
q = {}
# Get reconstructed compositions from list of children in file
children = []
for node in t.walk_nodes('/'):
try: children += [nod... | identifier_body | |
repocachemanager.go | bool
logger log.Logger
cacheClient Client
sync.Mutex
}
func newRepoCacheManager(now time.Time,
repoID image.Name, clientFactory registry.ClientFactory, creds registry.Credentials, repoClientTimeout time.Duration,
burst int, trace bool, logger log.Logger, cacheClient Client) (*repoCacheManager, error) {
... | (ctx context.Context) ([]string, error) {
ctx, cancel := context.WithTimeout(ctx, c.clientTimeout)
defer cancel()
tags, err := c.client.Tags(ctx)
if ctx.Err() == context.DeadlineExceeded {
return nil, c.clientTimeoutError()
}
return tags, err
}
// storeRepository stores the repository from the cache
func (c *r... | getTags | identifier_name |
repocachemanager.go | bool
logger log.Logger
cacheClient Client
sync.Mutex
}
func newRepoCacheManager(now time.Time,
repoID image.Name, clientFactory registry.ClientFactory, creds registry.Credentials, repoClientTimeout time.Duration,
burst int, trace bool, logger log.Logger, cacheClient Client) (*repoCacheManager, error) {
... | if c.now.After(deadline) {
toUpdate = append(toUpdate, imageToUpdate{ref: newID, previousRefresh: excludedRefresh})
refresh++
}
}
}
}
}
result := fetchImagesResult{
imagesFound: images,
imagesToUpdate: toUpdate,
imagesToUpdateRefreshCount: refresh,
im... | } else {
if c.trace {
c.logger.Log("trace", "excluded in cache", "ref", newID, "reason", entry.ExcludedReason)
} | random_line_split |
repocachemanager.go | tags, err := c.client.Tags(ctx)
if ctx.Err() == context.DeadlineExceeded {
return nil, c.clientTimeoutError()
}
return tags, err
}
// storeRepository stores the repository from the cache
func (c *repoCacheManager) storeRepository(repo ImageRepository) error {
repoKey := NewRepositoryKey(c.repoID.CanonicalName()... | {
return fmt.Errorf("client timeout (%s) exceeded", r.clientTimeout)
} | identifier_body | |
repocachemanager.go | func (c *repoCacheManager) getTags(ctx context.Context) ([]string, error) {
ctx, cancel := context.WithTimeout(ctx, c.clientTimeout)
defer cancel()
tags, err := c.client.Tags(ctx)
if ctx.Err() == context.DeadlineExceeded {
return nil, c.clientTimeoutError()
}
return tags, err
}
// storeRepository stores the re... | {
return registry.ImageEntry{}, err
} | conditional_block | |
sdss_sqldata.py | 1], 'f_SDSS_z')
sql.rename_column(sqlc[11-1], 'e_SDSS_z')
sql['#id'] = sql['#id'].astype('str')
targets = sql['#id']
sqlc = sql.colnames
#%% FAST input
os.chdir(path_lib)
default = 'hdfn_fs99'
ftrinfo = open('FILTER.RES.latest.info', 'r').readlines() # https://github.com/gbrammer/eazy... |
# elif line.startswith('N_SIM'):
# p.write(line.replace('0', '100'))
elif line.startswith('RESOLUTION'):
p.write(line.replace("= 'hr'", "= 'lr'"))
# elif line.startswith('NO_MAX_AGE'):
# p.write(line.replace('= 0', '= 1'))
... | p.write(line.replace(default, sdssdate)) | conditional_block |
sdss_sqldata.py | 1], 'f_SDSS_z')
sql.rename_column(sqlc[11-1], 'e_SDSS_z')
sql['#id'] = sql['#id'].astype('str')
targets = sql['#id']
sqlc = sql.colnames
#%% FAST input
os.chdir(path_lib)
default = 'hdfn_fs99'
ftrinfo = open('FILTER.RES.latest.info', 'r').readlines() # https://github.com/gbrammer/eazy... |
# plt.rcParams.update({'font.size': 14})
fig, axs = plt.subplots(2, 1, figsize=(9,12))
plt.rcParams.update({'font.size': 18})
ax_Mr = axs[1]
ax_lM = ax_Mr.twinx()
# ax_Mr.set_title('SDSS DR12 Galaxies Distribution')
# automatically update ylim of ax2 when ylim of ax1 changes.
ax_Mr.callbacks.connect("ylim_change... | """
Update second axis according with first axis.
"""
y1, y2 = ax_Mr.get_ylim()
ax_lM.set_ylim(Mr2logM(y1), Mr2logM(y2))
ax_lM.figure.canvas.draw() | identifier_body |
sdss_sqldata.py | = open('FILTER.RES.latest.info', 'r').readlines() # https://github.com/gbrammer/eazy-photoz
translate = ascii.read('translate.cat') # write down manually
filters = [f for f in sqlc if f.startswith('f_')]
ftrtbl = Table()
for f in filters:
if f not in translate['filter']:
print("Warning: Filter... | ax_Mr.set_xlim(0.0075, 0.20)
ax_Mr.set_ylim(-15, -24)
ax_Mr.legend(loc='lower right')
# ax_Mr.set_title('Spectroscopically Confirmed')
ax_Mr.set_ylabel('$M_r$') | random_line_split | |
sdss_sqldata.py | 1], 'f_SDSS_z')
sql.rename_column(sqlc[11-1], 'e_SDSS_z')
sql['#id'] = sql['#id'].astype('str')
targets = sql['#id']
sqlc = sql.colnames
#%% FAST input
os.chdir(path_lib)
default = 'hdfn_fs99'
ftrinfo = open('FILTER.RES.latest.info', 'r').readlines() # https://github.com/gbrammer/eazy... | (ax_Mr):
"""
Update second axis according with first axis.
"""
y1, y2 = ax_Mr.get_ylim()
ax_lM.set_ylim(Mr2logM(y1), Mr2logM(y2))
ax_lM.figure.canvas.draw()
# plt.rcParams.update({'font.size': 14})
fig, axs = plt.subplots(2, 1, figsize=(9,12))
plt.rcParams.update({'font.size': 18})
ax_Mr = a... | convert | identifier_name |
instance.go | FlavorRef string
SystemDiskSizeGB int `json:"vdisk"`
SystemDiskId string
ServerType string
ServerVmType string
EcStatus string
BootVolumeType string
Deleted int
Visible bool
Region string
PortDetail []SInstanceNic
}
func (i *SInstance) GetBill... |
func (in *SInstance) fetchSysDisk() {
storage, _ := in.host.zone.getStorageByType(api.STORAGE_ECLOUD_SYSTEM)
disk := SDisk{
storage: storage,
ManualAttr: SDiskManualAttr{
IsVirtual: true,
TempalteId: in.ImageRef,
ServerId: in.Id,
},
SCreateTime: in.SCreateTime,
SZoneRegionBase: in.SZoneReg... | {
return nil
} | identifier_body |
instance.go | FlavorRef string
SystemDiskSizeGB int `json:"vdisk"`
SystemDiskId string
ServerType string
ServerVmType string
EcStatus string
BootVolumeType string
Deleted int
Visible bool
Region string
PortDetail []SInstanceNic
}
func (i *SInstance) GetBill... | (bc billing.SBillingCycle) error {
return cloudprovider.ErrNotImplemented
}
func (self *SInstance) GetError() error {
return nil
}
func (in *SInstance) fetchSysDisk() {
storage, _ := in.host.zone.getStorageByType(api.STORAGE_ECLOUD_SYSTEM)
disk := SDisk{
storage: storage,
ManualAttr: SDiskManualAttr{
IsVir... | Renew | identifier_name |
instance.go |
FlavorRef string
SystemDiskSizeGB int `json:"vdisk"`
SystemDiskId string
ServerType string
ServerVmType string
EcStatus string
BootVolumeType string
Deleted int
Visible bool
Region string
PortDetail []SInstanceNic
}
func (i *SInstance) GetBil... | }
func (in *SInstance) ChangeConfig(ctx context.Context, config *cloudprovider.SManagedVMChangeConfig) error {
return errors.ErrNotImplemented
}
func (in *SInstance) GetVNCInfo() (jsonutils.JSONObject, error) {
url, err := in.host.zone.region.GetInstanceVNCUrl(in.GetId())
if err != nil {
return nil, err
}
ret ... | return cloudprovider.ErrNotImplemented | random_line_split |
instance.go | ":
return api.VM_READY
case "migrating":
return api.VM_MIGRATING
case "backuping":
return api.VM_BACKUP_CREATING
default:
return api.VM_UNKNOWN
}
}
func (i *SInstance) Refresh() error {
// TODO
return nil
}
func (i *SInstance) IsEmulated() bool {
return false
}
func (self *SInstance) GetBootOrder() st... | {
nic := &in.PortDetail[i]
routerIds.Insert(nic.RouterId)
nics[nic.PortId] = nic
} | conditional_block | |
lifecycle.go | nil
}
// pumpMessages reads and decodes messages from a Journal & offset into the provided channel.
func pumpMessages(shard Shard, app Application, journal pb.Journal, offset int64, msgCh chan<- message.Envelope) error {
var spec, err = fetchJournalSpec(shard.Context(), journal, shard.JournalClient())
if err != nil... | func pickFirstHints(f fetchedHints) recoverylog.FSMHints {
for _, currHints := range f.hints {
if currHints == nil {
continue
}
return *currHints
}
return recoverylog.FSMHints{Log: f.spec.RecoveryLog()}
}
// fetchHints retrieves and decodes all FSMHints for the ShardSpec.
// Nil values will be returned wh... | // pickFirstHints retrieves the first hints from |f|. If there are no primary
// hints available the most recent backup hints will be returned. If there are
// no hints available an empty set of hints is returned. | random_line_split |
lifecycle.go | nil {
return extendErr(err, "storing recorded FSMHints")
}
return nil
}
// storeRecoveredHints writes the FSMHints into the first backup hint key of the spec,
// rotating hints previously stored under that key to the second backup hint key,
// and so on as a single transaction.
func storeRecoveredHints(shard Shar... | {
if err == nil {
panic("expected error")
} else if err == context.Canceled || err == context.DeadlineExceeded {
return err
} else if _, ok := err.(interface{ StackTrace() errors.StackTrace }); ok {
// Avoid attaching another errors.StackTrace if one is already present.
return errors.WithMessage(err, fmt.Spr... | identifier_body | |
lifecycle.go |
}
// pumpMessages reads and decodes messages from a Journal & offset into the provided channel.
func pumpMessages(shard Shard, app Application, journal pb.Journal, offset int64, msgCh chan<- message.Envelope) error {
var spec, err = fetchJournalSpec(shard.Context(), journal, shard.JournalClient())
if err != nil {
... |
for i := range out.txnResp.Responses {
var currHints recoverylog.FSMHints
if kvs := out.txnResp.Responses[i].GetResponseRange().Kvs; len(kvs) == 0 {
out.hints = append(out.hints, nil)
continue
} else if err = json.Unmarshal(kvs[0].Value, &currHints); err != nil {
err = extendErr(err, "unmarshal FSMHin... | {
err = extendErr(err, "fetching ShardSpec.HintKeys")
return
} | conditional_block |
lifecycle.go | := err.(rpctypes.EtcdError); ok && etcdErr.Code() == codes.Unavailable {
// Recorded hints are advisory and can generally tolerate omitted
// updates. It's also annoying for temporary Etcd partitions to abort
// an otherwise-fine shard primary. So, log but allow shard processing
// to continue; we'll retry on ... | extendErr | identifier_name | |
incident-sk.ts | </pre>
*
* @evt assign Sent when the user want to assign the incident to someone else.
* The detail includes the key of the incident.
*
* <pre>
* detail {
* key: "12312123123",
* }
* </pre>
*
*/
import { define } from '../../../elements-sk/modules/define';
import '../../../elements-sk/m... | (i: Incident) =>
html`<incident-sk .incident_state=${i} minimized></incident-sk>`
);
})
.catch(errorMessage); | random_line_split | |
incident-sk.ts | key: "12312123123",
* index: 0,
* }
* </pre>
*
* @evt take Sent when the user wants the incident assigned to themselves.
* The detail includes the key of the incident.
*
* <pre>
* detail {
* key: "12312123123",
* }
* </pre>
*
* @evt assign Sent when the user want to... | (val: Silence[]) {
this._render();
this.silences = val;
}
/** @prop recently_expired_silence Whether silence recently expired. */
get incident_has_recently_expired_silence(): boolean {
return this.recently_expired_silence;
}
set incident_has_recently_expired_silence(val: boolean) {
// No nee... | incident_silences | identifier_name |
incident-sk.ts | key: "12312123123",
* index: 0,
* }
* </pre>
*
* @evt take Sent when the user wants the incident assigned to themselves.
* The detail includes the key of the incident.
*
* <pre>
* detail {
* key: "12312123123",
* }
* </pre>
*
* @evt assign Sent when the user want to assig... |
private classOfH2(): string {
if (!this.state.active) {
return 'inactive';
}
if (this.state.params.assigned_to) {
return 'assigned';
}
return '';
}
private table(): TemplateResult[] {
const params = this.state.params;
const keys = Object.keys(params);
keys.sort();
... | {
// No need to render again if value is same as old value.
if (val !== this.flaky) {
this.flaky = val;
this._render();
}
} | identifier_body |
incident-sk.ts | key: "12312123123",
* index: 0,
* }
* </pre>
*
* @evt take Sent when the user wants the incident assigned to themselves.
* The detail includes the key of the incident.
*
* <pre>
* detail {
* key: "12312123123",
* }
* </pre>
*
* @evt assign Sent when the user want to assig... |
}
/** @prop flaky Whether this incident has been flaky. */
get incident_flaky(): boolean {
return this.flaky;
}
set incident_flaky(val: boolean) {
// No need to render again if value is same as old value.
if (val !== this.flaky) {
this.flaky = val;
this._render();
}
}
priva... | {
this.recently_expired_silence = val;
this._render();
} | conditional_block |
parse.go | ) {
p := newParser(input)
p.lex.seriesDesc = true
return p.parseSeriesDesc()
}
// parseSeriesDesc parses a description of a time series into its metric and value sequence.
func (p *parser) parseSeriesDesc() (m labels.Labels, vals []sequenceValue, err error) {
defer p.recover(&err)
m = p.metric()
const ctx = "... | p.errorf("expected label matching operator but got %s", op)
}
var validOp = false
for _, allowedOp := range operators { | random_line_split | |
parse.go | newParser(input)
defer p.recover(&err)
m = p.metric()
if p.peek().typ != itemEOF {
p.errorf("could not parse remaining input %.15q...", p.lex.input[p.lex.lastPos:])
}
return m, nil
}
// newParser returns a new parser.
func newParser(input string) *parser {
p := &parser{
lex: lex(input),
}
return p
}
// ... |
// Extract values.
sign := 1.0
if t := p.peek().typ; t == itemSUB || t == itemADD {
if p.next().typ == itemSUB {
sign = -1
}
}
var k float64
if t := p.peek().typ; t == itemNumber {
k = sign * p.number(p.expect(itemNumber, ctx).val)
} else if t == itemIdentifier && p.peek().val == "stale" {
... | {
p.next()
times := uint64(1)
if p.peek().typ == itemTimes {
p.next()
times, err = strconv.ParseUint(p.expect(itemNumber, ctx).val, 10, 64)
if err != nil {
p.errorf("invalid repetition in %s: %s", ctx, err)
}
}
for i := uint64(0); i < times; i++ {
vals = append(vals, sequenceValu... | conditional_block |
parse.go | newParser(input)
defer p.recover(&err)
m = p.metric()
if p.peek().typ != itemEOF {
p.errorf("could not parse remaining input %.15q...", p.lex.input[p.lex.lastPos:])
}
return m, nil
}
// newParser returns a new parser.
func newParser(input string) *parser {
p := &parser{
lex: lex(input),
}
return p
}
// ... |
var errUnexpected = fmt.Errorf("unexpected error")
// recover is the handler that turns panics into returns from the top level of Parse.
func (p *parser) recover(errp *error) {
e := recover()
if e != nil {
if _, ok := e.(runtime.Error); ok {
// Print the stack trace but do not inhibit the running application.... | {
token := p.next()
if token.typ != exp1 && token.typ != exp2 {
p.errorf("unexpected %s in %s, expected %s or %s", token.desc(), context, exp1.desc(), exp2.desc())
}
return token
} | identifier_body |
parse.go | := newParser(input)
defer p.recover(&err)
m = p.metric()
if p.peek().typ != itemEOF {
p.errorf("could not parse remaining input %.15q...", p.lex.input[p.lex.lastPos:])
}
return m, nil
}
// newParser returns a new parser.
func newParser(input string) *parser {
p := &parser{
lex: lex(input),
}
return p
}
... | (errp *error) {
e := recover()
if e != nil {
if _, ok := e.(runtime.Error); ok {
// Print the stack trace but do not inhibit the running application.
buf := make([]byte, 64<<10)
buf = buf[:runtime.Stack(buf, false)]
fmt.Fprintf(os.Stderr, "parser panic: %v\n%s", e, buf)
*errp = errUnexpected
} els... | recover | identifier_name |
mock_cr50_agent.rs | Error,
fidl_fuchsia_tpm_cr50::{
InsertLeafResponse, PinWeaverRequest, PinWeaverRequestStream, TryAuthFailed,
TryAuthRateLimited, TryAuthResponse, TryAuthSuccess,
},
fuchsia_async as fasync,
fuchsia_component::server as fserver,
fuchsia_component_test::LocalComponentHandles,
futur... |
/// Adds a successful TryAuth response.
pub(crate) fn add_try_auth_success_response(
mut self,
root_hash: Hash,
cred_metadata: Vec<u8>,
mac: Hash,
) -> Self {
let success = TryAuthSuccess {
root_hash: Some(root_hash),
cred_metadata: Some(cred... | {
self.responses.push_back(MockResponse::RemoveLeaf { root_hash });
self
} | identifier_body |
mock_cr50_agent.rs | Error,
fidl_fuchsia_tpm_cr50::{
InsertLeafResponse, PinWeaverRequest, PinWeaverRequestStream, TryAuthFailed,
TryAuthRateLimited, TryAuthResponse, TryAuthSuccess,
},
fuchsia_async as fasync,
fuchsia_component::server as fserver,
fuchsia_component_test::LocalComponentHandles,
futur... |
}
_ => {
panic!("Next mock response type was {:?} but expected TryAuth.", next_response)
}
};
}
// GetLog and LogReplay are unimplemented as testing log replay is out
// of scope for pwauth-credmgr integration tests... | {
resp.send(&mut std::result::Result::Ok(response))
.expect("failed to send response");
} | conditional_block |
mock_cr50_agent.rs | Error,
fidl_fuchsia_tpm_cr50::{
InsertLeafResponse, PinWeaverRequest, PinWeaverRequestStream, TryAuthFailed,
TryAuthRateLimited, TryAuthResponse, TryAuthSuccess,
},
fuchsia_async as fasync,
fuchsia_component::server as fserver,
fuchsia_component_test::LocalComponentHandles,
futur... | (
request: PinWeaverRequest,
next_response: MockResponse,
he_secret: &Arc<Mutex<Vec<u8>>>,
) {
// Match the next response with the request, panicking if requests are out
// of the expected order.
match request {
PinWeaverRequest::GetVersion { responder: resp } => {
match next... | handle_request | identifier_name |
mock_cr50_agent.rs | ::Error,
fidl_fuchsia_tpm_cr50::{
InsertLeafResponse, PinWeaverRequest, PinWeaverRequestStream, TryAuthFailed,
TryAuthRateLimited, TryAuthResponse, TryAuthSuccess,
},
fuchsia_async as fasync,
fuchsia_component::server as fserver,
fuchsia_component_test::LocalComponentHandles,
fut... | ),
};
}
PinWeaverRequest::RemoveLeaf { params: _, responder: resp } => {
match next_response {
MockResponse::RemoveLeaf { root_hash } => {
resp.send(&mut std::result::Result::Ok(root_hash))
.expect("faile... | }
_ => panic!(
"Next mock response type was {:?} but expected InsertLeaf.",
next_response | random_line_split |
hash_aggregator.go | // aggregation group, so we perform aggregation on each of them in turn.
// After we do so, we will have three buckets and the hash table will contain
// three tuples (with buckets and tuples corresponding to each other):
// buckets = [<bucket for -3>, <bucket for -2>, <bucket for -1>]
// ht.Vals = [-3... | {
var retErr error
if op.inputTrackingState.tuples != nil {
retErr = op.inputTrackingState.tuples.Close(ctx)
}
if err := op.toClose.Close(ctx); err != nil {
retErr = err
}
return retErr
} | identifier_body | |
hash_aggregator.go | all tuples from the
// batch will be included into one of these chains). These chains must
// be set to zero length once the batch has been processed so that the
// memory could be reused.
eqChains [][]int
// intSlice and anotherIntSlice are simply scratch int slices that are
// reused for several purpose... |
op.output.SetLength(curOutputIdx)
| {
op.state = hashAggregatorDone
} | conditional_block |
hash_aggregator.go | ([]int, numBuffered)
}
}
// onlineAgg groups all tuples in b into equality chains, then probes the
// heads of those chains against already existing groups, aggregates matched
// chains into the corresponding buckets and creates new buckets for new
// aggregation groups.
//
// Let's go through an example of how this ... | op.ht.ProbeScratch.HashBuffer[newGroupCount] = op.ht.ProbeScratch.HashBuffer[eqChainSlot]
newGroupCount++ | random_line_split | |
hash_aggregator.go | 3]
// The special "heads of equality chains" selection vector is [0, 2, 3].
// 3. we don't have any existing buckets yet, so this step is a noop.
// 4. each of the three equality chains contains tuples from a separate
// aggregation group, so we perform aggregation on each of them in turn.
// After we d... | Close | identifier_name | |
watcher.go | the
// specific language governing permissions and limitations
// under the License.
package docker
import (
"fmt"
"net/http"
"sync"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/events"
"github.com/docker/docker/api/types/filters"
"github.com/docker/go-connections/tlsconfi... | "container": container,
})
}
// Delete
if event.Action == "die" {
container := w.Container(event.Actor.ID)
if container != nil {
w.bus.Publish(bus.Event{
"stop": true,
"container": container,
})
}
w.Lock()
w.deleted[event.Actor.ID] = time.... | delete(w.deleted, event.Actor.ID)
w.Unlock()
w.bus.Publish(bus.Event{
"start": true, | random_line_split |
watcher.go | cleanupTimeout time.Duration
lastValidTimestamp int64
stopped sync.WaitGroup
bus bus.Bus
shortID bool // whether to store short ID in "containers" too
}
// Container info retrieved by the watcher
type Container struct {
ID string
Name string
Image ... | {
return w.bus.Subscribe("stop")
} | identifier_body | |
watcher.go | the
// specific language governing permissions and limitations
// under the License.
package docker
import (
"fmt"
"net/http"
"sync"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/events"
"github.com/docker/docker/api/types/filters"
"github.com/docker/go-connections/tlsconfi... |
return res
}
// Start watching docker API for new containers
func (w *watcher) Start() error {
// Do initial scan of existing containers
logp.Debug("docker", "Start docker containers scanner")
w.lastValidTimestamp = time.Now().Unix()
w.Lock()
defer w.Unlock()
containers, err := w.listContainers(types.Containe... | {
if !w.shortID || len(k) != shortIDLen {
res[k] = v
}
} | conditional_block |
watcher.go | the
// specific language governing permissions and limitations
// under the License.
package docker
import (
"fmt"
"net/http"
"sync"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/events"
"github.com/docker/docker/api/types/filters"
"github.com/docker/go-connections/tlsconfi... | () map[string]*Container {
w.RLock()
defer w.RUnlock()
res := make(map[string]*Container)
for k, v := range w.containers {
if !w.shortID || len(k) != shortIDLen {
res[k] = v
}
}
return res
}
// Start watching docker API for new containers
func (w *watcher) Start() error {
// Do initial scan of existing c... | Containers | identifier_name |
catsass.py | _ can do here is save the sys.ENVIRONMENT
by reducing print-ed waste. Mew.
returns: probably what you want
"""
return __cat_whisperer()[Cat.ASS]
# === comb() ===
def comb(cat, *brush):
"""
Filter the results of poking the cat. Takes variable
names as strings for the args.
cat:
... | """
if not catnip:
from random import randint
class BadCat(InterruptedError):
pass
if randint(1, 10) == 7:
mew = "You attempt to poke the cat but it attacks. " \
"Maybe if you gave it some catnip?"
raise BadCat(mew)
return __ca... | """
You really shouldn't be poking cats. But if you insist,
it is recommended to bring catnip as it's not unusual for
cats to attack dicks who poke them.
where:
I leave this as an exercise for the reader. But
a word of wisdom from my 1st grade teacher: never do
anything that yo... | identifier_body |
catsass.py | you_ can do here is save the sys.ENVIRONMENT
by reducing print-ed waste. Mew.
returns: probably what you want
"""
return __cat_whisperer()[Cat.ASS]
# === comb() ===
def comb(cat, *brush):
"""
Filter the results of poking the cat. Takes variable
names as strings for the args.
cat:
... | if template is None:
# Option 1
template = Template({
"Name": self.ctx,
"Vars": self.values}, 1)
# Option 2
template = Template({self.ctx: self.values}, 1)
self.template = template
if cat is None:
cat ... | self.logo_colorz = logo_colorz
# TODO Should be public
Template = namedtuple("Template", "view offset") | random_line_split |
catsass.py | _ can do here is save the sys.ENVIRONMENT
by reducing print-ed waste. Mew.
returns: probably what you want
"""
return __cat_whisperer()[Cat.ASS]
# === comb() ===
def comb(cat, *brush):
"""
Filter the results of poking the cat. Takes variable
names as strings for the args.
cat:
... | (InterruptedError):
pass
if randint(1, 10) == 7:
mew = "You attempt to poke the cat but it attacks. " \
"Maybe if you gave it some catnip?"
raise BadCat(mew)
return __cat_whisperer()[where]
# === schrodingers_cat() ===
def schrodingers_cat(peek=Fals... | BadCat | identifier_name |
catsass.py | _ can do here is save the sys.ENVIRONMENT
by reducing print-ed waste. Mew.
returns: probably what you want
"""
return __cat_whisperer()[Cat.ASS]
# === comb() ===
def comb(cat, *brush):
"""
Filter the results of poking the cat. Takes variable
names as strings for the args.
cat:
... |
return rv
highlight = color_stuffs.get('highlight')
# Customz
cat_colorz = color_stuffs.get(self.coat) or {}
logo_colorz = color_stuffs.get(self.logo_colorz) or | rv.append("".join(line)) | conditional_block |
Modules.py |
def updateScript(dbconnection):
"""
scans all rss feeds for new
"""
cursor = dbconnection.cursor()
cursor.execute("select rss, name, source from podcasts;")
rssArray = cursor.fetchall()
for rss in rssArray:
print("chekcing name " + str(rss[1]))
... | def runAutoCheck(dbConnection, maxConcurrent):
"""
runs an automatic check to see if any transcriptions need to be started or are already finished
and need to be reuploded\n\n
Needs dbConnection & an integer representing the max concurrent transcriptons that can be ran at a time\n\n
... | identifier_body | |
Modules.py | , dbID)
count += 1
except:
print("couldnt upload one at index " + str(count))
count += 1
class ParseText:
"""
This class handles parsing of two entities:
\n\tText files containing one instance of a transcribed podcast or...
\n\tnoh... | ():
"""
gets the number of runnning transcription processes
"""
try:
proc = subprocess.run("ps -Af|grep -i \"online2-wav-nnet3-latgen-faster\"", stdout=subprocess.PIPE, shell=True)
np = (len(str(proc.stdout).split("\\n")) - 3)
if(np == None):
... | numRunningProcesses | identifier_name |
Modules.py |
def updateScript(dbconnection):
"""
scans all rss feeds for new
"""
cursor = dbconnection.cursor()
cursor.execute("select rss, name, source from podcasts;")
rssArray = cursor.fetchall()
for rss in rssArray:
print("chekcing name " + str(rss[1]))... | cursor = dbConnection.cursor()
cursor.execute("UPDATE transcriptions SET pending = TRUE WHERE id = '" + str(fileContent[1]) + "';")
dbConnection.commit()
cursor.close()
url = fileContent[0]
indexID = str(fileContent[1]) # g... | conditional_block | |
Modules.py | duration, dbID)
count += 1
except:
print("couldnt upload one at index " + str(count))
count += 1
class ParseText:
"""
This class handles parsing of two entities:
\n\tText files containing one instance of a transcribed podcast or...
... | results = []
realTimeFactor = re.findall(r'Timing stats: real-time factor for offline decoding was (.*?) = ', fileContent)
results.append(realTimeFactor)
transcription = re.findall(r'utterance-id(.*?) (.*?)\n', fileContent)
transcriptionList = []
t... | random_line_split | |
preprocess.py | ",
"i'll": "i will",
"i'll've": "i will have",
"i'm": "i am",
"i've": "i have",
"isn't": "is not",
"it'd": "it had",
"it'd've": "it would have",
"it'll": "it will",
"it'll've": "it will have",
"it's": "it is",
"let's": "let us",
... | return final_string
def shortenText(text, all_words):
# print('shortenText')
count = 0
final_string = ""
try:
words = text.split()
for word in words:
word = word.lower()
if len(word) > 7:
if word in all_words:
count += 1
... | final_string = final_string[:-1]
except Exception as e:
# print("type error: " + str(e))
print("type error")
exit() | random_line_split |
preprocess.py | ",
"i'll": "i will",
"i'll've": "i will have",
"i'm": "i am",
"i've": "i have",
"isn't": "is not",
"it'd": "it had",
"it'd've": "it would have",
"it'll": "it will",
"it'll've": "it will have",
"it's": "it is",
"let's": "let us",
... | (filepath):
"""Read the CSV from disk."""
df = pd.read_csv(filepath, delimiter=',')
stop_words = ["will", "done", "goes","let", "know", "just", "put" "also",
"got", "can", "get" "said", "mr", "mrs", "one", "two", "three",
"four", "five", "i", "me", "my", "myself", "we", "our",
... | read_data | identifier_name |
preprocess.py | ",
"i'll": "i will",
"i'll've": "i will have",
"i'm": "i am",
"i've": "i have",
"isn't": "is not",
"it'd": "it had",
"it'd've": "it would have",
"it'll": "it will",
"it'll've": "it will have",
"it's": "it is",
"let's": "let us",
... |
if(flag):
final_string = final_string[:-1]
except Exception as e:
print("type error: " + str(e))
exit()
return final_string
def removePunctuationFromList(all_words):
all_words = [''.join(c for c in s if c not in string.punctuation)
for s in all_words]
# ... | final_string += word
final_string += ' '
flag = False | conditional_block |
preprocess.py | ",
"i'll": "i will",
"i'll've": "i will have",
"i'm": "i am",
"i've": "i have",
"isn't": "is not",
"it'd": "it had",
"it'd've": "it would have",
"it'll": "it will",
"it'll've": "it will have",
"it's": "it is",
"let's": "let us",
... |
def shortenText(text, all_words):
# print('shortenText')
count = 0
final_string = ""
try:
words = text.split()
for word in words:
word = word.lower()
if len(word) > 7:
if word in all_words:
count += 1
if(co... | words = text.split()
final_string = ""
flag = False
try:
for word in words:
word = word.lower()
if word not in stop_words:
final_string += word
final_string += ' '
flag = True
else:
flag = False
... | identifier_body |
lib.rs | Option<TableId>,
// A mapping of string names to the function index, filled with all exported
// functions.
name_map: HashMap<String, FunctionId>,
// The current stack pointer (global 0) and wasm memory (the stack). Only
// used in a limited capacity.
sp: i32,
mem: Vec<i32>,
scratch: ... | (&mut self, id: FunctionId, module: &Module) -> Option<&[u32]> {
self.descriptor.truncate(0);
// We should have a blank wasm and LLVM stack at both the start and end
// of the call.
assert_eq!(self.sp, self.mem.len() as i32);
self.call(id, module, &[]);
assert_eq!(self.s... | interpret_descriptor | identifier_name |
lib.rs | Option<TableId>,
// A mapping of string names to the function index, filled with all exported
// functions.
name_map: HashMap<String, FunctionId>,
// The current stack pointer (global 0) and wasm memory (the stack). Only
// used in a limited capacity.
sp: i32,
mem: Vec<i32>,
scratch: ... | for (arg, val) in local.args.iter().zip(args) {
frame.locals.insert(*arg, *val);
}
for (instr, _) in block.instrs.iter() {
frame.eval(instr);
if frame.done {
break;
}
}
self.scratch.last().cloned()
}
}
struct ... | {
let func = module.funcs.get(id);
log::debug!("starting a call of {:?} {:?}", id, func.name);
log::debug!("arguments {:?}", args);
let local = match &func.kind {
walrus::FunctionKind::Local(l) => l,
_ => panic!("can only call locally defined functions"),
... | identifier_body |
lib.rs | Option<TableId>,
// A mapping of string names to the function index, filled with all exported
// functions.
name_map: HashMap<String, FunctionId>,
// The current stack pointer (global 0) and wasm memory (the stack). Only
// used in a limited capacity.
sp: i32,
mem: Vec<i32>,
scratch: ... | impl Interpreter {
/// Creates a new interpreter from a provided `Module`, precomputing all
/// information necessary to interpret further.
///
/// Note that the `module` passed in to this function must be the same as
/// the `module` passed to `interpret` below.
pub fn new(module: &Module) -> R... | }
| random_line_split |
lib.rs | ` was found in the `module` and `None` if it was
/// not found in the `module`.
pub fn interpret_descriptor(&mut self, id: FunctionId, module: &Module) -> Option<&[u32]> {
self.descriptor.truncate(0);
// We should have a blank wasm and LLVM stack at both the start and end
// of the call... | {
let ty = self.module.types.get(self.module.funcs.get(e.func).ty());
let args = (0..ty.params().len())
.map(|_| stack.pop().unwrap())
.collect::<Vec<_>>();
self.interp.call(e.func, self.module, &args);
... | conditional_block | |
maze.rs | "FPGA" being there.
//!
//! The other approach is trying to have just nice solution for normal processors - just implement
//! properly aligned A* as pretty easy and common solutions for pathfinding. Nothing special there,
//! but on SISD arch it should behave pretty nicely (it could be probably improved by using some... | // I have feeling it is strongly suboptimal; Actually as both directions are encoded as 4
// bits, just precalculated table would be best solution
let mut min = 4;
for dir in [Self::LEFT, Self::RIGHT, Self::UP, Self::DOWN].iter() {
let mut d = *dir;
if !self.has_... | pub fn min_rotation(self, other: Self) -> usize { | random_line_split |
maze.rs | FPGA" being there.
//!
//! The other approach is trying to have just nice solution for normal processors - just implement
//! properly aligned A* as pretty easy and common solutions for pathfinding. Nothing special there,
//! but on SISD arch it should behave pretty nicely (it could be probably improved by using some
/... | {
Empty,
Wall,
/// Empty field with known distance from the start of the maze
/// It doesn't need to be the closes path - it is distance calulated using some path
Calculated(Dir, usize),
}
/// Whole maze reprezentation
pub struct Maze {
/// All fields flattened
maze: Box<[Field]>,
/// ... | Field | identifier_name |
maze.rs | FPGA" being there.
//!
//! The other approach is trying to have just nice solution for normal processors - just implement
//! properly aligned A* as pretty easy and common solutions for pathfinding. Nothing special there,
//! but on SISD arch it should behave pretty nicely (it could be probably improved by using some
/... |
/// Rotates left
pub fn left(mut self) -> Self {
let down = (self.0 & 1) << 3;
self.0 >>= 1;
self.0 |= down;
self
}
/// Rotates right
pub fn right(mut self) -> Self {
let left = (self.0 & 8) >> 3;
self.0 <<= 1;
self.0 |= left;
self.0... | {
let h = match from_x.cmp(&to_x) {
Ordering::Less => Self::LEFT,
Ordering::Greater => Self::RIGHT,
Ordering::Equal => Self::NONE,
};
let v = match from_y.cmp(&to_y) {
Ordering::Less => Self::UP,
Ordering::Greater => Self::DOWN,
... | identifier_body |
darts.js |
/*
* initialize game variables
*/
DG.prototype.init = function(){
DG.buttonEnable = true;
DG.numberPlay = 3;
DG.isEndGame = false;
DG.player1 = true;
DG.multi = 1
DG.lastScore = 0;
DG.keyPressed = 0;
DG.currentPla... | {
DG.scoreP1 = 0;
DG.scoreP2 = 0;
DG.game = 301
} | identifier_body | |
darts.js | (){
DG.scoreP1 = 0;
DG.scoreP2 = 0;
DG.game = 301
}
/*
* initialize game variables
*/
DG.prototype.init = function(){
DG.buttonEnable = true;
DG.numberPlay = 3;
DG.isEndGame = false;
DG.player1 = true;
DG.mul... | DG | identifier_name | |
darts.js | .prototype.initDarts = function(bBegin = false){
if(bBegin == true){
$(".numberPlayLeftP1")[0].innerText = DG.prototype.addFullDarts();
}else{
$(".numberPlayLeftP1")[0].innerText = "";
}
$(".numberPlayLeftP2")[0].innerText = "";
}
/*
* initialize winner buttons
* - click on yes button... | random_line_split | ||
darts.js | 3', 0.2);
DG.sampleError = new RapidSoundsSample('medias/error.wav', 0.2);
DG.sampleChangePlayer = new RapidSoundsSample('medias/changePlayer.mp3', 0.5);
DG.sampleplayer1 = new RapidSoundsSample('medias/testoo.mp3', 1);
DG.sampleplayer2 = new RapidSoundsSample('medias/rouge.low.mp3'... |
DG.lastMulti = DG.multi
DG.result = $(DG.playerResult).val();
DG.result -= (DG.multi * DG.keyMark);
DG.prototype.saveData();
// initialize multi
DG.multi = 1
if (DG.result==1){
DG.prototype.endError()
return false;
}
if (DG.result == 0){
if(DG.lastMulti =... | {
DG.lastScore = $(DG.playerResult).val() ;
} | conditional_block |
table.ts | i-core/utils/request';
interface FieldTypes {
metric: 'metric';
threshold: 'metric';
dimension: 'dimension';
dateTime: 'dateTime';
}
type LegacyType = keyof FieldTypes;
type LegacyFieldType = FieldTypes[LegacyType];
interface LegacyColumn<K extends LegacyType> {
type: K;
field?: string | ({ [T in FieldType... | columns[tableIndex] = requestColumn;
} else if (requestColumn !== undefined && tableColumn === undefined) {
// this column only exists in the request
missedRequestColumns.push(requestColumn);
}
return columns;
}, [])
.filter((c) => c); // remove skipped columns
reques... | {
if (visualization.version === 2) {
return visualization;
}
injectDimensionFields(request, naviMetadata);
const columnData: Record<string, ColumnInfo> = buildColumnInfo(request, visualization, naviMetadata);
// Rearranges request columns to match table order
const missedRequestColumns: Column[] = [];... | identifier_body |
table.ts | -core/utils/request';
interface FieldTypes {
metric: 'metric';
threshold: 'metric';
dimension: 'dimension';
dateTime: 'dateTime';
}
type LegacyType = keyof FieldTypes;
type LegacyFieldType = FieldTypes[LegacyType];
interface LegacyColumn<K extends LegacyType> {
type: K;
field?: string | ({ [T in FieldTypes... |
columns[tableIndex] = requestColumn;
} else if (requestColumn !== undefined && tableColumn === undefined) {
// this column only exists in the request
missedRequestColumns.push(requestColumn);
}
return columns;
}, [])
.filter((c) => c); // remove skipped columns
reque... | {
// If display name is custom move over to request
requestColumn.alias = tableColumn.displayName;
} | conditional_block |
table.ts | i-core/utils/request';
interface FieldTypes {
metric: 'metric';
threshold: 'metric';
dimension: 'dimension';
dateTime: 'dateTime';
}
type LegacyType = keyof FieldTypes;
type LegacyFieldType = FieldTypes[LegacyType];
interface LegacyColumn<K extends LegacyType> {
type: K;
field?: string | ({ [T in FieldType... | (request: RequestV2, naviMetadata: NaviMetadataService) {
const newColumns: RequestV2['columns'] = [];
request.columns.forEach((col) => {
const { type, field } = col;
if (type === 'dimension') {
const dimMeta = naviMetadata.getById(type, field, request.dataSource);
// get all show fields for dim... | injectDimensionFields | identifier_name |
table.ts | i-core/utils/request';
interface FieldTypes {
metric: 'metric';
threshold: 'metric';
dimension: 'dimension';
dateTime: 'dateTime';
}
type LegacyType = keyof FieldTypes;
type LegacyFieldType = FieldTypes[LegacyType];
interface LegacyColumn<K extends LegacyType> {
type: K;
field?: string | ({ [T in FieldType... | if (tableColumn === undefined || requestColumn === undefined) {
// this column does not exist in the table
return columns;
}
const { attributes } = tableColumn;
assert(
`The request column ${requestColumn.field} should have a present 'cid' field`,
requestColumn.cid !== undefined
... | // extract column attributes
const columnAttributes = Object.values(columnData).reduce((columns, columnInfo) => {
const { tableColumn, requestColumn } = columnInfo; | random_line_split |
lib.rs | : 1,
},
mip_level_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Bgra8UnormSrgb,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
});
Self {
texture,
sample_count,
}
}
pub f... |
}
pub fn resize(&mut self, device: &wgpu::Device, width: u32, height: u32) {
self.configure(
&device,
&SurfaceHandlerConfiguration {
width,
height,
sample_count: self.sample_count(),
},
);
}
pub fn con... | {
SampleCount::Single
} | conditional_block |
lib.rs | : 1,
},
mip_level_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Bgra8UnormSrgb,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
});
Self {
texture,
sample_count,
}
}
pub f... | (window: &Window) -> Self {
pollster::block_on(Self::new_async(window))
}
pub async fn new_async(window: &Window) -> Self {
let instance = wgpu::Instance::new(wgpu::Backends::PRIMARY);
let surface = unsafe { instance.create_surface(window) };
let adapter = instance
... | new | identifier_name |
lib.rs | : 1,
},
mip_level_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Bgra8UnormSrgb,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
});
Self {
texture,
sample_count,
}
}
pub f... |
pub fn create_render_pass_resources(&self) -> Result<RenderPassResources, wgpu::SurfaceError> {
Ok(RenderPassResources {
command_encoder: self.device.create_command_encoder(&Default::default()),
surface_texture: self.surface_handler.surface.get_current_frame()?.output,
... | {
self.surface_handler.multisample_state()
} | identifier_body |
lib.rs | : 1,
},
mip_level_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Bgra8UnormSrgb,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
});
Self {
texture,
sample_count,
}
}
pub f... | usage: wgpu::BufferUsages,
) -> wgpu::Buffer {
self.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(label),
contents: Self::as_buffer_contents(contents),
usage,
})
}
pub fn create_index_buffer... | fn create_buffer<T>(
&self,
label: &str,
contents: &[T], | random_line_split |
cloudLibUtils.js | ;
const BUILD_TYPES = require('../constants').BUILD_TYPES;
const SOURCE_PATH = '/var/config/rest/iapps/f5-appsvcs/packages';
const IAPP_DIR = '/var/config/rest/iapps/f5-appsvcs';
const RETRY_OPTIONS = {
retries: 5,
delay: 1000
};
const readFile = function (path) {
return new Promise((resolve, reject) => ... | (context, discoveryRpm) {
// not installed
if (typeof discoveryRpm === 'undefined') {
return Promise.resolve(true);
}
const options = {
path: '/mgmt/shared/iapp/package-management-tasks',
method: 'POST',
ctype: 'application/json',
why: 'Uninstall discovery worker'... | uninstallDiscoveryRpm | identifier_name |
cloudLibUtils.js | const RETRY_OPTIONS = {
retries: 5,
delay: 1000
};
const readFile = function (path) {
return new Promise((resolve, reject) => {
fs.readFile(path, (error, data) => {
if (error) reject(error);
else resolve(data);
});
});
};
const getIControlPromise = (context, iCo... | {
return getIsInstalled(context)
.then((isInstalled) => (isInstalled ? Promise.resolve() : install(context)));
} | identifier_body | |
cloudLibUtils.js | const log = require('../log');
const util = require('./util');
const iappUtil = require('./iappUtil');
const constants = require('../constants');
const DEVICE_TYPES = require('../constants').DEVICE_TYPES;
const BUILD_TYPES = require('../constants').BUILD_TYPES;
const SOURCE_PATH = '/var/config/rest/iapps/f5-appsvcs/p... | const semver = require('semver');
const promiseUtil = require('@f5devcentral/atg-shared-utilities').promiseUtils; | random_line_split | |
cloudLibUtils.js | ;
const BUILD_TYPES = require('../constants').BUILD_TYPES;
const SOURCE_PATH = '/var/config/rest/iapps/f5-appsvcs/packages';
const IAPP_DIR = '/var/config/rest/iapps/f5-appsvcs';
const RETRY_OPTIONS = {
retries: 5,
delay: 1000
};
const readFile = function (path) {
return new Promise((resolve, reject) => ... |
return response;
});
};
const install = function (context) {
log.info('Installing service discovery worker');
return Promise.resolve()
.then(() => getDiscoveryRpm(context, 'packageName'))
.then((discoveryRpmName) => uninstallDiscoveryRpm(context, discoveryRpmName))
... | {
throw new Error(`${failureMessage}: ${response.statusCode}`);
} | conditional_block |
ad_grabber_util.py | _to_visit = training_sites[train_category]
with open(os.path.join(export_folder, 'session_info.csv'), 'w') as fwtr:
fwtr.write('session_str : %s\n' % session_date)
fwtr.write('machine_info : %s\n' % machineid)
fwtr.write('vmid : %s\n' % vmid)
fwtr.write('profile : %s\n' % profile)
fwtr.write('tra... | output_dir = args[0]
saved_file_name = args[1]
path = args[2]
bug = args[3]
curl_result_queue = args[4]
# subprocess.call(['curl', '-o', path , bug.get_src() ])
subprocess.call(['wget', '-t', '1', '-q', '-T', '3', '-O', path , bug.get_src()])
# Use the unix tool 'file' to check filetype
subpr_out = subp... | identifier_body | |
ad_grabber_util.py |
try:
bug.set_dimension(height, width)
dimension = '%s-%s' % (height, width)
# check all the images in the bin with the dimensions
m_list = target_bin[dimension]
dup = None
for m in m_list:
if check_duplicat... | target_bin = img_bin
LOG.debug(bug_filepath)
try:
height = subprocess.check_output(['identify', '-format', '"%h"',\
bug_filepath]).strip()
width = subprocess.check_output(['identify', '-format','"%w"',\
bug_filepath]).st... | conditional_block | |
ad_grabber_util.py | (session_results):
"""
i) Identify duplicate ads
ii) bin the ads by their dimensions
iii) Keep track of the test sites and have many times they have displayed this
ad
"""
# bin by dimensions
ads = {}
notads = {}
swf_bin = {}
img_bin = {}
error_bugs = []
for train_category, cat_dict in session_... | identify_uniq_ads | identifier_name | |
ad_grabber_util.py | , if
# exists
try:
# separate the non-ads from the ads for ease of handchecking
os.makedirs(output_dir)
os.makedirs(os.path.join(output_dir, 'notad'))
except OSError:
pass
# uses a pool of 'curl' workers
curl_worker_pool = Pool(processes=num_of_workers)
manager = Manager()
c... | # send stop signal
input_queue.put(("STOP",)) | random_line_split | |
model.go | as assigned by the scheduler
// internally.
CronID int64 `gorm:"column:cron_id"`
// CronExpression specifies the scheduling of the job.
CronExpression string `gorm:"column:cron_expression"`
// Paused specifies whether this rawJob has been paused.
Paused bool `gorm:"column:paused"`
// CreatedAt specifies when th... | {
return err
} | conditional_block | |
model.go | added to the scheduler.
func (j *Job) CreatedAt() time.Time {
return j.createdAt
}
// UpdatedAt returns the last time this Job has been updated, i.e.,
// paused, resumed, schedule changed.
func (j *Job) UpdatedAt() time.Time {
return j.updatedAt
}
// Paused returns whether this Job is currently paused
// or not.
f... | (jobs []JobWithSchedule) []int64 {
ids := make([]int64, len(jobs))
for i, job := range jobs {
ids[i] = job.rawJob.ID
}
return ids
}
// getIdsFrom | getIdsFromJobsWithScheduleList | identifier_name |
model.go | added to the scheduler.
func (j *Job) CreatedAt() time.Time {
return j.createdAt
}
// UpdatedAt returns the last time this Job has been updated, i.e.,
// paused, resumed, schedule changed.
func (j *Job) UpdatedAt() time.Time {
return j.updatedAt
}
// Paused returns whether this Job is currently paused
// or not.
f... | run: j.Job,
runInput: CronJobInput{
JobID: j.ID,
GroupID: j.GroupID,
SuperGroupID: j.SuperGroupID,
OtherInputs: j.JobInput,
CronExpression: j.CronExpression,
},
}
return result, nil
}
// RawJob models a raw rawJob coming from the database.
type RawJob struct {
// ID is... | },
schedule: schedule, | random_line_split |
model.go | to the scheduler.
func (j *Job) CreatedAt() time.Time {
return j.createdAt
}
// UpdatedAt returns the last time this Job has been updated, i.e.,
// paused, resumed, schedule changed.
func (j *Job) UpdatedAt() time.Time {
return j.updatedAt
}
// Paused returns whether this Job is currently paused
// or not.
func (j... |
// ToJobWithSchedule returns a JobWithSchedule object from the current RawJob,
// by copy. It returns errors in case the given schedule is not valid,
// or in case the conversion of the rawJob interface/input fails.
// It does NOT copy the byte arrays from j.
func (j *RawJob) ToJobWithSchedule() (JobWithSchedule, err... | {
job, jobInput, err := j.decodeSerializedFields()
if err != nil {
return Job{}, err
}
result := Job{
ID: j.ID,
GroupID: j.GroupID,
SuperGroupID: j.SuperGroupID,
cronID: j.CronID,
CronExpression: j.CronExpression,
paused: j.Paused,
createdAt: j.CreatedAt,
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.