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
D1.py
#!/usr/bin/python # # Problem: Endless Knight # Language: Python # Author: KirarinSnow # Usage: python thisfile.py <input.in >output.out # Comments: OK for large, but may time out on small. from itertools import * MOD = 10007 # Precompute factorial table mod MOD fact = [1] * MOD for i in xrange(1, MOD): fact[i]...
(): h, w, r = map(int, raw_input().split()) rocks = [map(int, raw_input().split()) for i in range(r)] if (h+w-2)%3 != 0: return 0 # normalize rock coordinates h, w = h-1-(h+w-2)/3, w-1-(h+w-2)/3 for i in range(r): row, col = rocks[i] if (row+col-2)%3 != 0: ...
compute
identifier_name
slack_table_formatter.ts
import * as _ from "underscore" import * as uuid from "uuid" import { IDatum, IQuery, IQueryResponse, IQueryResponseField, IQueryResponseRow} from "../looker_api_types" import { IAttachment, IAttachmentAction, Message } from "../message" import { SlackUtils } from "../slack_utils" export class SlackTableFormatter { ...
else { return(`${shareUrl}\nNo results.`) } } else if (visType === "single_value") { const field = this.measureLike[0] || this.dimensionLike[0] const share = shareUrl ? `\n${shareUrl}` : "" const datum = result.data[0] const rendered = this.renderField(field, datum) cons...
{ const txt = result.errors.map((e) => `${e.message}\`\`\`${e.message_details}\`\`\``).join("\n") return(`:warning: ${shareUrl}\n${txt}`) }
conditional_block
slack_table_formatter.ts
import * as _ from "underscore" import * as uuid from "uuid" import { IDatum, IQuery, IQueryResponse, IQueryResponseField, IQueryResponseRow} from "../looker_api_types" import { IAttachment, IAttachmentAction, Message } from "../message" import { SlackUtils } from "../slack_utils" export class SlackTableFormatter { ...
} private renderFieldLabel(field: IQueryResponseField): string { let showViewNames: boolean if (!this.query.vis_config || typeof this.query.vis_config.show_view_names === "undefined") { showViewNames = true } else { showViewNames = this.query.vis_config.show_view_names } if (showVie...
} }) attachment.callback_id = uuid()
random_line_split
slack_table_formatter.ts
import * as _ from "underscore" import * as uuid from "uuid" import { IDatum, IQuery, IQueryResponse, IQueryResponseField, IQueryResponseRow} from "../looker_api_types" import { IAttachment, IAttachmentAction, Message } from "../message" import { SlackUtils } from "../slack_utils" export class SlackTableFormatter { ...
( private options: {query: IQuery, result: IQueryResponse, baseUrl: string, shareUrl: string}, ) { this.query = options.query this.result = options.result // Handle hidden fields const hiddenFields = this.query.vis_config.hidden_fields || [] if (hiddenFields.length > 0) { for (const k ...
constructor
identifier_name
exactly_one_err.rs
#[cfg(feature = "use_std")] use std::error::Error; use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::iter::ExactSizeIterator; use either::Either; use crate::size_hint;
/// effectively "restores" the state of the input iterator when it's handed back. /// /// This is very similar to PutBackN except this iterator only supports 0-2 elements and does not /// use a `Vec`. #[derive(Clone)] pub struct ExactlyOneError<I> where I: Iterator, { first_two: Option<Either<[I::Item; 2], I::I...
/// Iterator returned for the error case of `IterTools::exactly_one()` /// This iterator yields exactly the same elements as the input iterator. /// /// During the execution of exactly_one the iterator must be mutated. This wrapper
random_line_split
exactly_one_err.rs
#[cfg(feature = "use_std")] use std::error::Error; use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::iter::ExactSizeIterator; use either::Either; use crate::size_hint; /// Iterator returned for the error case of `IterTools::exactly_one()` /// This iterator yields exactly the same elements as ...
, Some(Either::Right(second)) => { write!(f, "ExactlyOneError[Second: {:?}, RemainingIter: {:?}]", second, self.inner) } None => { write!(f, "ExactlyOneError[RemainingIter: {:?}]", self.inner) } } } } #[cfg(feature = "use_std")...
{ write!(f, "ExactlyOneError[First: {:?}, Second: {:?}, RemainingIter: {:?}]", first, second, self.inner) }
conditional_block
exactly_one_err.rs
#[cfg(feature = "use_std")] use std::error::Error; use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::iter::ExactSizeIterator; use either::Either; use crate::size_hint; /// Iterator returned for the error case of `IterTools::exactly_one()` /// This iterator yields exactly the same elements as ...
} impl<I> ExactSizeIterator for ExactlyOneError<I> where I: ExactSizeIterator {} impl<I> Display for ExactlyOneError<I> where I: Iterator, { fn fmt(&self, f: &mut Formatter) -> FmtResult { let additional = self.additional_len(); if additional > 0 { write!(f, "got at least 2 elem...
{ size_hint::add_scalar(self.inner.size_hint(), self.additional_len()) }
identifier_body
exactly_one_err.rs
#[cfg(feature = "use_std")] use std::error::Error; use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::iter::ExactSizeIterator; use either::Either; use crate::size_hint; /// Iterator returned for the error case of `IterTools::exactly_one()` /// This iterator yields exactly the same elements as ...
(&self) -> (usize, Option<usize>) { size_hint::add_scalar(self.inner.size_hint(), self.additional_len()) } } impl<I> ExactSizeIterator for ExactlyOneError<I> where I: ExactSizeIterator {} impl<I> Display for ExactlyOneError<I> where I: Iterator, { fn fmt(&self, f: &mut Formatter) -> FmtResult { ...
size_hint
identifier_name
mappers.py
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
class WPRoomMapperCreation(WPRoomMapperBase): def _getTabContent(self, params): return WRoomMapperEdit().getHTML({ 'postURL': urlHandlers.UHRoomMapperPerformCreation.getURL() }) class WPRoomMapperModification(WPRoomMapperBase): def __init__(self, rh, domain): WPRoomMappe...
wvars = WTemplated.getVars(self) wvars['name'] = self._roomMapper.getName() wvars['description'] = self._roomMapper.getDescription() wvars['url'] = self._roomMapper.getBaseMapURL() wvars['placeName'] = self._roomMapper.getPlaceName() wvars['regexps'] = self._roomMapper.getRegular...
identifier_body
mappers.py
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
(WPRoomMapperBase): def _getTabContent(self, params): return WRoomMapperEdit().getHTML({ 'postURL': urlHandlers.UHRoomMapperPerformCreation.getURL() }) class WPRoomMapperModification(WPRoomMapperBase): def __init__(self, rh, domain): WPRoomMapperBase.__init__(self, rh) ...
WPRoomMapperCreation
identifier_name
mappers.py
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the
# # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with...
# License, or (at your option) any later version.
random_line_split
mappers.py
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
return WRoomMapperList(criteria).getHTML() class WRoomMapperList(WTemplated): def __init__(self, criteria): self._criteria = criteria def _performSearch(self, criteria): return RoomMapperHolder().match(criteria) def getVars(self): wvars = WTemplated.getVars(self) ...
criteria['name'] = self._params.get('sName', '')
conditional_block
environment.staging.ts
export const environment = {
production: true, ci: false, ensemblDomain: 'grch37.rest.ensembl.org', ensemblProtocol: 'https', baseHref: '', auth0ClientId: 'eS2HA6aSYnxCXFvo9bzHpV1DI6H1yw0l', auth0Domain: 'sgc.au.auth0.com', auth0Connection: 'Username-Password-Authentication', beaconNetworkUrl: 'https://beacon-ne...
random_line_split
location.component.ts
import { Component } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { LocationService } from './location.service'; import { Location } from './location.class'; @Component({ selector: 'location', // <location></location> template: ` <leaflet-map [location]="location" draggable=...
ngOnDestroy() { this.sub.unsubscribe(); } updateLocation(latLng: L.LatLng): void { // TODO: Do you want to save location? this.locationService.setPosition(latLng.lat, latLng.lng); } }
{ this.sub = this.locationService.getPosition() .subscribe(position => { this.location = new Location('', [position.coords.latitude, position.coords.longitude]); }, error => {console.log(error); alert('double click map to set location...')}); // TODO: Handle error }
identifier_body
location.component.ts
import { Component } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { LocationService } from './location.service'; import { Location } from './location.class'; @Component({ selector: 'location', // <location></location> template: ` <leaflet-map [location]="location" draggable=...
this.sub = this.locationService.getPosition() .subscribe(position => { this.location = new Location('', [position.coords.latitude, position.coords.longitude]); }, error => {console.log(error); alert('double click map to set location...')}); // TODO: Handle error } ngOnDestroy() { ...
ngOnInit() {
random_line_split
location.component.ts
import { Component } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { LocationService } from './location.service'; import { Location } from './location.class'; @Component({ selector: 'location', // <location></location> template: ` <leaflet-map [location]="location" draggable=...
{ public static pageTitle = 'My Location'; private sub: Subscription; private location: Location; constructor( public locationService: LocationService) { } ngOnInit() { this.sub = this.locationService.getPosition() .subscribe(position => { this.location = new Location('', [position...
LocationComponent
identifier_name
init.js
jQuery(document).ready(function($) { function _reiszeImage(){ $('.card-image').each(function() { var maxWidth = $(this).data('maxwidth'); var maxHeight = $(this).data('maxheight'); var _mratio = maxWidth/maxHeight; var _imageContainer = $(this); $(this).find('img').each(function(index) { var ratio...
var _carousel = $('.card-image', _this).slick({ arrow: false, dots: false, slidesToShow: 1, autoplay: true, autoplaySpeed: _autoplayspeed, slidesToScroll: 1, infinite: false, arrows: false }); var _index = index; _this.find('a.cq-thumb-lightbox').each(function(index) {...
{ var _buttons = $('.card-caption-container .cq-button', _this); _buttons.css('background-color', _buttonbg); _buttons.on('mouseover', function(event) { $(this).css('background-color', _buttonhoverbg); }).on('mouseleave', function(event) { $(this).css('background-color', _buttonbg); }); }
conditional_block
init.js
jQuery(document).ready(function($) { function _reiszeImage()
// _imageContainer.css({ // 'width': maxHeight*ratio // }); // $(this).css("width", maxHeight*ratio); $(this).css("min-width", maxWidth); } }); }); } $('.cq-cards-container').each(function(index) { var _this = $(this); v...
{ $('.card-image').each(function() { var maxWidth = $(this).data('maxwidth'); var maxHeight = $(this).data('maxheight'); var _mratio = maxWidth/maxHeight; var _imageContainer = $(this); $(this).find('img').each(function(index) { var ratio = $(this).data('ratio'); var width = $(this).data(...
identifier_body
init.js
jQuery(document).ready(function($) { function _reiszeImage(){ $('.card-image').each(function() { var maxWidth = $(this).data('maxwidth'); var maxHeight = $(this).data('maxheight'); var _mratio = maxWidth/maxHeight; var _imageContainer = $(this); $(this).find('img').each(function(index) { var ratio...
_buttons.on('mouseover', function(event) { $(this).css('background-color', _buttonhoverbg); }).on('mouseleave', function(event) { $(this).css('background-color', _buttonbg); }); } var _carousel = $('.card-image', _this).slick({ arrow: false, dots: false, slidesToShow: 1, autoplay...
var _buttons = $('.card-caption-container .cq-button', _this); _buttons.css('background-color', _buttonbg);
random_line_split
init.js
jQuery(document).ready(function($) { function
(){ $('.card-image').each(function() { var maxWidth = $(this).data('maxwidth'); var maxHeight = $(this).data('maxheight'); var _mratio = maxWidth/maxHeight; var _imageContainer = $(this); $(this).find('img').each(function(index) { var ratio = $(this).data('ratio'); var width = $(this).dat...
_reiszeImage
identifier_name
url.js
/* url utils @sha0coder */ exports.getUrlDir = function(url) { return url.replace(/\/[^\/]*$/,'/') } exports.getBase = function(url) { var spl = url.split('/'); return spl[0]+'//'+spl[2]; }; exports.getDomain = function(url) { return url.split('/')[2]; }; exports.isDir = functio...
url = url+'/'; return url; }; exports.fixDir = function(dir) { if (dir.charAt(0) == '/') dir = dir.substring(1,dir.length); return dir; };
if (url.charAt(url.length-1) != '/')
random_line_split
storm.js
/* THIS IS JUST A SCRATCH FILE FOR TESTING AND DEBUGGING. Working with JS in PG is still a little raw, so easier to play using node and move across. */ // var json = '{"uuid":"ba596c94-9e50-11e1-a50e-70cd60fffe0e","integer":10,"string":"Blick","date":"2012-05-11T15:42:15+10:00","boolean":true,"numeric":99.9,"o...
(ret) { var ret = ret.boolean; // console.log(ret); // console.log(ret == true); if (ret === true || ret === false) { console.log("bool:"+ret); } else { console.log("null!"); } // if (ret != true || ret != false) { // console.log("null!"); // } else { // console.log("...
test
identifier_name
storm.js
/* THIS IS JUST A SCRATCH FILE FOR TESTING AND DEBUGGING. Working with JS in PG is still a little raw, so easier to play using node and move across. */ // var json = '{"uuid":"ba596c94-9e50-11e1-a50e-70cd60fffe0e","integer":10,"string":"Blick","date":"2012-05-11T15:42:15+10:00","boolean":true,"numeric":99.9,"o...
test(JSON.parse('{"boolean":true}')); test(JSON.parse('{"boolean":false}')); test(JSON.parse('{"boolean":1}')); test(JSON.parse('{"boolean":0}')); test(JSON.parse('{"boolean":"true"}')); test(JSON.parse('{"boolean":"false"}')); test(JSON.parse('{"boolean":"100"}')); // var data ='{"count":[99], "date":"2012-05-0...
{ var ret = ret.boolean; // console.log(ret); // console.log(ret == true); if (ret === true || ret === false) { console.log("bool:"+ret); } else { console.log("null!"); } // if (ret != true || ret != false) { // console.log("null!"); // } else { // console.log("bool:"...
identifier_body
storm.js
/* THIS IS JUST A SCRATCH FILE FOR TESTING AND DEBUGGING. Working with JS in PG is still a little raw, so easier to play using node and move across. */ // var json = '{"uuid":"ba596c94-9e50-11e1-a50e-70cd60fffe0e","integer":10,"string":"Blick","date":"2012-05-11T15:42:15+10:00","boolean":true,"numeric":99.9,"o...
else { console.log("null!"); } // if (ret != true || ret != false) { // console.log("null!"); // } else { // console.log("bool:"+ret); // } } test(JSON.parse('{"boolean":true}')); test(JSON.parse('{"boolean":false}')); test(JSON.parse('{"boolean":1}')); test(JSON.parse('{"boolean":0}'...
{ console.log("bool:"+ret); }
conditional_block
storm.js
/* THIS IS JUST A SCRATCH FILE FOR TESTING AND DEBUGGING. Working with JS in PG is still a little raw, so easier to play using node and move across. */
// var json = '{"uuid":"ba596c94-9e50-11e1-a50e-70cd60fffe0e","integer":10,"string":"Blick","date":"2012-05-11T15:42:15+10:00","boolean":true,"numeric":99.9,"object":{"string":"Ullrich","array":[3428,7389,5166,5823,3566,6086,3087,7690,6374,4531,6019,9722,8793,6732,5264,9618,5843,6714,5160,4065,2102,4972,2778,6110,4357...
random_line_split
sequence_roi_gt_propagation.py
#!/usr/bin/env python # -------------------------------------------------------- # Test regression propagation on ImageNet VID video # Modified by Kai KANG (myfavouritekk@gmail.com) # -------------------------------------------------------- """Test a Fast R-CNN network on an image database.""" import argparse import...
args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() print 'Called with args:' print args if osp.isfile(args.save_file): print "{} already exists.".format(args.save_file) sys.exit(1) vid_proto = proto_load(args.vid_file) box_proto = ...
parser.print_help() sys.exit(1)
conditional_block
sequence_roi_gt_propagation.py
#!/usr/bin/env python # -------------------------------------------------------- # Test regression propagation on ImageNet VID video # Modified by Kai KANG (myfavouritekk@gmail.com) # -------------------------------------------------------- """Test a Fast R-CNN network on an image database.""" import argparse import...
(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Test a Fast R-CNN network') parser.add_argument('vid_file') parser.add_argument('box_file') parser.add_argument('annot_file', default=None, help='Ground truth annotation file. [None]') ...
parse_args
identifier_name
sequence_roi_gt_propagation.py
#!/usr/bin/env python # -------------------------------------------------------- # Test regression propagation on ImageNet VID video # Modified by Kai KANG (myfavouritekk@gmail.com) # -------------------------------------------------------- """Test a Fast R-CNN network on an image database.""" import argparse import...
help='GT overlap threshold for tracking. [0.5]') parser.add_argument('--wait', dest='wait', help='wait until net file exists', default=True, type=bool) parser.set_defaults(vis=False, zip=False, keep_feat=False) if len(sys.argv) == 1: ...
""" Parse input arguments """ parser = argparse.ArgumentParser(description='Test a Fast R-CNN network') parser.add_argument('vid_file') parser.add_argument('box_file') parser.add_argument('annot_file', default=None, help='Ground truth annotation file. [None]') parser....
identifier_body
sequence_roi_gt_propagation.py
#!/usr/bin/env python # -------------------------------------------------------- # Test regression propagation on ImageNet VID video # Modified by Kai KANG (myfavouritekk@gmail.com) # -------------------------------------------------------- """Test a Fast R-CNN network on an image database.""" import argparse import...
vid_proto = proto_load(args.vid_file) box_proto = proto_load(args.box_file) annot_proto = proto_load(args.annot_file) track_proto = gt_motion_propagation(vid_proto, box_proto, annot_proto, window=args.window, length=args.length, sample_rate=args.sample_rate, overlap_thres=args.overlap)...
if osp.isfile(args.save_file): print "{} already exists.".format(args.save_file) sys.exit(1)
random_line_split
spawn.ts
import { GitProcess } from 'dugite' import * as GitPerf from '../../ui/lib/git-perf' import { isErrnoException } from '../errno-exception' import { withTrampolineEnv } from '../trampoline/trampoline-environment' type ProcessOutput = { /** The contents of stdout received from the spawned process */ output: Buffer ...
* @param stdOutMaxLength An optional maximum number of bytes to read from stdout. * If the process writes more than this number of bytes it * will be killed silently and the truncated output is * returned. */ export async function spawnAndCom...
random_line_split
spawn.ts
import { GitProcess } from 'dugite' import * as GitPerf from '../../ui/lib/git-perf' import { isErrnoException } from '../errno-exception' import { withTrampolineEnv } from '../trampoline/trampoline-environment' type ProcessOutput = { /** The contents of stdout received from the spawned process */ output: Buffer ...
( args: string[], path: string, name: string, successExitCodes?: Set<number>, stdOutMaxLength?: number ): Promise<ProcessOutput> { return withTrampolineEnv(env => { const commandName = `${name}: git ${args.join(' ')}` return GitPerf.measure( commandName, () => new Promise<Process...
spawnAndComplete
identifier_name
spawn.ts
import { GitProcess } from 'dugite' import * as GitPerf from '../../ui/lib/git-perf' import { isErrnoException } from '../errno-exception' import { withTrampolineEnv } from '../trampoline/trampoline-environment' type ProcessOutput = { /** The contents of stdout received from the spawned process */ output: Buffer ...
else { reject( new Error( `Git returned an unexpected exit code '${code}' which should be handled by the caller.'` ) ) } }) }) ) }) }
{ resolve({ output: stdout, error: stderr, exitCode: code, }) return }
conditional_block
spawn.ts
import { GitProcess } from 'dugite' import * as GitPerf from '../../ui/lib/git-perf' import { isErrnoException } from '../errno-exception' import { withTrampolineEnv } from '../trampoline/trampoline-environment' type ProcessOutput = { /** The contents of stdout received from the spawned process */ output: Buffer ...
}) let totalStdoutLength = 0 let killSignalSent = false const stdoutChunks = new Array<Buffer>() // If Node.js encounters a synchronous runtime error while spawning // `stdout` will be undefined and the error will be emitted asynchronously if (pro...
{ return withTrampolineEnv(env => { const commandName = `${name}: git ${args.join(' ')}` return GitPerf.measure( commandName, () => new Promise<ProcessOutput>(async (resolve, reject) => { const process = GitProcess.spawn(args, path, { env }) process.on('error', err => ...
identifier_body
lock.py
"""holds locking functionality that works across processes""" from __future__ import absolute_import, unicode_literals from contextlib import contextmanager import py from filelock import FileLock, Timeout from tox.reporter import verbosity1 @contextmanager def hold_lock(lock_file, reporter=verbosity1): py.pat...
"""get a unique file in a folder having a given prefix and suffix, with unique number in between""" lock_file = path.join(".lock") prefix = "{}-".format(prefix) with hold_lock(lock_file): max_value = -1 for candidate in path.listdir("{}*{}".format(prefix, suffix)): try: ...
identifier_body
lock.py
"""holds locking functionality that works across processes""" from __future__ import absolute_import, unicode_literals from contextlib import contextmanager import py
from filelock import FileLock, Timeout from tox.reporter import verbosity1 @contextmanager def hold_lock(lock_file, reporter=verbosity1): py.path.local(lock_file.dirname).ensure(dir=1) lock = FileLock(str(lock_file)) try: try: lock.acquire(0.0001) except Timeout: r...
random_line_split
lock.py
"""holds locking functionality that works across processes""" from __future__ import absolute_import, unicode_literals from contextlib import contextmanager import py from filelock import FileLock, Timeout from tox.reporter import verbosity1 @contextmanager def hold_lock(lock_file, reporter=verbosity1): py.pat...
(path, prefix, suffix): """get a unique file in a folder having a given prefix and suffix, with unique number in between""" lock_file = path.join(".lock") prefix = "{}-".format(prefix) with hold_lock(lock_file): max_value = -1 for candidate in path.listdir("{}*{}".format(prefix, suff...
get_unique_file
identifier_name
lock.py
"""holds locking functionality that works across processes""" from __future__ import absolute_import, unicode_literals from contextlib import contextmanager import py from filelock import FileLock, Timeout from tox.reporter import verbosity1 @contextmanager def hold_lock(lock_file, reporter=verbosity1): py.pat...
winner = path.join("{}{}{}".format(prefix, max_value + 1, suffix)) winner.ensure(dir=0) return winner
try: max_value = max(max_value, int(candidate.basename[len(prefix) : -len(suffix)])) except ValueError: continue
conditional_block
sync_sectors.py
import logging logger = logging.getLogger(__name__) class SyncSectors: def __init__(self, sector_model, sectors, disable_on=None, simulate=False): self.sector_model = sector_model self.sectors = sectors self.disable_on = disable_on self.simulate = simulate def log(self, msg,...
sector.name = sector_name sector.save() def _create_sector(self, sector_id, sector_name): self.log(f'Creating Sector {sector_id}: [{sector_name}]') if self.simulate: return self.sector_model.objects.create(id=sector_id, name=sector_name) def _disable_sector...
if self.simulate: return
random_line_split
sync_sectors.py
import logging logger = logging.getLogger(__name__) class SyncSectors: def __init__(self, sector_model, sectors, disable_on=None, simulate=False): self.sector_model = sector_model self.sectors = sectors self.disable_on = disable_on self.simulate = simulate def log(self, msg,...
def disable_sectors(self): sector_ids = list(dict(self.sectors).keys()) deprecated_sectors = self.sector_model.objects.exclude(id__in=sector_ids).filter( disabled_on__isnull=True ) for sector in deprecated_sectors: self._disable_sector(sector)
self._update_sector_name(sector, sector_name)
conditional_block
sync_sectors.py
import logging logger = logging.getLogger(__name__) class SyncSectors: def __init__(self, sector_model, sectors, disable_on=None, simulate=False): self.sector_model = sector_model self.sectors = sectors self.disable_on = disable_on self.simulate = simulate def log(self, msg,...
(self): sector_ids = list(dict(self.sectors).keys()) deprecated_sectors = self.sector_model.objects.exclude(id__in=sector_ids).filter( disabled_on__isnull=True ) for sector in deprecated_sectors: self._disable_sector(sector)
disable_sectors
identifier_name
sync_sectors.py
import logging logger = logging.getLogger(__name__) class SyncSectors: def __init__(self, sector_model, sectors, disable_on=None, simulate=False): self.sector_model = sector_model self.sectors = sectors self.disable_on = disable_on self.simulate = simulate def log(self, msg,...
def _create_sector(self, sector_id, sector_name): self.log(f'Creating Sector {sector_id}: [{sector_name}]') if self.simulate: return self.sector_model.objects.create(id=sector_id, name=sector_name) def _disable_sector(self, sector): self.log(f'Disabling Sector {se...
if sector.name != sector_name: self.log(f'Updating Sector {sector.id}: [{sector.name} to {sector_name}]') if self.simulate: return sector.name = sector_name sector.save()
identifier_body
text_run.rs
for TextRun { fn drop(&mut self) { // Invalidate the glyph run cache if it was our text run that got freed. INDEX_OF_FIRST_GLYPH_RUN_CACHE.with(|index_of_first_glyph_run_cache| { if let Some((text_run_ptr, _, _)) = index_of_first_glyph_run_cache.get() { if text_run_ptr =...
; impl Comparator<CharIndex, GlyphRun> for CharIndexComparator { fn compare(&self, key: &CharIndex, value: &GlyphRun) -> Ordering { if *key < value.range.begin() { Ordering::Less } else if *key >= value.range.end() { Ordering::Greater } else { Ordering::E...
CharIndexComparator
identifier_name
text_run.rs
to the start of the *text run*. pub offset: CharIndex, /// The range that these glyphs encompass, relative to the start of the *glyph store*. pub range: Range<CharIndex>, } impl<'a> TextRunSlice<'a> { /// Returns the range that these glyphs encompass, relative to the start of the *text run*. #[inl...
} /// Returns an iterator that over natural word slices in visual order (left to right or
random_line_split
match-vec-unreachable.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x: Vec<(isize, isize)> = Vec::new(); let x: &[(isize, isize)] = &x; match *x { [a, (2, 3), _] => (), [(1, 2), (2, 3), b] => (), //~ ERROR unreachable pattern _ => () } let x: Vec<String> = vec!["foo".to_string(), "bar".to_string(), ...
main
identifier_name
match-vec-unreachable.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// except according to those terms. #![feature(slice_patterns)] #![deny(unreachable_patterns)] fn main() { let x: Vec<(isize, isize)> = Vec::new(); let x: &[(isize, isize)] = &x; match *x { [a, (2, 3), _] => (), [(1, 2), (2, 3), b] => (), //~ ERROR unreachable pattern _ => () }...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
match-vec-unreachable.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let x: &[char] = &x; match *x { ['a', 'b', 'c', ref _tail..] => {} ['a', 'b', 'c'] => {} //~ ERROR unreachable pattern _ => {} } }
{ let x: Vec<(isize, isize)> = Vec::new(); let x: &[(isize, isize)] = &x; match *x { [a, (2, 3), _] => (), [(1, 2), (2, 3), b] => (), //~ ERROR unreachable pattern _ => () } let x: Vec<String> = vec!["foo".to_string(), "bar".to_string(), ...
identifier_body
serializers.py
to_representation(self, obj): return obj def to_internal_value(self, data): return data class ProductCommonSerializer(serializers.ModelSerializer): """ Common serializer for the Product model, both for the ProductSummarySerializer and the ProductDetailSerializer. """ price = ...
(self, validated_data): validated_data['cart'] = CartModel.objects.get_or_create_from_request(self.context['request']) return super(CartItemSerializer, self).create(validated_data) class WatchItemSerializer(BaseItemSerializer): class Meta(BaseItemSerializer.Meta): list_serializer_class = W...
create
identifier_name
serializers.py
class ProductCommonSerializer(serializers.ModelSerializer): """ Common serializer for the Product model, both for the ProductSummarySerializer and the ProductDetailSerializer. """ price = serializers.SerializerMethodField() availability = serializers.SerializerMethodField() def get_price(...
def to_representation(self, obj): return obj def to_internal_value(self, data): return data
random_line_split
serializers.py
class JSONSerializerField(serializers.Field): """ Serializer field which transparently bypasses its object instead of serializing/deserializing. """ def to_representation(self, obj): return obj def to_internal_value(self, data): return data class ProductCommonSerializer(seriali...
return OrderedDict(data)
identifier_body
serializers.py
to_representation(self, obj): return obj def to_internal_value(self, data): return data class ProductCommonSerializer(serializers.ModelSerializer): """ Common serializer for the Product model, both for the ProductSummarySerializer and the ProductDetailSerializer. """ price = ...
new_class = super(cls, SerializerRegistryMetaclass).__new__(cls, clsname, bases, attrs) if clsname != 'ProductSummarySerializerBase': product_summary_serializer_class = new_class return new_class product_summary_serializer_class = None class ProductSummarySerializerBase(with_meta...
msg = "Class `{}` inheriting from `ProductSummarySerializerBase` already registred." raise exceptions.ImproperlyConfigured(msg.format(product_summary_serializer_class.__name__))
conditional_block
sdc-modal.component.ts
import { ModalOptions } from './../table-component/table.objects'; // tslint:disable-next-line:max-line-length import { Component, ViewChild, ViewContainerRef, Input, Output, EventEmitter, ElementRef, AfterContentInit, OnDestroy } from '@angular/core'; @Component({ selector: 'sdc-modal', templateUrl: './sdc-modal....
private closeModal(): void { this.hideModal = true; this.container.clear() ; } }
{ if (this.componentFactory !== undefined && this.componentFactory !== null) { let messageComponent = this.container.createComponent(this.componentFactory); if (this.objectToPassToComponent) { messageComponent.instance['data'] = this.objectToPassToComponent; } messageComponent.instan...
identifier_body
sdc-modal.component.ts
import { ModalOptions } from './../table-component/table.objects'; // tslint:disable-next-line:max-line-length import { Component, ViewChild, ViewContainerRef, Input, Output, EventEmitter, ElementRef, AfterContentInit, OnDestroy } from '@angular/core'; @Component({ selector: 'sdc-modal', templateUrl: './sdc-modal....
@ViewChild('container', { read: ViewContainerRef }) private container: ViewContainerRef; @Input() private componentFactory: any; @Input() private modalSettings: ModalOptions = { styles: { background: { rgbaColor: 'rgba(106, 108, 112, 0.7)' }, dialog: { rgbaColor: 'rgba(255, 2...
random_line_split
sdc-modal.component.ts
import { ModalOptions } from './../table-component/table.objects'; // tslint:disable-next-line:max-line-length import { Component, ViewChild, ViewContainerRef, Input, Output, EventEmitter, ElementRef, AfterContentInit, OnDestroy } from '@angular/core'; @Component({ selector: 'sdc-modal', templateUrl: './sdc-modal....
messageComponent.instance['change'].subscribe(change => { this.change.emit({data: change}); }); messageComponent.instance['close'].subscribe(() => { this.closeModal(); }); } else { // tslint:disable-next-line:max-line-length console.log('Error loading component. ...
{ messageComponent.instance['data'] = this.objectToPassToComponent; }
conditional_block
sdc-modal.component.ts
import { ModalOptions } from './../table-component/table.objects'; // tslint:disable-next-line:max-line-length import { Component, ViewChild, ViewContainerRef, Input, Output, EventEmitter, ElementRef, AfterContentInit, OnDestroy } from '@angular/core'; @Component({ selector: 'sdc-modal', templateUrl: './sdc-modal....
(): void { this.hideModal = true; this.container.clear() ; } }
closeModal
identifier_name
jsonb.py
import json from psycopg2.extras import Json from django.contrib.postgres import forms, lookups from django.core import exceptions from django.db.models import Field, Transform from django.utils.translation import ugettext_lazy as _ __all__ = ['JSONField'] class JSONField(Field): empty_strings_all...
return super(JSONField, self).get_prep_lookup(lookup_type, value) def validate(self, value, model_instance): super(JSONField, self).validate(value, model_instance) try: json.dumps(value) except TypeError: raise exceptions.ValidationError( ...
return Json(value)
conditional_block
jsonb.py
import json from psycopg2.extras import Json from django.contrib.postgres import forms, lookups from django.core import exceptions from django.db.models import Field, Transform from django.utils.translation import ugettext_lazy as _ __all__ = ['JSONField'] class JSONField(Field): empty_strings_all...
return value def get_prep_lookup(self, lookup_type, value): if lookup_type in ('has_key', 'has_keys', 'has_any_keys'): return value if isinstance(value, (dict, list)): return Json(value) return super(JSONField, self).get_prep_lookup(lookup_type, value)...
random_line_split
jsonb.py
import json from psycopg2.extras import Json from django.contrib.postgres import forms, lookups from django.core import exceptions from django.db.models import Field, Transform from django.utils.translation import ugettext_lazy as _ __all__ = ['JSONField'] class JSONField(Field): empty_strings_all...
(self, name): transform = super(JSONField, self).get_transform(name) if transform: return transform return KeyTransformFactory(name) def get_prep_value(self, value): if value is not None: return Json(value) return value def get_prep_lo...
get_transform
identifier_name
jsonb.py
import json from psycopg2.extras import Json from django.contrib.postgres import forms, lookups from django.core import exceptions from django.db.models import Field, Transform from django.utils.translation import ugettext_lazy as _ __all__ = ['JSONField'] class JSONField(Field): empty_strings_all...
JSONField.register_lookup(lookups.DataContains) JSONField.register_lookup(lookups.ContainedBy) JSONField.register_lookup(lookups.HasKey) JSONField.register_lookup(lookups.HasKeys) JSONField.register_lookup(lookups.HasAnyKeys) class KeyTransform(Transform): def __init__(self, key_name, *args, **kwa...
defaults = {'form_class': forms.JSONField} defaults.update(kwargs) return super(JSONField, self).formfield(**defaults)
identifier_body
marketplace.js
评分 rating: { type: Number, decimal: true, optional: true, min: 0, max: 1 }, // 商家支持那些语言 lang: { type: [String], allowedValues: ["en", "zh", "local"], maxCount: 3, optional: true }, // 商家资质 qualifications: { type: [String], allowedValues: [], optional: true ...
data: { type: Object, // allowedKeys: ['userId'|'memo'|'amount'|'reason'] blackbox: true, optional: true } }); // 订单 Marketplace.Order = new SimpleSchema({ // 订单编号 orderId: { type: Number, min: 1 }, // 消费者的用户名 consumerId: { type: Number, min: 1
// 附加数据
random_line_split
utils.py
# Copyright 2018 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
"""Parse the resource creation time from its name. The resource name should be in the format "TYPE-YYYYMMDDHHMMSS-HASH", and the time should be in utc. Args: resource_name: Name of the resource to parse. Returns: Creation time of the resource. """ # The time string is like "2...
identifier_body
utils.py
# Copyright 2018 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
(resource_type: str = '', hash_len: int = 4, timestamp_format: str = TIMESTAMP_FORMAT, delimiter: chr = '-') -> str: """Generate resource names as TYPE-YYYYMMDD-HHMMSS-HASH. This function is useful to avoid operations on the same resource when ...
get_resource_name
identifier_name
utils.py
# Copyright 2018 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
This function is useful to avoid operations on the same resource when running integration tests simultaneously. Args: resource_type: Type of the resource which needs to generated name. hash_len: The length of hash at the end of generated name. timestamp_format: The timestamp format...
timestamp_format: str = TIMESTAMP_FORMAT, delimiter: chr = '-') -> str: """Generate resource names as TYPE-YYYYMMDD-HHMMSS-HASH.
random_line_split
hashset.rs
use std::collections::HashSet; fn main() { let mut a: HashSet<i32> = vec!(1i32, 2, 3).into_iter().collect(); let mut b: HashSet<i32> = vec!(2i32, 3, 4).into_iter().collect(); assert!(a.insert(4)); assert!(a.contains(&4)); // `HashSet::insert()` returns false if // there was a value already pr...
// If a collection's element type implements `Show`, // then the collection implements `Show`. // It usually prints its elements in the format `[elem1, elem2, ...]` println!("A: {:?}", a); println!("B: {:?}", b); // Print [1, 2, 3, 4, 5] in arbitrary order println!("Union: {:?}", a.union(&...
assert!(b.insert(4), "Value 4 is already in set B!"); // FIXME ^ Comment out this line b.insert(5);
random_line_split
hashset.rs
use std::collections::HashSet; fn main()
// Print [1, 2, 3, 4, 5] in arbitrary order println!("Union: {:?}", a.union(&b).collect::<Vec<&i32>>()); // This should print [1] println!("Difference: {:?}", a.difference(&b).collect::<Vec<&i32>>()); // Print [2, 3, 4] in arbitrary order. println!("Intersection: {:?}", a.intersection(&b).coll...
{ let mut a: HashSet<i32> = vec!(1i32, 2, 3).into_iter().collect(); let mut b: HashSet<i32> = vec!(2i32, 3, 4).into_iter().collect(); assert!(a.insert(4)); assert!(a.contains(&4)); // `HashSet::insert()` returns false if // there was a value already present. assert!(b.insert(4), "Value 4 i...
identifier_body
hashset.rs
use std::collections::HashSet; fn
() { let mut a: HashSet<i32> = vec!(1i32, 2, 3).into_iter().collect(); let mut b: HashSet<i32> = vec!(2i32, 3, 4).into_iter().collect(); assert!(a.insert(4)); assert!(a.contains(&4)); // `HashSet::insert()` returns false if // there was a value already present. assert!(b.insert(4), "Value ...
main
identifier_name
optional.rs
use crate::reflect::value::value_ref::ReflectValueMut; use crate::reflect::ReflectValueBox; use crate::reflect::ReflectValueRef; use crate::reflect::RuntimeTypeBox; #[derive(Debug, Clone)] pub(crate) struct DynamicOptional { elem: RuntimeTypeBox, value: Option<ReflectValueBox>, }
impl DynamicOptional { pub fn none(elem: RuntimeTypeBox) -> DynamicOptional { DynamicOptional { elem, value: None } } pub fn mut_or_default(&mut self) -> ReflectValueMut { if let None = self.value { self.value = Some(self.elem.default_value_ref().to_box()); } sel...
random_line_split
optional.rs
use crate::reflect::value::value_ref::ReflectValueMut; use crate::reflect::ReflectValueBox; use crate::reflect::ReflectValueRef; use crate::reflect::RuntimeTypeBox; #[derive(Debug, Clone)] pub(crate) struct DynamicOptional { elem: RuntimeTypeBox, value: Option<ReflectValueBox>, } impl DynamicOptional { pu...
(&self) -> Option<ReflectValueRef> { self.value.as_ref().map(ReflectValueBox::as_value_ref) } pub fn set(&mut self, value: ReflectValueBox) { assert_eq!(value.get_type(), self.elem); self.value = Some(value); } }
get
identifier_name
optional.rs
use crate::reflect::value::value_ref::ReflectValueMut; use crate::reflect::ReflectValueBox; use crate::reflect::ReflectValueRef; use crate::reflect::RuntimeTypeBox; #[derive(Debug, Clone)] pub(crate) struct DynamicOptional { elem: RuntimeTypeBox, value: Option<ReflectValueBox>, } impl DynamicOptional { pu...
pub fn mut_or_default(&mut self) -> ReflectValueMut { if let None = self.value { self.value = Some(self.elem.default_value_ref().to_box()); } self.value.as_mut().unwrap().as_value_mut() } pub fn clear(&mut self) { self.value = None; } pub fn get(&self)...
{ DynamicOptional { elem, value: None } }
identifier_body
optional.rs
use crate::reflect::value::value_ref::ReflectValueMut; use crate::reflect::ReflectValueBox; use crate::reflect::ReflectValueRef; use crate::reflect::RuntimeTypeBox; #[derive(Debug, Clone)] pub(crate) struct DynamicOptional { elem: RuntimeTypeBox, value: Option<ReflectValueBox>, } impl DynamicOptional { pu...
self.value.as_mut().unwrap().as_value_mut() } pub fn clear(&mut self) { self.value = None; } pub fn get(&self) -> Option<ReflectValueRef> { self.value.as_ref().map(ReflectValueBox::as_value_ref) } pub fn set(&mut self, value: ReflectValueBox) { assert_eq!(valu...
{ self.value = Some(self.elem.default_value_ref().to_box()); }
conditional_block
users.py
import collections from django.conf import settings from django.contrib.auth.models import User, Group from django.core.cache import cache from django.contrib import messages from django.shortcuts import render, redirect from django.db import transaction from django.db.models import Q from funfactory.urlresolvers imp...
item['is_superuser'] = True if user.id in contributor_ids: item['is_contributor'] = True if not user.is_active: item['is_inactive'] = True if groups_map[user.id]: item['groups'] = groups_map[user.id] users.append(item) return users @...
# javascript, doing `if (thing.something)` works equally if it # exists and is false or if it does not exist. if user.is_staff: item['is_staff'] = True if user.is_superuser:
random_line_split
users.py
import collections from django.conf import settings from django.contrib.auth.models import User, Group from django.core.cache import cache from django.contrib import messages from django.shortcuts import render, redirect from django.db import transaction from django.db.models import Q from funfactory.urlresolvers imp...
return render(request, 'manage/user_edit.html', {'form': form, 'user': user})
form = forms.UserEditForm(instance=user)
conditional_block
users.py
import collections from django.conf import settings from django.contrib.auth.models import User, Group from django.core.cache import cache from django.contrib import messages from django.shortcuts import render, redirect from django.db import transaction from django.db.models import Q from funfactory.urlresolvers imp...
(request, id): """Editing an individual user.""" user = User.objects.get(id=id) if request.method == 'POST': form = forms.UserEditForm(request.POST, instance=user) if form.is_valid(): form.save() messages.info(request, 'User %s saved.' % user.email) return...
user_edit
identifier_name
users.py
import collections from django.conf import settings from django.contrib.auth.models import User, Group from django.core.cache import cache from django.contrib import messages from django.shortcuts import render, redirect from django.db import transaction from django.db.models import Q from funfactory.urlresolvers imp...
"""Editing an individual user.""" user = User.objects.get(id=id) if request.method == 'POST': form = forms.UserEditForm(request.POST, instance=user) if form.is_valid(): form.save() messages.info(request, 'User %s saved.' % user.email) return redirect('manage:u...
identifier_body
simpleeval_multi.py
from net.grinder.script.Grinder import grinder from net.grinder.script import Test from net.grinder.plugin.http import HTTPRequest from HTTPClient import NVPair from java.util import Random newCellTest = Test(1, "Make a new Cell") evaluationTest = Test(2, "Evaluate") updateTest = Test(3, "Poll until evaluated") delete...
: def __call__(self): random = Random() worksheet = random.nextInt(10) base_url = 'http://localhost:8080/home/admin/%s' % worksheet request = newCellTest.wrap(HTTPRequest(url=base_url + "/new_cell_after")) result = request.POST((NVPair("id","0"),)) new_cell = result....
TestRunner
identifier_name
simpleeval_multi.py
from net.grinder.script.Grinder import grinder from net.grinder.script import Test from net.grinder.plugin.http import HTTPRequest from HTTPClient import NVPair from java.util import Random newCellTest = Test(1, "Make a new Cell") evaluationTest = Test(2, "Evaluate") updateTest = Test(3, "Poll until evaluated") delete...
request = deleteCellTest.wrap(HTTPRequest(url=base_url + "/delete_cell")) getData = ( NVPair("id", new_cell),) result = request.POST(getData) def strip_answer(text): #<pre class="shrunk">532962756677</pre> st = text.find('<pre') end = text.find('</pre>') return text[st + 20 : end]...
print 'wait',count,'test',a,'*',b,'=', strip_answer(result.text) break
conditional_block
simpleeval_multi.py
from net.grinder.script.Grinder import grinder from net.grinder.script import Test from net.grinder.plugin.http import HTTPRequest from HTTPClient import NVPair from java.util import Random newCellTest = Test(1, "Make a new Cell") evaluationTest = Test(2, "Evaluate") updateTest = Test(3, "Poll until evaluated") delete...
#<pre class="shrunk">532962756677</pre> st = text.find('<pre') end = text.find('</pre>') return text[st + 20 : end]
random_line_split
simpleeval_multi.py
from net.grinder.script.Grinder import grinder from net.grinder.script import Test from net.grinder.plugin.http import HTTPRequest from HTTPClient import NVPair from java.util import Random newCellTest = Test(1, "Make a new Cell") evaluationTest = Test(2, "Evaluate") updateTest = Test(3, "Poll until evaluated") delete...
result = request.POST(getData) count += 1 if result.text.find('pre') != -1: print 'wait',count,'test',a,'*',b,'=', strip_answer(result.text) break request = deleteCellTest.wrap(HTTPRequest(url=base_url + "/delete_cell")) g...
def __call__(self): random = Random() worksheet = random.nextInt(10) base_url = 'http://localhost:8080/home/admin/%s' % worksheet request = newCellTest.wrap(HTTPRequest(url=base_url + "/new_cell_after")) result = request.POST((NVPair("id","0"),)) new_cell = result.text.s...
identifier_body
color.rs
(|i| CalcNode::parse_number_or_percentage(self.0, i)) }, t => return Err(location.new_unexpected_token_error(t)), } } } impl Parse for Color { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { /...
{ Color::parse(context, input).map(MozFontSmoothingBackgroundColor) }
identifier_body
color.rs
/// Used to button text color when hovered. MozButtonhovertext, /// Used for menu item backgrounds when hovered. MozMenuhover, /// Used for menu item text when hovered. MozMenuhovertext, /// Used for menubar item text. MozMenubartext, /// Used for menubar item text when hovered. ...
currentcolor
identifier_name
color.rs
TextSelectBackgroundAttention, #[css(skip)] TextHighlightBackground, #[css(skip)] TextHighlightForeground, #[css(skip)] IMERawInputBackground, #[css(skip)] IMERawInputForeground, #[css(skip)] IMERawInputUnderline, #[css(skip)] IMESelectedRawTextBackground, #[css(s...
#[css(skip)] TextSelectForegroundCustom, #[css(skip)] TextSelectBackgroundDisabled, #[css(skip)]
random_line_split
step_kw25_classification.py
# coding=utf-8 """ InaSAFE Disaster risk assessment tool by AusAid -**InaSAFE Wizard** This module provides: Keyword Wizard Step: Classification Selector Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Pu...
(self): """Set widgets on the Classification tab.""" self.clear_further_steps() purpose = self.parent.step_kw_purpose.selected_purpose()['name'] subcategory = self.parent.step_kw_subcategory.\ selected_subcategory()['name'] self.lstClassifications.clear() self...
set_widgets
identifier_name
step_kw25_classification.py
# coding=utf-8 """ InaSAFE Disaster risk assessment tool by AusAid -**InaSAFE Wizard** This module provides: Keyword Wizard Step: Classification Selector Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Pu...
return new_step def classifications_for_layer(self): """Return a list of valid classifications for a layer. :returns: A list where each value represents a valid classification. :rtype: list """ layer_geometry_id = self.parent.get_layer_geometry_id() layer_m...
new_step = self.parent.step_kw_field
conditional_block
step_kw25_classification.py
# coding=utf-8 """ InaSAFE Disaster risk assessment tool by AusAid -**InaSAFE Wizard** This module provides: Keyword Wizard Step: Classification Selector Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Pu...
def classifications_for_layer(self): """Return a list of valid classifications for a layer. :returns: A list where each value represents a valid classification. :rtype: list """ layer_geometry_id = self.parent.get_layer_geometry_id() layer_mode_id = self.parent.ste...
"""Find the proper step when user clicks the Next button. :returns: The step to be switched to :rtype: WizardStep instance or None """ if is_raster_layer(self.parent.layer): new_step = self.parent.step_kw_classify else: new_step = self.parent.step_kw_fiel...
identifier_body
step_kw25_classification.py
# coding=utf-8 """ InaSAFE Disaster risk assessment tool by AusAid -**InaSAFE Wizard** This module provides: Keyword Wizard Step: Classification Selector Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Pu...
classifications.index(classification_keyword)) self.auto_select_one_item(self.lstClassifications)
item = self.lstClassifications.item(index) classifications.append(item.data(QtCore.Qt.UserRole)) if classification_keyword in classifications: self.lstClassifications.setCurrentRow(
random_line_split
daily-schedule-visits.component.ts
import { Component, OnInit, OnDestroy, Input } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { BehaviorSubject, Subscription } from 'rxjs'; import * as Moment from 'moment'; import { ClinicDashboardCacheService } from '../../clinic-dashboard/services/clinic-dashboard-cache.service'; i...
this.nextStartIndex = 0; this.errors = []; this.dailyVisitsPatientList = []; } private getDailyVisits(params) { this.setBusy(); this.loadingDailyVisits = true; this.clinicDashboardCacheService.setIsLoading(this.loadingDailyVisits); const result = this.dailyScheduleResource.getDailyVisit...
this.dataLoaded = false;
random_line_split
daily-schedule-visits.component.ts
import { Component, OnInit, OnDestroy, Input } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { BehaviorSubject, Subscription } from 'rxjs'; import * as Moment from 'moment'; import { ClinicDashboardCacheService } from '../../clinic-dashboard/services/clinic-dashboard-cache.service'; i...
if (this.params.encounterType && this.params.encounterType.length > 0) { encounterType = this.params.encounterType; } if (this.params.startDate) { this.selectedDate = this.params.startDate; } else { this.selectedDate = Moment().format('YYYY-MM-DD'); } return { startDate:...
{ visitType = this.params.visitType; }
conditional_block
daily-schedule-visits.component.ts
import { Component, OnInit, OnDestroy, Input } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { BehaviorSubject, Subscription } from 'rxjs'; import * as Moment from 'moment'; import { ClinicDashboardCacheService } from '../../clinic-dashboard/services/clinic-dashboard-cache.service'; i...
public loadMoreVisits() { this.loadingDailyVisits = true; this.clinicDashboardCacheService.setIsLoading(this.loadingDailyVisits); const params = this.getQueryParams(); this.getDailyVisits(params); } public getQueryParams() { let programType: any = []; let visitType: any = []; let en...
{ const routeSub = this.route.queryParams.subscribe((params) => { if (params) { if (params.programType || params.department) { this.initParams(); this.params = params; const searchParams = this.getQueryParams(); if (params.resetFilter && params.resetFilter === '...
identifier_body
daily-schedule-visits.component.ts
import { Component, OnInit, OnDestroy, Input } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { BehaviorSubject, Subscription } from 'rxjs'; import * as Moment from 'moment'; import { ClinicDashboardCacheService } from '../../clinic-dashboard/services/clinic-dashboard-cache.service'; i...
() { this.loadingDailyVisits = false; this.clinicDashboardCacheService.setIsLoading(this.loadingDailyVisits); this.dataLoaded = false; this.nextStartIndex = 0; this.errors = []; this.dailyVisitsPatientList = []; } private getDailyVisits(params) { this.setBusy(); this.loadingDailyVis...
initParams
identifier_name
test_migrations_util.py
import unittest from db.migrations import migrations_util class TestMigrationUtil(unittest.TestCase): """Test the CLI API.""" @classmethod def setUpClass(cls): cls.db_path = '/some/random/path/file.db' def setUp(self): self.parser = migrations_util.make_argument_parser(self.db_path)...
(self): options = self.parser.parse_args(['upgrade']) self.assertEqual(options.path, self.db_path) self.assertEqual(options.action, 'upgrade') def test_cli_parser_user(self): other_db_path = '/some/other/path/file.db' options = self.parser.parse_args([ 'downgrad...
test_cli_parser_default
identifier_name
test_migrations_util.py
import unittest from db.migrations import migrations_util class TestMigrationUtil(unittest.TestCase): """Test the CLI API.""" @classmethod def setUpClass(cls): cls.db_path = '/some/random/path/file.db' def setUp(self): self.parser = migrations_util.make_argument_parser(self.db_path)...
unittest.main()
conditional_block
test_migrations_util.py
import unittest from db.migrations import migrations_util class TestMigrationUtil(unittest.TestCase): """Test the CLI API.""" @classmethod def setUpClass(cls): cls.db_path = '/some/random/path/file.db' def setUp(self): self.parser = migrations_util.make_argument_parser(self.db_path)...
def test_cli_parser_user(self): other_db_path = '/some/other/path/file.db' options = self.parser.parse_args([ 'downgrade', '--path', other_db_path ]) self.assertEqual(options.path, other_db_path) self.assertEqual(options.action, 'downgrade...
self.assertEqual(options.action, 'upgrade')
random_line_split
test_migrations_util.py
import unittest from db.migrations import migrations_util class TestMigrationUtil(unittest.TestCase): """Test the CLI API.""" @classmethod def setUpClass(cls): cls.db_path = '/some/random/path/file.db' def setUp(self): self.parser = migrations_util.make_argument_parser(self.db_path)...
def test_cli_parser_user(self): other_db_path = '/some/other/path/file.db' options = self.parser.parse_args([ 'downgrade', '--path', other_db_path ]) self.assertEqual(options.path, other_db_path) self.assertEqual(options.action, 'downgra...
options = self.parser.parse_args(['upgrade']) self.assertEqual(options.path, self.db_path) self.assertEqual(options.action, 'upgrade')
identifier_body
tests.py
"""Tests the challenge_mgr module.""" import datetime from django.contrib.auth.models import User from django.test import TransactionTestCase from django.core.urlresolvers import reverse from apps.managers.challenge_mgr import challenge_mgr from apps.managers.challenge_mgr.models import RoundSetting from apps.utils ...
(TransactionTestCase): """Tests that the proper variables are loaded into a page.""" def testRoundInfo(self): """Tests that round info is available for the page to process.""" challenge_mgr.init() test_utils.set_competition_round() current_round = challenge_mgr.get_round_name() ...
ContextProcessorFunctionalTestCase
identifier_name
tests.py
"""Tests the challenge_mgr module.""" import datetime from django.contrib.auth.models import User from django.test import TransactionTestCase from django.core.urlresolvers import reverse from apps.managers.challenge_mgr import challenge_mgr from apps.managers.challenge_mgr.models import RoundSetting from apps.utils ...
class BaseUnitTestCase(TransactionTestCase): """basic setting test""" def testCurrentRound(self): """Tests that the current round retrieval is correct.""" current_round = "Round 1" test_utils.set_competition_round() current = challenge_mgr.get_round_name() self.asser...
"""Tests that the proper variables are loaded into a page.""" def testRoundInfo(self): """Tests that round info is available for the page to process.""" challenge_mgr.init() test_utils.set_competition_round() current_round = challenge_mgr.get_round_name() User.objects.creat...
identifier_body
tests.py
"""Tests the challenge_mgr module.""" import datetime from django.contrib.auth.models import User from django.test import TransactionTestCase from django.core.urlresolvers import reverse from apps.managers.challenge_mgr import challenge_mgr from apps.managers.challenge_mgr.models import RoundSetting from apps.utils ...
current_round = challenge_mgr.get_round_name() self.assertTrue(current_round is None, "Test that there is no current round.")
random_line_split
num.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T>(x: T, base: u8) -> RadixFmt<T, Radix> { RadixFmt(x, Radix::new(base)) } macro_rules! radix_fmt { ($T:ty as $U:ty, $fmt:ident) => { impl fmt::Show for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RadixFmt(ref x, radix) => radi...
radix
identifier_name
num.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
f.pad_integral(is_positive, self.prefix(), buf.slice_from(curr)) } } /// A binary (base 2) radix #[deriving(Clone, PartialEq)] struct Binary; /// An octal (base 8) radix #[deriving(Clone, PartialEq)] struct Octal; /// A decimal (base 10) radix #[deriving(Clone, PartialEq)] struct Decimal; /// A hexadec...
{ // Do the same as above, but accounting for two's complement. for byte in buf.iter_mut().rev() { let n = -(x % base); // Get the current place value. x = x / base; // Deaccumulate the number. *byte...
conditional_block
num.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } /// A binary (base 2) radix #[deriving(Clone, PartialEq)] struct Binary; /// An octal (base 8) radix #[deriving(Clone, PartialEq)] struct Octal; /// A decimal (base 10) radix #[deriving(Clone, PartialEq)] struct Decimal; /// A hexadecimal (base 16) radix, formatted with lower-case characters #[deriving(Clon...
random_line_split
router-active.directive.ts
import {Router} from 'angular2/router'; import {isPresent} from 'angular2/src/facade/lang'; import { Directive, Query, QueryList, Attribute, ElementRef, Renderer, Optional, Input } from 'angular2/core'; import {Instruction, RouterLink} from 'angular2/router'; /** * RouterActive dynamically finds the f...
}); } private _findRootRouter(): Router { let router: Router = this.router; while (isPresent(router.parent)) { router = router.parent; } return router; } private _updateClass() { let active = this.routerLink.first.isRouteActive; this.renderer.setElementClass(this.element.nat...
{ this._updateClass(); this._findRootRouter().subscribe(() => { this._updateClass(); }); }
conditional_block
router-active.directive.ts
import {Router} from 'angular2/router'; import {isPresent} from 'angular2/src/facade/lang';
QueryList, Attribute, ElementRef, Renderer, Optional, Input } from 'angular2/core'; import {Instruction, RouterLink} from 'angular2/router'; /** * RouterActive dynamically finds the first element with routerLink and toggles the active class * * ## Use * * ``` * <li router-active="active"><a [routerLi...
import { Directive, Query,
random_line_split