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
helper.go
regions.Region, error) { idClient, err := goopenstack.NewIdentityV3(client, gophercloud.EndpointOpts{}) if err != nil { return nil, err } listOpts := osregions.ListOpts{ ParentRegionID: "", } allPages, err := osregions.List(idClient, listOpts).AllPages() if err != nil { return nil, err } regions, err :=...
{ return nil, err }
conditional_block
helper.go
ophercloud/gophercloud/pagination" "go.uber.org/zap" ) var ( errNotFound = errors.New("not found") securityGroupCreationLock = sync.Mutex{} ) const ( errorStatus = "ERROR" floatingReassignIPCheckPeriod = 3 * time.Second ) func getRegion(client *gophercloud.ProviderClient, name string) (*osregions...
(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
ophercloud/gophercloud/pagination" "go.uber.org/zap" ) var ( errNotFound = errors.New("not found") securityGroupCreationLock = sync.Mutex{} ) const ( errorStatus = "ERROR" floatingReassignIPCheckPeriod = 3 * time.Second ) func getRegion(client *gophercloud.ProviderClient, name string) (*osregions...
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
ourceid_and_photrpmeanmag_v{cdipssource_vnum}.csv' ) if not os.path.exists(catalogfile): if cdipssource_vnum < 0.6: cfile = join(catdir, f'OC_MG_FINAL_GaiaRp_lt_16_v{cdipssource_vnum}.csv') cdipsdf = pd.read_csv(cfile, sep=';') else: cfile...
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, fovcathasgaia
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
'sourceid_and_photrpmeanmag_v{cdipssource_vnum}.csv' ) if not os.path.exists(catalogfile): if cdipssource_vnum < 0.6: cfile = join(catdir, f'OC_MG_FINAL_GaiaRp_lt_16_v{cdipssource_vnum}.csv') cdipsdf = pd.read_csv(cfile, sep=';') else: cfi...
catdir = '/ar1/local/cdips/catalogs/' 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') outpath = statsfile.replace('cdips_lc_statistics', ...
""" 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
ourceid_and_photrpmeanmag_v{cdipssource_vnum}.csv' ) if not os.path.exists(catalogfile): if cdipssource_vnum < 0.6: cfile = join(catdir, f'OC_MG_FINAL_GaiaRp_lt_16_v{cdipssource_vnum}.csv') cdipsdf = pd.read_csv(cfile, sep=';') else: cfile...
( 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
nfs/phtess2/ar0/TESS/PROJ/lbouma/CDIPS_LCS/sector-{sector}/' catdir = '/nfs/phtess1/ar1/TESS/PROJ/lbouma/' elif filesystem in ['wh1', 'wh2']: projdir = "/ar1/PROJ/luke/proj/cdips" lcdirectory = f'/ar1/PROJ/luke/proj/CDIPS_LCS/sector-{sector}/' catdir = '/ar1/local/cdips/catalogs/' ...
sel = ( (stats['ndet_rm1']==0) & (stats['ndet_rm2']==0) &
random_line_split
lane-finder.py
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
(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
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
.max(abs_sobel)) grad_binary = np.zeros_like(scaled_sobel) grad_binary[(scaled_sobel >= thresh[0]) & (scaled_sobel <= thresh[1])] = 1 return grad_binary def color_threshold(img): #R = img[:,:,0] #G = img[:,:,1] #B = img[:,:,2] #binary = np.zeros_like(R) #binary[(R > 200) & (G > 160) &...
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
] (button is same as 'mouse', ) - dpi:direction, direction is one of 'loop', 'up', 'down' - dpi-lock:value - media:key - macro:bank - keyboard:modifiers:key The provided mappings are always applied over the default configuration, not the current one. If no mappings are provided, the default...
{ 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
0] (button is same as 'mouse', ) - dpi:direction, direction is one of 'loop', 'up', 'down' - dpi-lock:value - media:key - macro:bank - keyboard:modifiers:key The provided mappings are always applied over the default configuration, not the current one. If no mappings are provided, the defaul...
(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
] (button is same as 'mouse', ) - dpi:direction, direction is one of 'loop', 'up', 'down' - dpi-lock:value - media:key - macro:bank - keyboard:modifiers:key The provided mappings are always applied over the default configuration, not the current one. If no mappings are provided, the default...
} } 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
PickupSearchQueryService } from './pickup-search-query.service'; import { MatDialog } from '@angular/material'; import { New, InProgress, Completed, Canceled } from '../../constants/pickup-dashboard-state'; import { PickupActionType } from '../../constants/pickup-action-type'; import { PickupLinkType } from '....
constructExportRow
identifier_name
pickup-search.component.ts
Configurator } from './conf/pickup-search-filter-configurator'; import { PickupSearchViewEnum } from './conf/pickup-search-view.enum'; import { PickupSearchDefaultColumnsMap } from './conf/pickup-search-view-template'; import { pickupDownloadFields } from './conf/pickup-column-variable-name.conf'; import { PickupSearch...
} // 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
Configurator } from './conf/pickup-search-filter-configurator'; import { PickupSearchViewEnum } from './conf/pickup-search-view.enum'; import { PickupSearchDefaultColumnsMap } from './conf/pickup-search-view-template'; import { pickupDownloadFields } from './conf/pickup-column-variable-name.conf'; import { PickupSearch...
/* ====================================================================== */ /* 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
Service: AidDialogService, public pickupService: PickupService) { super(pickupSearchQueryService, true); this.subscribeMessageIndicator(); } // implement abstract method - checkPrivilege checkPrivilege(): boolean { return true; } // implement abstract method - watchPredefinedGlobalSearchFilt...
} 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
fcntl import logging import os from pathlib import Path import shutil import subprocess as sp import sys logging.basicConfig(level=logging.INFO) class BootItException(Exception): pass class BootItState: state = [] @classmethod def push_state(cls, bootit): cls.state += [bootit] @class...
else:
Cmd("{} {}".format(prefix, " ".join(needed)))
conditional_block
bootit2.py
fcntl import logging import os from pathlib import Path import shutil import subprocess as sp import sys logging.basicConfig(level=logging.INFO) class BootItException(Exception): pass class
: 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
fcntl import logging import os from pathlib import Path import shutil import subprocess as sp import sys logging.basicConfig(level=logging.INFO) class BootItException(Exception): pass class BootItState: state = [] @classmethod def push_state(cls, bootit): cls.state += [bootit] @class...
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
return cls.state[-1] else: return None class BootIt: def __init__(self, args=None): if args is None: args = sys.argv self.argparse(args) self.selfdir = Path(__file__).absolute().parent if (self.selfdir / ".git").exists(): l...
# # evaluator = Evaluator(commands, options.dry_run)
random_line_split
jwxt.js
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
资料 exports.getMyInfo = async (cookies) => { const url = `framework/xsMain.jsp`; const customHeader = { 'Cookie': cookies }; let myInfo; try { myInfo = await req.get(url, null, customHeader); } catch (e) { return { ret: false, code: resModel.CODE.JWXT_INACCESSIBLE, msg: resModel.TEXT...
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
_prefix=None), "jitsi_app_id": values.Value(environ_name="JITSI_APP_ID", environ_prefix=None), "jitsi_secret_key": values.Value( environ_name="JITSI_SECRET_KEY", environ_prefix=None ), "jitsi_xmpp_domain": values.Value( environ_name="JITSI_XMPP_DOMAIN", environ_pr...
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
DEBUG = False SITE_ID = 1 # Security ALLOWED_HOSTS = [] CSRF_TRUSTED_ORIGINS = values.ListValue([]) SECRET_KEY = values.Value(None) # CORS headers CORS_ALLOWED_ORIGINS = values.ListValue([]) # System check reference: # https://docs.djangoproject.com/en/2.2/ref/checks/#securit...
"" 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
JITSI_GUEST_AVATAR", environ_prefix=None ), "jitsi_guest_username": values.Value( "Guest", environ_name="JITSI_GUEST_USERNAME", environ_prefix=None ), "jitsi_token_expiration_seconds": values.Value( 300, environ_name="JITSI_TOKEN_EXPIRATION_SECONDS", environ_prefi...
evelopment(
identifier_name
settings.py
"SAMEORIGIN" "security.W019" ] ) REST_FRAMEWORK = { "ALLOWED_VERSIONS": ("1.0",), "DEFAULT_AUTHENTICATION_CLASSES": values.ListValue( ["rest_framework_simplejwt.authentication.JWTAuthentication"], environ_name="DRF_DEFAULT_AUTHENTICATION_CLASSES", ...
"formatter": "verbose", } }, "loggers": { "django.db.backends": {
"class": "logging.StreamHandler",
random_line_split
intergen.ts
.getCombinedModifierFlags(type.valueDeclaration) return !(flags & ts.ModifierFlags.NonPublicAccessibilityModifier) } interface ClassProperty { name: string type: ts.Type relevantTypes: ts.Type[] typeString: string optional: boolean } interface ClassDefinition { name: string type: ts.Type typeParamet...
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
.getCombinedModifierFlags(type.valueDeclaration) return !(flags & ts.ModifierFlags.NonPublicAccessibilityModifier) } interface ClassProperty { name: string type: ts.Type relevantTypes: ts.Type[] typeString: string optional: boolean } interface ClassDefinition { name: string type: ts.Type typeParamet...
// keep type aliases return true } const symbol = type.getSymbol() if (!symbol) { debug(' no symbol') // e.g. string or number types have no symbol return false } if (symbol && symbol.flags & ts.SymbolFlags.Transient) { debug(' is transient')...
{ // 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
.getCombinedModifierFlags(type.valueDeclaration) return !(flags & ts.ModifierFlags.NonPublicAccessibilityModifier) } interface ClassProperty { name: string type: ts.Type relevantTypes: ts.Type[] typeString: string optional: boolean } interface ClassDefinition { name: string type: ts.Type typeParamet...
(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
ts.getCombinedModifierFlags(type.valueDeclaration) return !(flags & ts.ModifierFlags.NonPublicAccessibilityModifier) } interface ClassProperty { name: string type: ts.Type relevantTypes: ts.Type[] typeString: string optional: boolean } interface ClassDefinition { name: string type: ts.Type typePara...
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
= []; this.cpp11 = false; this.c11 = false; this.kore = true; this.targetOptions = { android: {}, xboxOne: {}, playStation4: {}, switch: {} }; this.rotated = false; this.cmd = false; this.stackSize = 0; } flatten() { for (let sub of this.subProjects) sub.flatten(); f...
{ this.addExclude(arguments[i]); }
conditional_block
Project.ts
true; } if (sub.cmd) { this.cmd = true; } let subbasedir = sub.basedir; for (let tkey of Object.keys(sub.targetOptions)) { const target = sub.targetOptions[tkey]; for (let key of Object.keys(target)) { const options = this.targetOptions[tkey]; const option = target[key]...
{ for (let i = 0; i < arguments.length; ++i) { this.addIncludeDir(arguments[i]); } }
identifier_body
Project.ts
let file = fs.readFileSync(path.resolve(directory, korefile), 'utf8'); let AsyncFunction = Object.getPrototypeOf(async () => {}).constructor; let project = new AsyncFunction( 'log', 'Project', 'Platform', 'platform', 'GraphicsApi', 'graphics', 'Architecture', 'arch', ...
{ 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
let file = fs.readFileSync(path.resolve(directory, korefile), 'utf8'); let AsyncFunction = Object.getPrototypeOf(async () => {}).constructor; let project = new AsyncFunction( 'log', 'Project', 'Platform', 'platform', 'GraphicsApi', 'graphics', 'Architecture', 'arch', ...
// 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
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.log = rf.log[:index] //delete the existing entry and all that follow it (§5.3) } } ...
AppendEntriesRepl
identifier_name
raft.go
f.log) data := w.Bytes() rf.persister.SaveRaftState(data) } // // restore previously persisted state. // func (rf *Raft) readPersist(data []byte) { if data == nil || len(data) < 1 { // bootstrap without any state? return } // Your code here (2C). // Example: // r := bytes.NewBuffer(data) // d := labgob.NewD...
} 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
lictTerm { reply.ConflictIndex = i break } } } return } 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 exist...
m(i int) int { prevLogIdx := r
identifier_body
raft.go
.currentTerm reply.VoteGranted = false if (args.Term < rf.currentTerm) || (rf.votedFor != NULL && rf.votedFor != args.CandidateId) { // Reply false if term < currentTerm (§5.1) If votedFor is not null and not candidateId, } else if args.LastLogTerm < rf.getLastLogTerm() || (args.LastLogTerm == rf.getLastLogTerm()...
} } func (rf *Raft) startAppendLog() { for i :=
conditional_block
proto2.rs
. The next six, `Name`, `Join`, `Query`, `Block`, `Unblock`, and `Op` are for sending commands or requests from the client to the server. The final three, `Info`, `Err`, and `Misc` are used to send information from the server back to the client. */ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum M...
{ 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
sends an invitation message to the user. */ Invite(String), /** Transfer operatorship to another user. (The user must be in the current room to receive the mantle of operatorship.) */ Give(String), } /** The `Msg` enum is the structure that gets serialized to JSON and passed along the TCP connect...
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
an invitation message to the user. */ Invite(String), /** Transfer operatorship to another user. (The user must be in the current room to receive the mantle of operatorship.) */ Give(String), } /** The `Msg` enum is the structure that gets serialized to JSON and passed along the TCP connections b...
(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
NetCaptions_Train from dataset.activitynet_valtest import ActivityNetCaptions_Val import transforms.spatial_transforms as spt import transforms.temporal_transforms as tpt from options import parse_args from utils.makemodel import generate_3dcnn, generate_rnn def train_lstm(args): # gpus device = torch.device(...
(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
NetCaptions_Train from dataset.activitynet_valtest import ActivityNetCaptions_Val import transforms.spatial_transforms as spt import transforms.temporal_transforms as tpt from options import parse_args from utils.makemodel import generate_3dcnn, generate_rnn def train_lstm(args): # gpus device = torch.device(...
clip = clip.to(device) captions = captions.to(device) target = captions.clone().detach() # flow through model if opt.freeze: with torch.no_grad(): feature = encoder(clip) else: feature = encoder(clip) # feature : (bs x C') ...
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
= [os.path.join(args.root_path, pth) for pth in args.annpaths] text_proc = build_vocab(annfiles, args.min_freq, args.max_seqlen) vocab_size = len(text_proc.vocab) # transforms sp = spt.Compose([spt.CornerCrop(size=args.imsize), spt.ToTensor()]) tp = tpt.Compose([tpt.TemporalRandomCrop(args.clip_le...
random_line_split
train_lstm.py
set = ActivityNetCaptions_Train(args.root_path, ann_path='train_fps.json', sample_duration=args.clip_len, spatial_transform=sp, temporal_transform=tp) trainloader = DataLoader(train_dset, batch_size=args.batch_size, shuffle=True, num_workers=args.n_cpu, drop_last=True, timeout=100) max_train_it = int(len(train_...
print("{}:\t\t{}".format(k, v))
conditional_block
promise_future_glue.rs
resolution value over a one-shot //! channel. One-shot channels are split into their two halves: sender and //! receiver. The sender half moves into the callback, but the receiver half is //! a future, and it represents the future resolution value of the original //! promise. //! //! The final concern to address is th...
<'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
resolution value over a one-shot //! channel. One-shot channels are split into their two halves: sender and //! receiver. The sender half moves into the callback, but the receiver half is //! a future, and it represents the future resolution value of the original //! promise. //! //! The final concern to address is th...
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
resolution value over a one-shot //! channel. One-shot channels are split into their two halves: sender and //! receiver. The sender half moves into the callback, but the receiver half is //! a future, and it represents the future resolution value of the original //! promise. //! //! The final concern to address is th...
e } else { return ready(Finished(PhantomData)); } } } Err(error) => { let cx = JsRuntime::get(); unsafe { rooted!(in(cx) let mut val = jsva...
{ 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
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @author: Octavio Gonzalez-Lugo ...
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
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @author: Octavio Gonzalez-Lugo ...
nrows,ncolumns=squaredUnique+1,squaredUnique+1 else: nrows,ncolumns=squaredUnique,squaredUnique+1 return nrows,ncolumns def MakeCorrelationPanel(Data,Headers,PlotSize): ''' Parameters ---------- Data : pandas dataframe Contains the data set to be analyzed. Hea...
""" 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
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @author: Octavio Gonzalez-Lugo ...
(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
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @author: Octavio Gonzalez-Lugo ...
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
0xEE, 0xEE, 0x7C, 0x83, 0x12, 0x06, 0xBD, /// 0x57, 0x7F, 0x9F, 0x26, 0x30, 0xD9, 0x17, 0x79, /// 0x79, 0x20, 0x3A, 0x94, 0x89, 0xE4, 0x7E, 0x04, /// 0xDF, 0x4E, 0x6D, 0xEA, 0xA0, 0xF8, 0xE0, 0xC0]); /// ``` pub fn hash(hashbitlen: i32, data: &[u8], hashval: &mut [u8]) ->...
/// /// # Examples
random_line_split
lib.rs
B, 0xDA, 0x95, 0x44, 0xCC, 0x3F, /// 0xFB, 0x59, 0x4B, 0x62, 0x84, 0xEF, 0x07, 0xDD, /// 0x59, 0xE7, 0x94, 0x2D, 0xCA, 0xCA, 0x07, 0x52, /// 0x14, 0x13, 0xE8, 0x06, 0xBD, 0x84, 0xB8, 0xC7, /// 0x8F, 0xB8, 0x03, 0x24, 0x39, 0xC8, 0x2E, 0xEC,...
hash
identifier_name
classes.ts
(user: Iuser):void{ this.users = this.users.filter((x)=>{x.conn!=user.conn}) } nameUserExist(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[] = t...
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
User(user: Iuser):void{ this.users = this.users.filter((x)=>{x.conn!=user.conn}) } nameUserExist(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[] ...
} 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
(user: Iuser):void{ this.users = this.users.filter((x)=>{x.conn!=user.conn}) } nameUserExist(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[] = t...
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
User(user: Iuser):void{ this.users = this.users.filter((x)=>{x.conn!=user.conn}) }
(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
"gonum.org/v1/gonum/graph/topo" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/metrics" diagnosisv1 "github.com/kubediag/ku...
(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
"gonum.org/v1/gonum/graph/topo" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/metrics" diagnosisv1 "github.com/kubediag/ku...
} else { if source { // Return error if some node is unreachable from start node in the graph. return operationSet, fmt.Errorf("node %d is unreachable from start node", node.ID()) } } } // Validate the graph does not have any cycles. _, err = topo.Sort(graph) if err != nil { return operationSet...
{ // 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
"gonum.org/v1/gonum/graph/topo" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/metrics" diagnosisv1 "github.com/kubediag/ku...
// 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
"gonum.org/v1/gonum/graph/topo" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/metrics" diagnosisv1 "github.com/kubediag/ku...
}, &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
Format of the account id: base58(hash(pubkey)) fn generate_account_id(pk: &PublicKey) -> Vec<u8> { let hash = hash(&pk.as_bytes()); bs58::encode(&hash.as_bytes()).into_vec() } /// Account Model #[derive(BorshDeserialize, BorshSerialize, Debug, PartialEq, Clone)] pub struct Account { pub id: AccountId, ...
} } 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
// Format of the account id: base58(hash(pubkey)) fn generate_account_id(pk: &PublicKey) -> Vec<u8> { let hash = hash(&pk.as_bytes()); bs58::encode(&hash.as_bytes()).into_vec() } /// Account Model #[derive(BorshDeserialize, BorshSerialize, Debug, PartialEq, Clone)] pub struct Account { pub id: AccountId, ...
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
Format of the account id: base58(hash(pubkey)) fn generate_account_id(pk: &PublicKey) -> Vec<u8> { let hash = hash(&pk.as_bytes()); bs58::encode(&hash.as_bytes()).into_vec() } /// Account Model #[derive(BorshDeserialize, BorshSerialize, Debug, PartialEq, Clone)] pub struct Account { pub id: AccountId, ...
{ 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
Format of the account id: base58(hash(pubkey)) fn generate_account_id(pk: &PublicKey) -> Vec<u8> { let hash = hash(&pk.as_bytes()); bs58::encode(&hash.as_bytes()).into_vec() } /// Account Model #[derive(BorshDeserialize, BorshSerialize, Debug, PartialEq, Clone)] pub struct Account { pub id: AccountId, ...
#[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
aver.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 } statusErr := zx.Status(status) if statusErr != ...
{ return fmt.Errorf("unable to write current channel to %v: %w", currentPath, err) }
conditional_block
processor.go
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
is (syscall.ENOENT did not work). modeSrc, err := updatePkg.Open("update-mode") if err != nil { syslog.Infof("parse_update_mode: could not open update-mode file, assuming normal system update flow.") return UpdateModeNormal, nil } defer modeSrc.Close() // Read the raw bytes. b, err := ioutil.ReadAll(modeSrc)...
{ 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
json.Unmarshal(b, &s); err == nil { b = []byte(s) } return json.Unmarshal(b, (*int)(i)) } func ParsePackagesJson(pkgSrc io.ReadCloser) ([]string, error) { bytes, err := ioutil.ReadAll(pkgSrc) if err != nil { return nil, fmt.Errorf("failed to read packages.json with error: %v", err) } var packages packages ...
(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
.log('[Service CategoryService getIncomeLargeCategoryList]get large category list Success.'); return $q.when(results); }).catch(function (err) { console.log('[Service CategoryService getIncomeLargeCategoryList]get large category list Error.'); console.log(err); return $q.when(''); }); ...
) } } }; return local_db.put
conditional_block
services.js
.log('[Service CategoryService getExpenseLargeCategoryList]get large category list Success.'); return $q.when(results); }).catch(function (err) { console.log('[Service CategoryService getExpenseLargeCategoryList]get large category list Error.'); console.log(err); return $q.when(''); }); ...
if (doc.type ===
identifier_name
services.js
return $q.when(largeCategory); }).then(function (results) { console.log('[Service CategoryService getIncomeLargeCategoryList]get large category list Success.'); return $q.when(results); }).catch(function (err) { console.log('[Service CategoryService getIncomeLargeCategoryList]get large catego...
emit([doc._id], doc);
random_line_split
services.js
or opens if it already exists _db = new PouchDB('users', {adapter: 'websql'}); addUser({username: 'admin', password: 'admin'}); } function addUser(user) { return $q.when(_db.post(user)); } function validUser(user) { _loginFlg = false; angular.forEach(_users, function (tmpUser) { if ...
// 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
events: EventHandler, // FIXME: see if we can implement `Stream` for the `PacketHandler` and use the // `ShutdownStream` type instead. shutdown: ShutdownRecv, state: ReadState, /// The address of the peer. This field is only here for logging purposes. address: Multiaddr, } impl PacketHandle...
} // 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
{ events: EventHandler, // FIXME: see if we can implement `Stream` for the `PacketHandler` and use the // `ShutdownStream` type instead. shutdown: ShutdownRecv, state: ReadState, /// The address of the peer. This field is only here for logging purposes. address: Multiaddr, } impl PacketHan...
(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
{ events: EventHandler, // FIXME: see if we can implement `Stream` for the `PacketHandler` and use the // `ShutdownStream` type instead. shutdown: ShutdownRecv, state: ReadState, /// The address of the peer. This field is only here for logging purposes. address: Multiaddr, } impl PacketHan...
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
_loss, show_samples ######################################################################## # configuration class CONFIG(baseCONFIG): """ Namspace for configuration """ # Data data_mean = 0.128 data_std = 0.305 add_image_noise = 0.08 maxpool = False img_size = (28, 28) devic...
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
_loss, show_samples ######################################################################## # configuration class CONFIG(baseCONFIG): """ Namspace for configuration """ # Data data_mean = 0.128 data_std = 0.305 add_image_noise = 0.08 maxpool = False img_size = (28, 28) devic...
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
_loss, show_samples ######################################################################## # configuration class CONFIG(baseCONFIG): """ Namspace for configuration """ # Data data_mean = 0.128 data_std = 0.305 add_image_noise = 0.08 maxpool = False img_size = (28, 28) devic...
(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
_loss, show_samples ######################################################################## # configuration class CONFIG(baseCONFIG): """ Namspace for configuration """ # Data data_mean = 0.128 data_std = 0.305 add_image_noise = 0.08 maxpool = False img_size = (28, 28) devic...
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
) String() string { return proto.CompactTextString(m) } func (*Session) ProtoMessage() {} func (*Session) Descriptor() ([]byte, []int) { return fileDescriptor_5b53032c0bb76d75, []int{0}
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
) String() string { return proto.CompactTextString(m) } func (*Session) ProtoMessage() {} func (*Session) Descriptor() ([]byte, []int) { return fileDescriptor_5b53032c0bb76d75, []int{0} } func (m *Session) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Session.Unmarshal(m, b) } func (m *Session) XXX_Marsh...
() 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
String() string { return proto.CompactTextString(m) } func (*Session) ProtoMessage() {} func (*Session) Descriptor() ([]byte, []int)
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
String() string { return proto.CompactTextString(m) } func (*Session) ProtoMessage() {} func (*Session) Descriptor() ([]byte, []int) { return fileDescriptor_5b53032c0bb76d75, []int{0} } func (m *Session) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Session.Unmarshal(m, b) } func (m *Session) XXX_Marsha...
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
gotten 0 rows before deadline exceeded") } func TestGroupSingle(t *testing.T) { eTotal := ADD(eA, eB) gx := Group(&goodSource{}, GroupOpts{ By: []GroupBy{NewGroupBy("x", goexpr.Param("x"))}, Fields: StaticFieldSource{ Field{ Name: "total", Expr: eTotal, }, }, Resolution: resolution * 2, AsOf...
TestUnflattenTransform
identifier_name
core_test.go
:= Group(&goodSource{}, GroupOpts{ Fields: StaticFieldSource{ Field{ Name: "total", Expr: eTotal, }, }, Resolution: resolution * 10, }) expectedValues := map[string]float64{ "1.1": 10 + 70, "1.3": 50, "1.5": 90, "2.2": 100, "2.3": 20 + 80, "2.5": 60, } ctx := context.Background() ...
{ more, err := onRow(row.key, row.vals) if !more || err != nil { return nil, err } }
conditional_block
core_test.go
0}, []float64{0, 50}, []float64{0, 0}, []float64{70, 50}, }, [][]float64{ []float64{0, 0}, []float64{0, 0}, []float64{80, 0}, []float64{0, 60}, []float64{80, 60}, }, } gx := Group(&goodSource{}, GroupOpts{ By: []GroupBy{NewGroupBy("x", goexpr.Param("x"))}, Crossta...
return resolution
random_line_split
core_test.go
2.3": 20 + 80, "2.5": 60, } ctx := context.Background() _, err := gx.Iterate(ctx, FieldsIgnored, func(key bytemap.ByteMap, vals Vals) (bool, error) { dims := fmt.Sprintf("%d.%d", key.Get("x"), key.Get("y")) val, _ := vals[0].ValueAt(0, eTotal) expectedVal := expectedValues[dims] delete(expectedValues, dim...
{ return Fields{totalField} }
identifier_body
util.ts
#endif }) } /** * 设置cookie数据 * @param {String} key 键值 * @param {String} data 值 * @returns Boolean */ export function setCookie(key:string, data:any) { try { uni.setStorageSync(key, data); return true; } catch (e) { return false; } } /** * 删除一个本地cookie * @param {String} key 键值 * @returns Boolean ...
} /**
identifier_name
util.ts
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
天前"; } else if (hourC >= 1) { return parseInt(hourC+'') + "小时前"; } else if (minC >= 1) { return parseInt(minC+'') + "分钟前"; } return '刚刚'; } /** * 打电话 * @param {String<Number>} phoneNumber - 数字字符串 * @return {Promise} */ export function callPhone(phoneNumber = '') { let num = phoneNumber.toString() retu...
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
(url,paramData,type,false,function(ret){ _fill_options(_select,ret); }); }); } }); return _select; }; FORM.getSelectedVal = function(sel){ require(['jquery/select2'],function(){ return $(sel).val(); }) } FORM.getSelectedText = function(sel){ require(['jquery/select2'],f...
identifier_body
app-form.js
formField.rules( "add", opts.rules[_fieldName]); } if(_fieldRole == 'select'){ var _selectOpt = opts.fieldOpts[_fieldName] || {}; try{ if(formField.attr('placeholder') && !isInitValue) _selectOpt.placeholder = JSON.parse(formField.attr('placeholder')); }catch(e){alert("placeholder属性值必须为js...
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
var type = "POST"; if(opts.jsonData && opts.jsonData != ""){ url = opts.jsonData; type = "GET"; } var paramData = {}; if(opts.stmID) paramData.stmID=opts.stmID; if(opts.param) paramData.param=opts.param; //同步方式防止数据量大是无法加载 APP.ajax(url,paramData,type,false,function(ret...
} }, callback: {
random_line_split
app-form.js
(url,paramData,type,false,function(ret){ _fill_options(_select,ret); }); }); } }); return _select; }; FORM.getSelectedVal = function(sel){ require(['jquery/select2'],function(){ return $(sel).val(); }) } FORM.getSelectedText = function(sel){ require(['jquery/select2'],f...
identifier_name
instance.rs
.len()]))?; val /= CHARS.len(); } Ok(()) } } #[derive(Debug)] struct ParsedEdgeHandler { edge_incidences: Vec<SkipVec<(NodeIdx, EntryIdx)>>, node_degrees: Vec<usize>, } impl ParsedEdgeHandler { fn handle_edge(&mut self, node_indices: impl IntoIterator<Item = Result<usize>>)...
} /// 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
instance.rs
let ParsedEdgeHandler { mut edge_incidences, node_degrees, } = handler; let mut node_incidences: Vec<_> = node_degrees .iter() .map(|&len| SkipVec::with_len(len)) .collect(); let mut rem_node_degrees = node_degrees; for...
{ write!(writer, " + ")?; }
conditional_block