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
helper.go
/* Copyright 2019 The Machine Controller 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 to in w...
return true, nil }) if err != nil { return nil, err } for _, f := range allFlavors { if f.Name == c.Flavor { return &f, nil } } return nil, errNotFound } func getSecurityGroup(client *gophercloud.ProviderClient, region, name string) (*ossecuritygroups.SecGroup, error) { netClient, err := goopenstac...
} allFlavors = append(allFlavors, flavors...)
random_line_split
helper.go
/* Copyright 2019 The Machine Controller 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 to in w...
allFIPs, err := osfloatingips.ExtractFloatingIPs(allPages) if err != nil { return nil, err } var freeFIPs []osfloatingips.FloatingIP for _, f := range allFIPs { // See some details about this test here: // https://github.com/kubermatic/machine-controller/pull/28#discussion_r163773619 // The check of Fix...
{ return nil, err }
conditional_block
helper.go
/* Copyright 2019 The Machine Controller 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 to in w...
(netClient *gophercloud.ServiceClient, nameOrID string) (*osnetworks.Network, error) { allNetworks, err := getNetworks(netClient) if err != nil { return nil, err } for _, n := range allNetworks { if n.Name == nameOrID || n.ID == nameOrID { return &n, nil } } return nil, errNotFound } func getSubnets(n...
getNetwork
identifier_name
helper.go
/* Copyright 2019 The Machine Controller 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 to in w...
func getAvailabilityZone(computeClient *gophercloud.ServiceClient, c *Config) (*osavailabilityzones.AvailabilityZone, error) { zones, err := getAvailabilityZones(computeClient) if err != nil { return nil, err } for _, z := range zones { if z.ZoneName == c.AvailabilityZone { return &z, nil } } return ...
{ allPages, err := osavailabilityzones.List(computeClient).AllPages() if err != nil { return nil, err } return osavailabilityzones.ExtractAvailabilityZones(allPages) }
identifier_body
get_cdips_lc_stats.py
""" * get simple rms vs mag stats for CDIPS LCs * plot them. * assess how many all-nan LCs there are. * move allnan light curves to a graveyard directory to collect dust * supplement the statsfile by matching against Gaia DR2 and CDIPS catalogs. usage: $ (cdips) python -u get_cdips_lc_stats.py |& tee logs/s6_stat...
statsdir = join(projdir, 'results', 'cdips_lc_stats', f'sector-{sector}') if not os.path.exists(statsdir): os.mkdir(statsdir) statsfile = os.path.join(statsdir,'cdips_lc_statistics.txt') stats = ap.read_stats_file(statsfile, fovcathasgaiaids=True) N_lcs = len(stats) print('CDIPS LIGHTCURVES ...
projdir = "/ar1/PROJ/luke/proj/cdips" lcdirectory = f'/ar1/PROJ/luke/proj/CDIPS_LCS/sector-{sector}/' catdir = '/ar1/local/cdips/catalogs/'
conditional_block
get_cdips_lc_stats.py
""" * get simple rms vs mag stats for CDIPS LCs * plot them. * assess how many all-nan LCs there are. * move allnan light curves to a graveyard directory to collect dust * supplement the statsfile by matching against Gaia DR2 and CDIPS catalogs. usage: $ (cdips) python -u get_cdips_lc_stats.py |& tee logs/s6_stat...
def print_metadata_stats(sector=6, filesystem=None): """ how many LCs? how many all nan LCs? """ assert isinstance(filesystem, str) if filesystem in ['phtess2', 'php1']: fs = f"/nfs/{filesystem}" projdir = f'{fs}/ar0/TESS/PROJ/lbouma/cdips' lcdirectory = f'/nfs/phtes...
""" add crossmatching info per line: * all gaia mags. also gaia extinction and parallax. (also parallax upper and lower bounds). * calculated T mag from TICv8 relations * all the gaia info (especially teff, rstar, etc if available. but also position ra,dec and x,y, for sky-map pl...
identifier_body
get_cdips_lc_stats.py
""" * get simple rms vs mag stats for CDIPS LCs * plot them. * assess how many all-nan LCs there are. * move allnan light curves to a graveyard directory to collect dust * supplement the statsfile by matching against Gaia DR2 and CDIPS catalogs. usage: $ (cdips) python -u get_cdips_lc_stats.py |& tee logs/s6_stat...
( cdipssource_vnum=None, sector=6, filesystem=None): """ add crossmatching info per line: * all gaia mags. also gaia extinction and parallax. (also parallax upper and lower bounds). * calculated T mag from TICv8 relations * all the gaia info (especially teff, rstar, etc i...
supplement_stats_file
identifier_name
get_cdips_lc_stats.py
""" * get simple rms vs mag stats for CDIPS LCs * plot them. * assess how many all-nan LCs there are. * move allnan light curves to a graveyard directory to collect dust * supplement the statsfile by matching against Gaia DR2 and CDIPS catalogs. usage: $ (cdips) python -u get_cdips_lc_stats.py |& tee logs/s6_stat...
(stats['ndet_rm3']==0) ) nanobjs = stats[sel]['lcobj'] lcdirectory = join(lcdirectory, "cam?_ccd?") lcnames = [( 'hlsp_cdips_tess_ffi_' 'gaiatwo{zsourceid}-{zsector}-cam{cam}-ccd{ccd}_' 'tess_v{zcdipsvnum}_llc.fits' ).format( cam='?', ccd...
sel = ( (stats['ndet_rm1']==0) & (stats['ndet_rm2']==0) &
random_line_split
lane-finder.py
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from glob import glob from moviepy.editor import VideoFileClip output_images_dir = './output_images/' test_images_dir = './test_images/' output_video_file = 'output.mp4' mtx = None dist = None def load_image(filename): ...
def undistort(img): return cv2.undistort(img, mtx, dist, None, mtx) def abs_sobel_thresh(img, orient='x', sobel_kernel=3, thresh=(0, 255)): gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) if orient == 'x': abs_sobel = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)) if orient =...
mpimg.imsave(output_images_dir + filename, img, cmap=cmap)
identifier_body
lane-finder.py
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from glob import glob from moviepy.editor import VideoFileClip output_images_dir = './output_images/' test_images_dir = './test_images/' output_video_file = 'output.mp4' mtx = None dist = None def
(filename): return mpimg.imread(filename) def calibrate_camera(rows=6, cols=9): mtx = None dist = None save_file = 'calibration.npz' try: data = np.load(save_file) mtx = data['mtx'] dist = data['dist'] print('using saved calibration') except FileNotFoundError: ...
load_image
identifier_name
lane-finder.py
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from glob import glob from moviepy.editor import VideoFileClip output_images_dir = './output_images/' test_images_dir = './test_images/' output_video_file = 'output.mp4' mtx = None dist = None def load_image(filename): ...
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None) if ret: for f in filenames: img = load_image(f) undist = cv2.undistort(img, mtx, dist, None, mtx) save_output_image(undist, 'undistorted-'...
imgpoints.append(corners) objpoints.append(objp)
conditional_block
lane-finder.py
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from glob import glob from moviepy.editor import VideoFileClip output_images_dir = './output_images/' test_images_dir = './test_images/' output_video_file = 'output.mp4' mtx = None dist = None def load_image(filename): ...
y_base = int(image.shape[0] - window_height/2) # Add what we found for the first layer y_center = y_base left_centroids.append((l_center, y_center)) right_centroids.append((r_center, y_center)) # Go through each layer looking for max pixel locations for level in range(1,(int)(image.shape[0...
r_sum = np.sum(image[int(3*image.shape[0]/4):,int(image.shape[1]/2):], axis=0) r_center = np.argmax(np.convolve(window,r_sum))-window_width/2+int(image.shape[1]/2)
random_line_split
main.rs
use std::convert::TryInto; use std::str::FromStr; use anyhow::{anyhow, Context, Result}; use clap::{ArgEnum, Clap}; use gloryctl::macros::Event; use gloryctl::{rgb::Effect, ButtonAction, Color, DpiValue, GloriousDevice}; #[derive(Clap)] pub struct Opts { #[clap(subcommand)] cmd: Command, } #[derive(Clap)] e...
} Rgb::Tail { speed, brightness } => { conf.rgb_current_effect = Effect::Tail; if let Some(spd) = speed { conf.rgb_effect_parameters.tail.speed = spd.into(); } if let Some(br) = brightness { ...
{ conf.rgb_effect_parameters.breathing.count = colors.len().try_into()?; for (i, c) in colors.iter().enumerate() { conf.rgb_effect_parameters.breathing.colors[i] = *c; } }
conditional_block
main.rs
use std::convert::TryInto; use std::str::FromStr; use anyhow::{anyhow, Context, Result}; use clap::{ArgEnum, Clap}; use gloryctl::macros::Event; use gloryctl::{rgb::Effect, ButtonAction, Color, DpiValue, GloriousDevice}; #[derive(Clap)] pub struct Opts { #[clap(subcommand)] cmd: Command, } #[derive(Clap)] e...
(s: &str) -> Result<Self, Self::Err> { let (btn, act) = s .split_once(':') .context("Format: button:action-type[:action-params]")?; let which = usize::from_str(btn)?; let action = ButtonAction::from_str(act)?; Ok(Self { which, action }) } } #[derive(Clap)] #[...
from_str
identifier_name
main.rs
use std::convert::TryInto; use std::str::FromStr; use anyhow::{anyhow, Context, Result}; use clap::{ArgEnum, Clap}; use gloryctl::macros::Event; use gloryctl::{rgb::Effect, ButtonAction, Color, DpiValue, GloriousDevice}; #[derive(Clap)] pub struct Opts { #[clap(subcommand)] cmd: Command, } #[derive(Clap)] e...
} } impl Macro { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { if self.bank > 3 { return Err(anyhow!( r"Only 2 macro banks are supported for now, TODO find out how many the hardware supports without bricking it" )); } dev...
conf.fixup_dpi_metadata(); dev.send_config(&conf)?; Ok(())
random_line_split
pickup-search.component.ts
import { Component, Input, Output, ViewEncapsulation, EventEmitter } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { Subject } from 'rxjs/Subject'; import { map } from 'rxjs/operators/map'; import { Observable } from 'rxjs/Observable'; import { Subscription } from "rxj...
(po: PickupSearchDto) { let retval = {}; let array = pickupDownloadFields; for (let col of array) { if (po.hasOwnProperty(col.field)) { let val = po[col.field]; if (col.field === 'createdTS') { retval[col.field] = this.dateFormatPipe.transformDate(val); } else { ...
constructExportRow
identifier_name
pickup-search.component.ts
import { Component, Input, Output, ViewEncapsulation, EventEmitter } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { Subject } from 'rxjs/Subject'; import { map } from 'rxjs/operators/map'; import { Observable } from 'rxjs/Observable'; import { Subscription } from "rxj...
} // implement abstract method - setDefaultDisplayedColumns setDefaultDisplayedColumns() { if (!this.displayedColumns || this.displayedColumns.length === 0) { let searchView = this.selectedView; if (PickupSearchDefaultColumnsMap.has(searchView)) { this.displayedColumns = PickupSearchDefa...
{ filterRangeResults[1].forEach((saleEvent: AidAutoCompleteSearchDto, index) => { this.eventListInSite.push({ id: Number(saleEvent.value), name: saleEvent.description }); }); }
conditional_block
pickup-search.component.ts
import { Component, Input, Output, ViewEncapsulation, EventEmitter } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { Subject } from 'rxjs/Subject'; import { map } from 'rxjs/operators/map'; import { Observable } from 'rxjs/Observable'; import { Subscription } from "rxj...
/* ====================================================================== */ /* EXPORT DATA TO EXCEL - START */ exportToExcel() { this.dialogService.showProgress(); let searchQuery = this.dataSource.getCurrentSearchCriteria(this.searchGroupFieldName, this.searchGroupFieldId, 0).getSearchCriteriaString...
{ if (this.search) { this.dataSource.requestGlobalSearchFilter(this.search); this.queryService.addGlobalSearchFilterValue(this.search); } this.callSearchAPI(); }
identifier_body
pickup-search.component.ts
import { Component, Input, Output, ViewEncapsulation, EventEmitter } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { Subject } from 'rxjs/Subject'; import { map } from 'rxjs/operators/map'; import { Observable } from 'rxjs/Observable'; import { Subscription } from "rxj...
url = isNewTab ? this.appMainState.linkSet.get(PickupLinkType.eventPickupDetailOnNewTab.toString()) : this.appMainState.linkSet.get(PickupLinkType.eventPickupDetail.toString()); } else { url = isNewTab ? this.appMainState.linkSet.get(PickupLinkType.sitePickupDetailOnNewTab.toString()) : this.appMainStat...
} getGoToLink(orderNumber: number, isNewTab: boolean) { let url: string; if (this.appMainState.eventId && this.appMainState.eventId !== undefined && this.appMainState.eventId > 0) {
random_line_split
bootit2.py
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # vim: ts=4 sts=4 sw=4 tw=100 sta et __author__ = 'Patrick Butler' __email__ = 'pbutler@killertux.org' import argparse import fcntl import logging import os from pathlib import Path import shutil import subprocess as sp import sys logging.basicConfig(level=logging.INFO...
else: Cmd("{} install {}".format(prefix, " ".join(needed))) else: logging.info("No pkgs from {} needed".format(prefix)) # def main(args): # commands = {} # for name, var in globals().items(): # if name == "Command": # continue # if i...
Cmd("{} {}".format(prefix, " ".join(needed)))
conditional_block
bootit2.py
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # vim: ts=4 sts=4 sw=4 tw=100 sta et __author__ = 'Patrick Butler' __email__ = 'pbutler@killertux.org' import argparse import fcntl import logging import os from pathlib import Path import shutil import subprocess as sp import sys logging.basicConfig(level=logging.INFO...
: state = [] @classmethod def push_state(cls, bootit): cls.state += [bootit] @classmethod def pop_state(cls): cls.state.pop() @classmethod def cur_state(cls): if cls.state: return cls.state[-1] else: return None class BootIt: d...
BootItState
identifier_name
bootit2.py
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # vim: ts=4 sts=4 sw=4 tw=100 sta et __author__ = 'Patrick Butler' __email__ = 'pbutler@killertux.org' import argparse import fcntl import logging import os from pathlib import Path import shutil import subprocess as sp import sys logging.basicConfig(level=logging.INFO...
class Chmod(Command): def do(self, name, mode): name = Path(name).expanduser() if name.exists(): logging.info("Chmodding dir {}".format(name)) if not self.state.dry_run: name.chmod(int(mode, 8)) else: raise BootItException("No file to ch...
name = Path(name).expanduser() if not name.exists(): logging.info("Making dir {}".format(name)) if not self.state.dry_run: name.mkdir(int(mode, 8), parents=True) Chmod(name, mode)
identifier_body
bootit2.py
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # vim: ts=4 sts=4 sw=4 tw=100 sta et __author__ = 'Patrick Butler' __email__ = 'pbutler@killertux.org' import argparse import fcntl import logging import os from pathlib import Path import shutil import subprocess as sp import sys logging.basicConfig(level=logging.INFO...
# evaluator.start(options.conf_file) # # os.chdir(curdir) # return 0 # # # if __name__ == "__main__": # sys.exit(main(sys.argv))
# # evaluator = Evaluator(commands, options.dry_run)
random_line_split
jwxt.js
const req = require('./req') const utils = require('./utils'); const resModel = require('../config/resModel') require('tls').DEFAULT_MIN_VERSION = 'TLSv1'; // 兼容教务系统TLS1.1 // 进行登录并在返回值携带cookies exports.doLogin = async (username, password) => { const url = `xk/LoginToXk`; const datas = { encoded: utils.encode...
case 302: // 登录成功,302是因为需要跳转到主界面,此时cookies有效 return { ret: true, data: cookies }; case 200: // 跳转回登录页,证明出现了登录错误,捕获错误类型 const regErrMsg = /<font style="display: inline;white-space:nowrap;" color="red">([^<]*?)<\/font\>/gi; return { ret: false, co...
const cookies = loginRes.headers['set-cookie'][0]; switch (loginRes.statusCode) {
random_line_split
jwxt.js
const req = require('./req') const utils = require('./utils'); const resModel = require('../config/resModel') require('tls').DEFAULT_MIN_VERSION = 'TLSv1'; // 兼容教务系统TLS1.1 // 进行登录并在返回值携带cookies exports.doLogin = async (username, password) => { const url = `xk/LoginToXk`; const datas = { encoded: utils.encode...
weekArr.push(i); } } } }) courseOutObj.week = weekArr; } // 解析上课节次 const courseSessionText = courseOutObj.session_text; if (courseSessionText) { if (courseSessionText.indexOf('-') === -1) { // 单节课程 courseOutObj.session_start = pa...
if (isWeekLeagl(i)) {
conditional_block
settings.py
""" Django settings for magnify project. """ import json import os from django.utils.translation import gettext_lazy as _ # pylint: disable=ungrouped-imports import sentry_sdk from configurations import Configuration, values from sentry_sdk.integrations.django import DjangoIntegration from magnify.apps.core.settings...
class Build(Base): """Build environment settings""" SECRET_KEY = "ThisIsAnExampleKeyForBuildPurposeOnly" # nosec JWT_JITSI_SECRET_KEY = "ThisIsAnExampleKeyForBuildPurposeOnly" # nosec STORAGES = { "staticfiles": { "BACKEND": str( values.Value("whitenoise.storage...
entry_sdk.init( # pylint: disable=abstract-class-instantiated dsn=cls.SENTRY_DSN, environment=cls._get_environment(), release=get_release(), integrations=[DjangoIntegration()], ) with sentry_sdk.configure_scope() as scope: ...
conditional_block
settings.py
""" Django settings for magnify project. """ import json import os from django.utils.translation import gettext_lazy as _ # pylint: disable=ungrouped-imports import sentry_sdk from configurations import Configuration, values from sentry_sdk.integrations.django import DjangoIntegration from magnify.apps.core.settings...
class Build(Base): """Build environment settings""" SECRET_KEY = "ThisIsAnExampleKeyForBuildPurposeOnly" # nosec JWT_JITSI_SECRET_KEY = "ThisIsAnExampleKeyForBuildPurposeOnly" # nosec STORAGES = { "staticfiles": { "BACKEND": str( values.Value("whitenoise.storage...
"" This is the base configuration every configuration (aka environnement) should inherit from. It is recommended to configure third-party applications by creating a configuration mixins in ./configurations and compose the Base configuration with those mixins. It depends on an environment variable that ...
identifier_body
settings.py
""" Django settings for magnify project. """ import json import os from django.utils.translation import gettext_lazy as _ # pylint: disable=ungrouped-imports import sentry_sdk from configurations import Configuration, values from sentry_sdk.integrations.django import DjangoIntegration from magnify.apps.core.settings...
Base): """ Development environment settings We set DEBUG to True and configure the server to respond from all hosts. """ DEBUG = True ALLOWED_HOSTS = ["*"] CORS_ALLOW_ALL_ORIGINS = True CSRF_TRUSTED_ORIGINS = ["http://localhost:8071"] @classmethod def post_setup(cls): ...
evelopment(
identifier_name
settings.py
""" Django settings for magnify project. """ import json import os from django.utils.translation import gettext_lazy as _ # pylint: disable=ungrouped-imports import sentry_sdk from configurations import Configuration, values from sentry_sdk.integrations.django import DjangoIntegration from magnify.apps.core.settings...
"formatter": "verbose", } }, "loggers": { "django.db.backends": { "level": "ERROR", "handlers": ["console"], "propagate": False, } }, } # Cache CACHES = { "default": { ...
"class": "logging.StreamHandler",
random_line_split
intergen.ts
import * as fs from 'fs' import * as ts from 'typescript' import {argparse, arg} from '@rondo.dev/argparse' import {error, info} from '../log' function isObjectType(type: ts.Type): type is ts.ObjectType { return !!(type.flags & ts.TypeFlags.Object) } function isTypeReference(type: ts.ObjectType): type is ts.TypeRef...
if (symbol && symbol.flags & ts.SymbolFlags.Transient) { debug(' is transient') // Array is transient. not sure if this is the best way to figure this return false } // if (symbol && !((symbol as any).parent)) { // // debug(' no parent', symbol) // // e.g. Arra...
{ debug(' no symbol') // e.g. string or number types have no symbol return false }
conditional_block
intergen.ts
import * as fs from 'fs' import * as ts from 'typescript' import {argparse, arg} from '@rondo.dev/argparse' import {error, info} from '../log' function isObjectType(type: ts.Type): type is ts.ObjectType { return !!(type.flags & ts.TypeFlags.Object) } function isTypeReference(type: ts.ObjectType): type is ts.TypeRef...
const interfaces = classesToInterfaces([args.input], { target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS, }) const header = '/* This file was generated by rondo intergen script */\n' + '/* tslint:disable */\n\n' const value = header + interfaces.join('\n\n') if (args.output === '-') {...
{ // Build a program using the set of root file names in fileNames const program = ts.createProgram(fileNames, options) // Get the checker, we will use it to find more about classes const checker = program.getTypeChecker() const classDefs: ClassDefinition[] = [] function typeToString(type: ts...
identifier_body
intergen.ts
import * as fs from 'fs' import * as ts from 'typescript' import {argparse, arg} from '@rondo.dev/argparse' import {error, info} from '../log' function isObjectType(type: ts.Type): type is ts.ObjectType { return !!(type.flags & ts.TypeFlags.Object) } function isTypeReference(type: ts.ObjectType): type is ts.TypeRef...
(type: ts.Type): ts.Type[] { function collectTypeParams( type2: ts.Type, params?: readonly ts.Type[], ): ts.Type[] { const types: ts.Type[] = [type2] if (params) { params.forEach(t => { const atp = getAllTypeParameters(t) types.push(...atp) ...
getAllTypeParameters
identifier_name
intergen.ts
import * as fs from 'fs' import * as ts from 'typescript' import {argparse, arg} from '@rondo.dev/argparse' import {error, info} from '../log' function isObjectType(type: ts.Type): type is ts.ObjectType { return !!(type.flags & ts.TypeFlags.Object) } function isTypeReference(type: ts.ObjectType): type is ts.TypeRef...
optional, } }) const relevantTypeParameters = expandedTypeParameters .filter(filterGlobalTypes) .filter(mapGenericTypes) .filter(filterDuplicates) allRelevantTypes.push(...relevantTypeParameters) const classDef: ClassDefinition = { name: typeToStrin...
typeString: typeToString(propType),
random_line_split
Project.ts
import * as fs from 'fs-extra'; import * as path from 'path'; import * as log from './log'; import {GraphicsApi} from './GraphicsApi'; import {Architecture} from './Architecture'; import {AudioApi} from './AudioApi'; import {VrApi} from './VrApi'; import {RayTraceApi} from './RayTraceApi'; import {Options} from...
} addDefine(value: string, config: string = null) { const define = {value, config}; if (containsDefine(this.defines, define)) return; this.defines.push(define); } addDefines() { for (let i = 0; i < arguments.length; ++i) { this.addDefine(arguments[i]); } } addIncludeDir(include: st...
{ this.addExclude(arguments[i]); }
conditional_block
Project.ts
import * as fs from 'fs-extra'; import * as path from 'path'; import * as log from './log'; import {GraphicsApi} from './GraphicsApi'; import {Architecture} from './Architecture'; import {AudioApi} from './AudioApi'; import {VrApi} from './VrApi'; import {RayTraceApi} from './RayTraceApi'; import {Options} from...
addLib(lib: string) { this.libs.push(lib); } addLibs() { for (let i = 0; i < arguments.length; ++i) { this.addLib(arguments[i]); } } addLibFor(system: string, lib: string) { if (this.systemDependendLibraries[system] === undefined) this.systemDependendLibraries[system] = []; this.syst...
{ for (let i = 0; i < arguments.length; ++i) { this.addIncludeDir(arguments[i]); } }
identifier_body
Project.ts
import * as fs from 'fs-extra'; import * as path from 'path'; import * as log from './log'; import {GraphicsApi} from './GraphicsApi'; import {Architecture} from './Architecture'; import {AudioApi} from './AudioApi'; import {VrApi} from './VrApi'; import {RayTraceApi} from './RayTraceApi'; import {Options} from...
{ value: string; config: string; } export class Project { static platform: string; static koreDir: string; static root: string; name: string; safeName: string; version: string; id: string; debugDir: string; basedir: string; uuid: string; files: File[]; javadirs: string[]; subProjects:...
Define
identifier_name
Project.ts
import * as fs from 'fs-extra'; import * as path from 'path'; import * as log from './log'; import {GraphicsApi} from './GraphicsApi'; import {Architecture} from './Architecture'; import {AudioApi} from './AudioApi'; import {VrApi} from './VrApi'; import {RayTraceApi} from './RayTraceApi'; import {Options} from...
// push library properties to current array instead else if (Array.isArray(options[key]) && Array.isArray(option)) { for (let value of option) { if (!options[key].includes(value)) options[key].push(value); } } } } for (let d of sub.defines) if (!containsDefine(this....
const target = sub.targetOptions[tkey]; for (let key of Object.keys(target)) { const options = this.targetOptions[tkey]; const option = target[key]; if (options[key] == null) options[key] = option;
random_line_split
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry ...
y) bool { ok := rf.peers[server].Call("Raft.AppendEntries", args, reply) return ok } func (rf *Raft) updateCommitIndex() { rf.matchIndex[rf.me] = len(rf.log) - 1 copyMatchIndex := make([]int, len(rf.matchIndex)) copy(copyMatchIndex, rf.matchIndex) sort.Sort(sort.Reverse(sort.IntSlice(copyMatchIndex))) //sort.I...
AppendEntriesRepl
identifier_name
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry ...
} if args.Term < rf.currentTerm { return } index := args.PrevLogIndex for i := 0; i < len(args.Entries); i++ { index++ if index < logSize { if rf.log[index].Term == args.Entries[i].Term { continue } else { //3. If an existing entry conflicts with a new one (same index but different terms), rf...
} } return
random_line_split
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry ...
f.getPrevLogIdx(i) if prevLogIdx < 0 { return -1 } return rf.log[prevLogIdx].Term } func (rf *Raft) sendAppendEntries(server int, args *AppendEntriesArgs, reply *AppendEntriesReply) bool { ok := rf.peers[server].Call("Raft.AppendEntries", args, reply) return ok } func (rf *Raft) updateCommitIndex() { rf.match...
m(i int) int { prevLogIdx := r
identifier_body
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry ...
0; i < len(rf.peers); i++ { if i == rf.me { continue } go func(idx int) { rf.mu.Lock() if rf.state != Leader { rf.mu.Unlock() return } args := AppendEntriesArgs{ Term: rf.currentTerm, LeaderId: rf.me, PrevLogIndex: rf.getPrevLogIdx(idx), PrevLogTerm: rf.getPrev...
} } func (rf *Raft) startAppendLog() { for i :=
conditional_block
proto2.rs
/*! proto2.rs A newer, simpler, more easily-extensible `grel` protocol. As of 2020-12-29, this supersedes the `grel::protocol` lib. 2020-01-23 */ use serde::{Serialize, Deserialize}; /** The `Op` enum represents one of the `Room` operator subcommands. It is used in the `Msg::Op(...)` variant of the `Msg` enum. */ #...
}
{ println!("Msg::Text variant"); let m = Msg::Text { who: String::from("gre luser"), lines: vec!["This is a first line of text.".to_string(), "Following the first is a second line of text.".to_string()], }; test_serde(&m); ...
identifier_body
proto2.rs
/*! proto2.rs A newer, simpler, more easily-extensible `grel` protocol. As of 2020-12-29, this supersedes the `grel::protocol` lib. 2020-01-23 */ use serde::{Serialize, Deserialize}; /** The `Op` enum represents one of the `Room` operator subcommands. It is used in the `Msg::Op(...)` variant of the `Msg` enum. */ #...
Misc { what: "name".to_string(), data: vec!["old name".to_string(), "new name".to_string()], alt: "\"old name\" is now known as \"new name\".".to_string(), }; // when the Room operator changes Misc { what: "new_op".to_string(), data: ["New ...
// when a user changes his or her name
random_line_split
proto2.rs
/*! proto2.rs A newer, simpler, more easily-extensible `grel` protocol. As of 2020-12-29, this supersedes the `grel::protocol` lib. 2020-01-23 */ use serde::{Serialize, Deserialize}; /** The `Op` enum represents one of the `Room` operator subcommands. It is used in the `Msg::Op(...)` variant of the `Msg` enum. */ #...
(m: &Msg) { let stringd = serde_json::to_string_pretty(m).unwrap(); println!("{}\n", &stringd); let newm: Msg = serde_json::from_str(&stringd).unwrap(); assert_eq!(*m, newm); } #[test] fn visual_serde() { println!("Msg::Text variant"); let m = Msg::Text {...
test_serde
identifier_name
train_lstm.py
import sys, os import time import shutil import argparse import functools import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import torch.optim as optim from nlgeval impo...
(trainloader, encoder, decoder, optimizer, criterion, device, text_proc, max_it, opt): if not opt.freeze: encoder.train() decoder.train() ep_begin = time.time() before = time.time() for it, data in enumerate(trainloader): # TODO: currently supports only one timestamp, enable more in...
train_epoch
identifier_name
train_lstm.py
import sys, os import time import shutil import argparse import functools import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import torch.optim as optim from nlgeval impo...
def validate(valloader, encoder, decoder, criterion, device, text_proc, max_it, opt): encoder.eval() decoder.eval() nll_list = [] ppl_list = [] begin = time.time() before = time.time() gt_list = [] ans_list = [] evaluator = NLGEval() with torch.no_grad(): for it, data i...
if not opt.freeze: encoder.train() decoder.train() ep_begin = time.time() before = time.time() for it, data in enumerate(trainloader): # TODO: currently supports only one timestamp, enable more in the future ids = data['id'] durations = data['duration'] sentences...
identifier_body
train_lstm.py
import sys, os import time import shutil import argparse import functools import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import torch.optim as optim from nlgeval impo...
before = time.time() samplesentence = return_sentences(sample, text_proc) # evaluate for only 100 iterations if it == max_it-1: print("sample sentences:") for s in ans_list[-10:]: print(s) print(...
random_line_split
train_lstm.py
import sys, os import time import shutil import argparse import functools import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import torch.optim as optim from nlgeval impo...
except: metrics_dict = None print("could not evaluate, some sort of error in NLGEval", flush=True) print("---METRICS---", flush=True) break meannll = sum(nll_list) / len(nll_list) meanppl = sum(ppl_list) / len(ppl_list) ...
print("{}:\t\t{}".format(k, v))
conditional_block
promise_future_glue.rs
//! Gluing Rust's `Future` and JavaScript's `Promise` together. //! //! JavaScript's `Promise` and Rust's `Future` are two abstractions with the //! same goal: asynchronous programming with eventual values. Both `Promise`s //! and `Future`s represent a value that may or may not have been computed //! yet. However, the ...
<'a>( waiting: &'a mut RentToOwn<'a, WaitingOnInner<F>>, ) -> Poll<AfterWaitingOnInner<F>, GenericVoid<F>> { let error = match waiting.future.poll() { Ok(Async::NotReady) => { return Ok(Async::NotReady); } Ok(Async::Ready(t)) => { l...
poll_waiting_on_inner
identifier_name
promise_future_glue.rs
//! Gluing Rust's `Future` and JavaScript's `Promise` together. //! //! JavaScript's `Promise` and Rust's `Future` are two abstractions with the //! same goal: asynchronous programming with eventual values. Both `Promise`s //! and `Future`s represent a value that may or may not have been computed //! yet. However, the ...
enum Future2Promise<F> where F: Future, <F as Future>::Item: ToJSValConvertible, <F as Future>::Error: ToJSValConvertible, { /// Initially, we are waiting on the inner future to be ready or error. #[state_machine_future(start, transitions(Finished, NotifyingOfError))] WaitingOnInner { fu...
random_line_split
promise_future_glue.rs
//! Gluing Rust's `Future` and JavaScript's `Promise` together. //! //! JavaScript's `Promise` and Rust's `Future` are two abstractions with the //! same goal: asynchronous programming with eventual values. Both `Promise`s //! and `Future`s represent a value that may or may not have been computed //! yet. However, the ...
fn poll_notifying_of_error<'a>( notification: &'a mut RentToOwn<'a, NotifyingOfError<F>>, ) -> Poll<AfterNotifyingOfError<F>, GenericVoid<F>> { match notification.notify.poll() { Ok(Async::NotReady) => { return Ok(Async::NotReady); } // The o...
{ let error = match waiting.future.poll() { Ok(Async::NotReady) => { return Ok(Async::NotReady); } Ok(Async::Ready(t)) => { let cx = JsRuntime::get(); unsafe { rooted!(in(cx) let mut val = jsval::UndefinedVa...
identifier_body
rainwater.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights tCopyright (c) 2020 Oct...
return nrows,ncolumns def MakeCorrelationPanel(Data,Headers,PlotSize): ''' Parameters ---------- Data : pandas dataframe Contains the data set to be analyzed. Headers : list list of strings with the data headers inside Data. PlotSize : tuple contains the size ...
nrows,ncolumns=squaredUnique,squaredUnique+1
conditional_block
rainwater.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights tCopyright (c) 2020 Oct...
def MakeCorrelationPanel(Data,Headers,PlotSize): ''' Parameters ---------- Data : pandas dataframe Contains the data set to be analyzed. Headers : list list of strings with the data headers inside Data. PlotSize : tuple contains the size of the generated plot. Ret...
""" Parameters ---------- TotalNumberOfElements : int Total number of elements in the plot. Returns ------- nrows : int number of rows in the plot. ncolumns : int number of columns in the plot. """ numberOfUnique=TotalNumberOfElements squaredUnique=int(...
identifier_body
rainwater.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights tCopyright (c) 2020 Oct...
(Axes): """ Parameters ---------- Axes : Matplotlib axes object Applies a general style to the matplotlib object Returns ------- None. """ Axes.spines['top'].set_visible(False) Axes.spines['bottom'].set_visible(True) Axes.spines['left'].set_visible(True) Axe...
PlotStyle
identifier_name
rainwater.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights tCopyright (c) 2020 Oct...
values=Data.groupby(name).mean()["PRECIP"] xticks=values.keys() data=values.tolist() data+=data[:1] angles=np.linspace(0,2*np.pi,len(data)) ax.plot(angles,data) ax.fill(angles,data,'b',alpha=0.1) ax.set_xticks(angles) if name=='Month': ...
''' fig,axes=plt.subplots(1,3,figsize=figsize,subplot_kw=dict(polar=True)) dataHeaders=['DayOfWeek','Month','Year'] for ax,name in zip(axes,dataHeaders):
random_line_split
lib.rs
//! An implementation of the [MD6 hash function](http://groups.csail.mit.edu/cis/md6), via FFI to reference implementation. //! //! For more information about MD6 visit its [official homepage](http://groups.csail.mit.edu/cis/md6). //! //! There are two APIs provided: one for single-chunk hashing and one for hashing of ...
/// /// Storing and verifying results of all possible sizes. /// /// ``` /// # use md6::Md6; /// # use std::iter::FromIterator; /// let mut result_64 = [0; 8]; /// let mut result_128 = [0; 16]; /// let mut result_256 = [0; 32]; /// let mut result_512 = [0; 64]; /// /// l...
/// /// # Examples
random_line_split
lib.rs
//! An implementation of the [MD6 hash function](http://groups.csail.mit.edu/cis/md6), via FFI to reference implementation. //! //! For more information about MD6 visit its [official homepage](http://groups.csail.mit.edu/cis/md6). //! //! There are two APIs provided: one for single-chunk hashing and one for hashing of ...
_state(&mut self.raw_state); } } impl Error for Md6Error { fn description(&self) -> &str { match self { &Md6Error::Fail => "Generic MD6 fail", &Md6Error::BadHashbitlen => "Incorrect hashbitlen", } } } impl From<i32> for Md6Error { /// Passing incorrect error va...
hash
identifier_name
classes.ts
import { Iuser, Ijugada, Iplayer, GamePhase, Igame, Iroom, Ifactory, Itile, IrowLeft, IobjectiveTile, IgameMode } from "../../common/interfaces" export class Room implements Iroom{ users: Iuser[]=[]; name: string=""; constructor(name:string) { this.name=name } addUser(user:Iuse...
RND = Math.floor(Math.random() * (tempBag.tiles.length - 1) + 1) RNDcolor = tempBag.tiles[RND].color this.bag.tiles = this.bag.tiles.map((x)=>{ x.amount = x.color == RNDcolor ? x.amount - 1 : x.amount return x }) ...
{ this.moveTrashToBag() tempBag.tiles = this.bag.tiles }
conditional_block
classes.ts
import { Iuser, Ijugada, Iplayer, GamePhase, Igame, Iroom, Ifactory, Itile, IrowLeft, IobjectiveTile, IgameMode } from "../../common/interfaces" export class Room implements Iroom{ users: Iuser[]=[]; name: string=""; constructor(name:string) { this.name=name } addUser(user:Iuse...
} export class Player implements Iplayer{ rowsLefts: IrowLeft[]; rowsRight: IobjectiveTile[][]; user: Iuser; points: number; hazard: string[]; firstPlayerToken: boolean; constructor(user:Iuser, gameMode:IgameMode){ this.points = 0 this.hazard = [] this.firstPlayerTok...
{ this.users = this.users.map((x) => { x.conn= (x.name == user.name )? user.conn:x.conn; return x }) }
identifier_body
classes.ts
import { Iuser, Ijugada, Iplayer, GamePhase, Igame, Iroom, Ifactory, Itile, IrowLeft, IobjectiveTile, IgameMode } from "../../common/interfaces" export class Room implements Iroom{ users: Iuser[]=[]; name: string=""; constructor(name:string) { this.name=name } addUser(user:Iuser...
let fabricQuant: number fabricQuant = room.users.length == 2 ? 6 : 6 + ((room.users.length - 2) * 2) for (let index = 0; index < fabricQuant; index++) { this.factories.push(new Factory(this.mode.colors)) } //assign to fabrics this.bagToFabrics(4) ...
this.bag.add(color,20) }); //create public board
random_line_split
classes.ts
import { Iuser, Ijugada, Iplayer, GamePhase, Igame, Iroom, Ifactory, Itile, IrowLeft, IobjectiveTile, IgameMode } from "../../common/interfaces" export class Room implements Iroom{ users: Iuser[]=[]; name: string=""; constructor(name:string) { this.name=name } addUser(user:Iuse...
(name:string):boolean{ let tmp:Iuser[] = this.users.filter((x) => { x.name == name }) return tmp.length>0?true:false } getUserByName(name:string):(Iuser|null){ let tmp:Iuser[] = this.users.filter((x)=>{x.name ==name}) return tmp.length>0?tmp[0]:null } getUserByConn(conn:...
nameUserExist
identifier_name
graphbuilder.go
/* Copyright 2021 The KubeDiag 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 to in writing, so...
(operationSet diagnosisv1.OperationSet) (diagnosisv1.OperationSet, error) { // Build directed graph from adjacency list. graph, err := newGraphFromAdjacencyList(operationSet.Spec.AdjacencyList) if err != nil { return operationSet, err } nodes := graph.Nodes() for nodes.Next() { node := nodes.Node() toNodes...
syncOperationSet
identifier_name
graphbuilder.go
/* Copyright 2021 The KubeDiag 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 to in writing, so...
// addDiagnosisToGraphBuilderQueue adds OperationSets to the queue processed by graph builder. func (gb *graphBuilder) addDiagnosisToGraphBuilderQueue(operationSet diagnosisv1.OperationSet) { graphbuilderSyncErrorCount.Inc() err := util.QueueOperationSet(gb, gb.graphBuilderCh, operationSet) if err != nil { gb.Er...
{ // Build directed graph from adjacency list. graph, err := newGraphFromAdjacencyList(operationSet.Spec.AdjacencyList) if err != nil { return operationSet, err } nodes := graph.Nodes() for nodes.Next() { node := nodes.Node() toNodes := graph.To(node.ID()) source := true for toNodes.Next() { source ...
identifier_body
graphbuilder.go
/* Copyright 2021 The KubeDiag 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 to in writing, so...
// Set operation set status with diagnosis paths. paths := make([]diagnosisv1.Path, 0) for _, diagnosisPath := range diagnosisPaths { path := make(diagnosisv1.Path, 0) for _, id := range diagnosisPath { if operationSet.Spec.AdjacencyList[int(id)].ID != 0 { path = append(path, operationSet.Spec.Adjacency...
{ return operationSet, fmt.Errorf("unable to search diagnosis path: %s", err) }
conditional_block
graphbuilder.go
/* Copyright 2021 The KubeDiag 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 to in writing, so...
}, &operationSet) if err != nil { if apierrors.IsNotFound(err) { continue } gb.addDiagnosisToGraphBuilderQueue(operationSet) continue } // Only process unready operation set. if operationSet.Status.Ready { graphbuilderSyncSkipCount.Inc() continue } operationSet, err =...
// Process operation sets queuing in graph builder channel. case operationSet := <-gb.graphBuilderCh: err := gb.client.Get(gb, client.ObjectKey{ Name: operationSet.Name,
random_line_split
lib.rs
//! //! Basic account support with an authenticator. Primarly used for development/testing. //! Uses a 'Trust Anchor' approach to bootstrapping users: Genesis accounts can create other accounts. //! use anyhow::{bail, ensure}; use borsh::{BorshDeserialize, BorshSerialize}; use exonum_crypto::{hash, PublicKey, PUBLIC_KE...
} } fn handle_query( &self, path: &str, key: Vec<u8>, view: &StoreView, ) -> Result<Vec<u8>, anyhow::Error> { ensure!(key.len() > 0, "bad account key"); // return a serialized account for the given id. match path { "/" => { ...
{ let store = AccountStore::new(); let caller_acct = store.get(ctx.sender(), &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); let updated = acct.update_pubkey(pubkey); store.put(upd...
conditional_block
lib.rs
//! //! Basic account support with an authenticator. Primarly used for development/testing. //! Uses a 'Trust Anchor' approach to bootstrapping users: Genesis accounts can create other accounts. //! use anyhow::{bail, ensure}; use borsh::{BorshDeserialize, BorshSerialize}; use exonum_crypto::{hash, PublicKey, PUBLIC_KE...
pub struct AccountModule { // PublicKeys of genesis accounts genesis: Vec<[u8; 32]>, } impl AccountModule { pub fn new(genesis: Vec<[u8; 32]>) -> Self { Self { genesis } } } impl AppModule for AccountModule { fn name(&self) -> String { ACCOUNT_APP_NAME.into() } // Load ge...
#[derive(BorshDeserialize, BorshSerialize, Debug, PartialEq, Clone)] pub enum Msgs { Create(PublicKeyBytes), ChangePubKey(PublicKeyBytes), }
random_line_split
lib.rs
//! //! Basic account support with an authenticator. Primarly used for development/testing. //! Uses a 'Trust Anchor' approach to bootstrapping users: Genesis accounts can create other accounts. //! use anyhow::{bail, ensure}; use borsh::{BorshDeserialize, BorshSerialize}; use exonum_crypto::{hash, PublicKey, PUBLIC_KE...
{ Create(PublicKeyBytes), ChangePubKey(PublicKeyBytes), } pub struct AccountModule { // PublicKeys of genesis accounts genesis: Vec<[u8; 32]>, } impl AccountModule { pub fn new(genesis: Vec<[u8; 32]>) -> Self { Self { genesis } } } impl AppModule for AccountModule { fn name(&self...
Msgs
identifier_name
lib.rs
//! //! Basic account support with an authenticator. Primarly used for development/testing. //! Uses a 'Trust Anchor' approach to bootstrapping users: Genesis accounts can create other accounts. //! use anyhow::{bail, ensure}; use borsh::{BorshDeserialize, BorshSerialize}; use exonum_crypto::{hash, PublicKey, PUBLIC_KE...
#[test] fn test_account_authenticator() { // Check signature verification and nonce rules are enforced let app = AppBuilder::new() .set_authenticator(AccountAuthenticator {}) .with_app(AccountModule::new(get_genesis_accounts())); let mut tester = TestKit::creat...
{ let mut tx = SignedTransaction::create( user, ACCOUNT_APP_NAME, Msgs::Create([1u8; 32]), // fake data nonce, ); tx.sign(&secret_key); tx }
identifier_body
processor.go
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package system_updater import ( "bufio" "bytes" "context" "encoding/json" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "syscall" "sys...
f.Sync() f.Close() if err := os.Rename(partPath, currentPath); err != nil { return fmt.Errorf("error moving %v to %v: %w", partPath, currentPath, err) } return nil }
{ return fmt.Errorf("unable to write current channel to %v: %w", currentPath, err) }
conditional_block
processor.go
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package system_updater import ( "bufio" "bytes" "context" "encoding/json" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "syscall" "sys...
bootManagerReq, bootManagerPxy, err := paver.NewBootManagerWithCtxInterfaceRequest() if err != nil { syslog.Errorf("boot manager interface could not be acquired: %s", err) return nil, nil, err } err = pxy.FindBootManager(context.Background(), bootManagerReq) if err != nil { syslog.Errorf("could not find boo...
random_line_split
processor.go
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package system_updater import ( "bufio" "bytes" "context" "encoding/json" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "syscall" "sys...
func setConfigurationActive(bootManager *paver.BootManagerWithCtxInterface, targetConfig paver.Configuration) error { syslog.Infof("img_writer: setting configuration %s active", targetConfig) status, err := bootManager.SetConfigurationActive(context.Background(), targetConfig) if err != nil { return err } stat...
{ var config paver.Configuration switch activeConfig { case paver.ConfigurationA: config = paver.ConfigurationB case paver.ConfigurationB: config = paver.ConfigurationA case paver.ConfigurationRecovery: syslog.Warnf("img_writer: configured for recovery, using partition A instead") config = paver.Configura...
identifier_body
processor.go
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package system_updater import ( "bufio" "bytes" "context" "encoding/json" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "syscall" "sys...
(basename string, filenames []string) []Image { var images []Image for _, name := range filenames { if strings.HasPrefix(name, basename) { suffix := name[len(basename):] if len(suffix) == 0 { // The base name alone indicates default type (empty string). images = append(images, Image{Name: basename, T...
FindTypedImages
identifier_name
services.js
var myapp = angular.module('starter.services', []); myapp.factory('FavoritesService', function () { // Might use a resource here that returns a JSON array // Some testing data var items = []; for (var i = 0; i < 100; i++) { var item = {}; item.imgURL = './img/ionic.png'; item.title = 'news' + (i ...
(designDocCategory).then(function () { console.log('[Service CategoryService createCategoryDesignDoc]createCategoryDesignDoc finished.'); }).catch(function (err) { console.log(err); throw err; }); } function deleteCategoryDesignDoc() { console.log('[Service CategoryService deleteCateg...
) } } }; return local_db.put
conditional_block
services.js
var myapp = angular.module('starter.services', []); myapp.factory('FavoritesService', function () { // Might use a resource here that returns a JSON array // Some testing data var items = []; for (var i = 0; i < 100; i++) { var item = {}; item.imgURL = './img/ionic.png'; item.title = 'news' + (i ...
'expense_category_small') { emit([doc._id], doc); } }.toString() }, 'expense_category_large_small': { map: function (doc) { if (doc.type === 'expense_category_large') { emit([doc._id, 0, doc.order], doc); } else if (doc....
if (doc.type ===
identifier_name
services.js
var myapp = angular.module('starter.services', []); myapp.factory('FavoritesService', function () { // Might use a resource here that returns a JSON array // Some testing data var items = []; for (var i = 0; i < 100; i++) { var item = {}; item.imgURL = './img/ionic.png'; item.title = 'news' + (i ...
} }.toString() } } }; return local_db.put(designDocCategory).then(function () { console.log('[Service CategoryService createCategoryDesignDoc]createCategoryDesignDoc finished.'); }).catch(function (err) { console.log(err); throw err; }); } func...
emit([doc._id], doc);
random_line_split
services.js
var myapp = angular.module('starter.services', []); myapp.factory('FavoritesService', function () { // Might use a resource here that returns a JSON array // Some testing data var items = []; for (var i = 0; i < 100; i++) { var item = {}; item.imgURL = './img/ionic.png'; item.title = 'news' + (i ...
// get expense large and small category list function getExpenseLargeWithSmallCategoryList() { console.log('[Service CategoryService getLargeAndSmallCategoryList] start'); return local_db.query('categoryDoc/expense_category_large_small').then(function (response) { var largeCategoryAndSmallCategoryD...
{ var local_default_db = new PouchDB('local_default_value_db'); var defaultValue = ''; var doc = {}; return local_default_db.get(key).then(function (result) { return $q.when(result.default_value); }).catch(function (err) { $q.when(''); }); }
identifier_body
packet_handler.rs
// Copyright 2020-2022 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use bee_gossip::Multiaddr; use futures::{ channel::oneshot, future::{self, FutureExt}, stream::StreamExt, }; use log::trace; use tokio::select; use tokio_stream::wrappers::UnboundedReceiverStream; use crate::packets::{HeaderPacket...
} // Get the requested bytes. This will not panic because the loop above only exists if we // have enough bytes to do this step. let bytes = &self.buffer[self.offset..][..len]; // Increase the offset by the length of the byte slice. self.offset += len; bytes ...
{ // If we received an event, we push it to the buffer. self.push_event(event); }
conditional_block
packet_handler.rs
// Copyright 2020-2022 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use bee_gossip::Multiaddr; use futures::{ channel::oneshot, future::{self, FutureExt}, stream::StreamExt, }; use log::trace; use tokio::select; use tokio_stream::wrappers::UnboundedReceiverStream; use crate::packets::{HeaderPacket...
(receiver: EventRecv, shutdown: ShutdownRecv, address: Multiaddr) -> Self { Self { events: EventHandler::new(receiver), shutdown, // The handler should read a header first. state: ReadState::Header, address, } } /// Fetch the header and...
new
identifier_name
packet_handler.rs
// Copyright 2020-2022 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use bee_gossip::Multiaddr; use futures::{ channel::oneshot, future::{self, FutureExt}, stream::StreamExt, }; use log::trace; use tokio::select; use tokio_stream::wrappers::UnboundedReceiverStream; use crate::packets::{HeaderPacket...
self.push_event(event); } } // Get the requested bytes. This will not panic because the loop above only exists if we // have enough bytes to do this step. let bytes = &self.buffer[self.offset..][..len]; // Increase the offset by the length of the byte ...
random_line_split
MNIST_minimal.py
""" MNIST cINN: minimal depends on: {FrEIA} based on: https://github.com/VLL-HD/conditional_INNs """ __all__ = ["CONFIG", "MNISTcINN_minimal", "train", "evaluate"] # imports import numpy as np from collections import OrderedDict import torch import torch.optim import torch.nn as nn from tqdm import tqdm from tim...
def forward(self, x, l, jac=True): return self.cinn(x, c=one_hot(l), jac=jac) def reverse_sample(self, z, l, jac=True): return self.cinn(z, c=one_hot(l), rev=True, jac=jac) def save(self, name): save_dict = {"opt": self.optimizer.state_dict(), "net": self.cin...
def fc_subnet(ch_in, ch_out): return nn.Sequential(nn.Linear(ch_in, self.c.internal_width), nn.ReLU(), nn.Linear(self.c.internal_width, ch_out)) cond = Ff.ConditionNode(10) nodes = [Ff.InputNode(1, *self.c.img_size)] ...
identifier_body
MNIST_minimal.py
""" MNIST cINN: minimal depends on: {FrEIA} based on: https://github.com/VLL-HD/conditional_INNs """ __all__ = ["CONFIG", "MNISTcINN_minimal", "train", "evaluate"] # imports import numpy as np from collections import OrderedDict import torch import torch.optim import torch.nn as nn from tqdm import tqdm from tim...
nll = torch.mean(z**2) / 2 - torch.mean(log_j) / np.prod(config.img_size) nll.backward() torch.nn.utils.clip_grad_norm_(model.trainable_parameters, config.clip_grad_norm) nll_mean.append(nll.item()) ...
random_line_split
MNIST_minimal.py
""" MNIST cINN: minimal depends on: {FrEIA} based on: https://github.com/VLL-HD/conditional_INNs """ __all__ = ["CONFIG", "MNISTcINN_minimal", "train", "evaluate"] # imports import numpy as np from collections import OrderedDict import torch import torch.optim import torch.nn as nn from tqdm import tqdm from tim...
(config): model = MNISTcINN_minimal(config) if config.maxpool: data = MNISTDataPreprocessed(config) else: data = MNISTData(config) t_start = time() nll_mean = [] # memorize evolution of losses val_losses_means = np.array([]) val_losses = np.array([]) try: ...
train
identifier_name
MNIST_minimal.py
""" MNIST cINN: minimal depends on: {FrEIA} based on: https://github.com/VLL-HD/conditional_INNs """ __all__ = ["CONFIG", "MNISTcINN_minimal", "train", "evaluate"] # imports import numpy as np from collections import OrderedDict import torch import torch.optim import torch.nn as nn from tqdm import tqdm from tim...
nodes += [cond, Ff.OutputNode(nodes[-1])] return Ff.ReversibleGraphNet(nodes, verbose=False) def forward(self, x, l, jac=True): return self.cinn(x, c=one_hot(l), jac=jac) def reverse_sample(self, z, l, jac=True): return self.cinn(z, c=one_hot(l), rev=True, jac=jac) def s...
nodes.append(Ff.Node(nodes[-1], Fm.PermuteRandom, {"seed": k})) nodes.append(Ff.Node(nodes[-1], Fm.GLOWCouplingBlock, {"subnet_constructor": fc_subnet, "clamp": self.c.clamping}, ...
conditional_block
session.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: github.com/bio-routing/bio-rd/protocols/bgp/api/session.proto package api import ( fmt "fmt" api "github.com/bio-routing/bio-rd/net/api" proto "github.com/golang/protobuf/proto" math "math" ) // Reference imports to suppress errors if they are not other...
func (m *Session) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Session.Unmarshal(m, b) } func (m *Session) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Session.Marshal(b, m, deterministic) } func (m *Session) XXX_Merge(src proto.Message) { xxx_messageInfo_Session.Merge...
}
random_line_split
session.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: github.com/bio-routing/bio-rd/protocols/bgp/api/session.proto package api import ( fmt "fmt" api "github.com/bio-routing/bio-rd/net/api" proto "github.com/golang/protobuf/proto" math "math" ) // Reference imports to suppress errors if they are not other...
() int { return xxx_messageInfo_Session.Size(m) } func (m *Session) XXX_DiscardUnknown() { xxx_messageInfo_Session.DiscardUnknown(m) } var xxx_messageInfo_Session proto.InternalMessageInfo func (m *Session) GetLocalAddress() *api.IP { if m != nil { return m.LocalAddress } return nil } func (m *Session) GetNei...
XXX_Size
identifier_name
session.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: github.com/bio-routing/bio-rd/protocols/bgp/api/session.proto package api import ( fmt "fmt" api "github.com/bio-routing/bio-rd/net/api" proto "github.com/golang/protobuf/proto" math "math" ) // Reference imports to suppress errors if they are not other...
func (m *Session) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Session.Unmarshal(m, b) } func (m *Session) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Session.Marshal(b, m, deterministic) } func (m *Session) XXX_Merge(src proto.Message) { xxx_messageInfo_Session.Mer...
{ return fileDescriptor_5b53032c0bb76d75, []int{0} }
identifier_body
session.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: github.com/bio-routing/bio-rd/protocols/bgp/api/session.proto package api import ( fmt "fmt" api "github.com/bio-routing/bio-rd/net/api" proto "github.com/golang/protobuf/proto" math "math" ) // Reference imports to suppress errors if they are not other...
return 0 } func (m *SessionStats) GetRoutesExported() uint64 { if m != nil { return m.RoutesExported } return 0 } func init() { proto.RegisterEnum("bio.bgp.Session_State", Session_State_name, Session_State_value) proto.RegisterType((*Session)(nil), "bio.bgp.Session") proto.RegisterType((*SessionStats)(nil),...
{ return m.RoutesImported }
conditional_block
core_test.go
package core import ( "context" "errors" "fmt" "github.com/getlantern/bytemap" "github.com/getlantern/goexpr" "github.com/getlantern/zenodb/encoding" . "github.com/getlantern/zenodb/expr" "github.com/stretchr/testify/assert" "sync/atomic" "testing" "time" ) var ( epoch = time.Date(2015, 1, 1, 0, 0, 0...
(t *testing.T) { avgTotal := ADD(AVG("a"), AVG("b")) f := Flatten(&goodSource{}) u := Unflatten(f, StaticFieldSource{NewField("total", avgTotal)}) doTestUnflattened(t, u, avgTotal) } func TestUnflattenOptimized(t *testing.T) { total := ADD(eA, eB) s := &totalingSource{} f := Flatten(s) u := UnflattenOptimized(...
TestUnflattenTransform
identifier_name
core_test.go
package core import ( "context" "errors" "fmt" "github.com/getlantern/bytemap" "github.com/getlantern/goexpr" "github.com/getlantern/zenodb/encoding" . "github.com/getlantern/zenodb/expr" "github.com/stretchr/testify/assert" "sync/atomic" "testing" "time" ) var ( epoch = time.Date(2015, 1, 1, 0, 0, 0...
} } func (s *infiniteSource) String() string { return "test.infinite" } type errorSource struct { testSource } func (s *errorSource) Iterate(ctx context.Context, onFields OnFields, onRow OnRow) (interface{}, error) { return nil, errTest } func (s *errorSource) String() string { return "test.error" } type tot...
{ more, err := onRow(row.key, row.vals) if !more || err != nil { return nil, err } }
conditional_block
core_test.go
package core import ( "context" "errors" "fmt" "github.com/getlantern/bytemap" "github.com/getlantern/goexpr" "github.com/getlantern/zenodb/encoding" . "github.com/getlantern/zenodb/expr" "github.com/stretchr/testify/assert" "sync/atomic" "testing" "time" ) var ( epoch = time.Date(2015, 1, 1, 0, 0, 0...
} func (s *testSource) GetAsOf() time.Time { return asOf } func (s *testSource) GetUntil() time.Time { return until } type testRow struct { key bytemap.ByteMap vals Vals } func (r *testRow) equals(other *testRow) bool { if r == nil || other == nil { return false } if string(r.key) != string(other.key) { ...
return resolution
random_line_split
core_test.go
package core import ( "context" "errors" "fmt" "github.com/getlantern/bytemap" "github.com/getlantern/goexpr" "github.com/getlantern/zenodb/encoding" . "github.com/getlantern/zenodb/expr" "github.com/stretchr/testify/assert" "sync/atomic" "testing" "time" ) var ( epoch = time.Date(2015, 1, 1, 0, 0, 0...
func (s *totalingSource) Iterate(ctx context.Context, onFields OnFields, onRow OnRow) (interface{}, error) { return s.goodSource.Iterate(ctx, onFields, func(key bytemap.ByteMap, vals Vals) (bool, error) { a, _ := vals[0].ValueAt(0, eA) b, _ := vals[0].ValueAt(0, eB) val := encoding.NewValue(totalField.Expr, va...
{ return Fields{totalField} }
identifier_body
util.ts
// #ifdef H5 // var clipboardJS = require( from ''./clipboardJS''); // import clipboardJS from './clipboardJS' // #endif import {ComponentInternalInstance} from 'vue' /** * 预览图片。 @param {Object} url 必填 当前预览的图片链接。 @param {Object} list 可以是url数组,也可以是对象,数据比如:["http:url"] or [{url:"https:url",...}] @param {Object} rang...
* 是否车牌 * @description 蓝牌5位,绿牌6位。 * @param s 字符串 * @returns Boolean */ export function isIdCar(s:string){ let reg = /^[京|沪|津|渝|鲁|冀|晋|蒙|辽|吉|黑|苏|浙|皖|闽|赣|豫|湘|鄂|粤|桂|琼|川|贵|云|藏|陕|甘|青|宁|新|港|澳|台|新|使]{1}[A-Z]{1}[A-Z_0-9]{5,6}$/ return !!s.match(reg); } /** * 纯数字密码验证 * @param s 字符串或者数字 * @param len 最小长度,默认6 * @param ma...
} /**
identifier_name
util.ts
// #ifdef H5 // var clipboardJS = require( from ''./clipboardJS''); // import clipboardJS from './clipboardJS' // #endif import {ComponentInternalInstance} from 'vue' /** * 预览图片。 @param {Object} url 必填 当前预览的图片链接。 @param {Object} list 可以是url数组,也可以是对象,数据比如:["http:url"] or [{url:"https:url",...}] @param {Object} rangK...
format.m = m < 10 ? '0' + m : m; format.s = s < 10 ? '0' + s : s; } return format; } //获取时间距离当前时间 export function getDateToNewData(timestamp:number|string|Date = new Date().getTime()){ if(typeof timestamp == 'string'){ timestamp = new Date(timestamp).getTime(); } // 补全为13位 var arrTimestamp:Array<string>...
random_line_split
util.ts
// #ifdef H5 // var clipboardJS = require( from ''./clipboardJS''); // import clipboardJS from './clipboardJS' // #endif import {ComponentInternalInstance} from 'vue' /** * 预览图片。 @param {Object} url 必填 当前预览的图片链接。 @param {Object} list 可以是url数组,也可以是对象,数据比如:["http:url"] or [{url:"https:url",...}] @param {Object} rang...
t(data) } else { const textArea = document.createElement('textarea') textArea.style.opacity = "0" textArea.style.position = "fixed" textArea.style.top = "0px" textArea.value = data document.body.appendChild(textArea) textArea.focus() textArea.select() document.execCommand('copy') ? rs(t...
(rs,rj)=>{ // #ifndef H5 uni.setClipboardData({ data: data, success:()=>rs(true), fail:(error)=>rj(error) }); // #endif // #ifdef H5 if (navigator.clipboard && window.isSecureContext) { return navigator.clipboard.writeTex
identifier_body
app-form.js
define('app/form',["app/common","moment","jquery/validate","jquery/form"],function(APP) { var FORM = { initDatePicker : function(ct){ APP.queryContainer(ct).find('[form-role="date"]').each(function(){ $(this).datePicker(); }); } }; /** * 将form格式化为json * @param {Object...
identifier_body
app-form.js
define('app/form',["app/common","moment","jquery/validate","jquery/form"],function(APP) { var FORM = { initDatePicker : function(ct){ APP.queryContainer(ct).find('[form-role="date"]').each(function(){ $(this).datePicker(); }); } }; /** * 将form格式化为json * @param {Object...
var _adddiv = $("<div>"); var _addform = $("<div class='row'><div class='col-md-12'><div class='form-group'><label class='control-label col-md-3'>代码</label><div class='col-md-9'><input type='text' name='_select_type_code' class='form-control input-small'></div></div></div></div>"+ "<div class='row'><div cl...
tn blue'><i class='fa fa-plus'></i></a></span>"); _select.wrap("<div class='input-group'></div>"); _add_btn.insertAfter(_select); _add_btn.click(function(){ var _this = $(this);
conditional_block
app-form.js
define('app/form',["app/common","moment","jquery/validate","jquery/form"],function(APP) { var FORM = { initDatePicker : function(ct){ APP.queryContainer(ct).find('[form-role="date"]').each(function(){ $(this).datePicker(); }); } }; /** * 将form格式化为json * @param {Object}...
onClick: function(e, tree_id, treeNode){//点击时将数据传入显示控件 var zTree = $.fn.zTree.getZTreeObj(tree_id), nodes = zTree.getSelectedNodes(), _name = "", _id = ""; nodes.sort(function compare(a,b){return a[_key_id]-b[_key_id];}); for (var i=0, l=nodes.length; i<l; i++) { _name +...
} }, callback: {
random_line_split
app-form.js
define('app/form',["app/common","moment","jquery/validate","jquery/form"],function(APP) { var FORM = { initDatePicker : function(ct){ APP.queryContainer(ct).find('[form-role="date"]').each(function(){ $(this).datePicker(); }); } }; /** * 将form格式化为json * @param {Object...
identifier_name
instance.rs
use crate::{ create_idx_struct, data_structures::{cont_idx_vec::ContiguousIdxVec, skipvec::SkipVec}, small_indices::SmallIdx, }; use anyhow::{anyhow, ensure, Error, Result}; use log::{info, trace}; use serde::Deserialize; use std::{ fmt::{self, Display, Write as _}, io::{BufRead, Write}, mem, ...
} /// Edges incident to a node, sorted by increasing indices. pub fn node( &self, node: NodeIdx, ) -> impl Iterator<Item = EdgeIdx> + ExactSizeIterator + Clone + '_ { self.node_incidences[node.idx()] .iter() .map(|(_, (edge, _))| *edge) } /// Nod...
self.edge_incidences.len()
random_line_split