file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
itSystemService.ts
module Kitos.Services { "use strict"; interface ISystemRoleModel { Id: number; HasReadAccess: boolean; HasWriteAccess: boolean;
Description?: any; ObjectOwnerId: number; LastChanged: Date; LastChangedByUserId: number; } interface ISystemRightsModel { Id: number; UserId: number; RoleId: number; ObjectId: number; ObjectOwnerId: number; LastChanged: Date; ...
Name: string; IsActive: boolean;
random_line_split
itSystemService.ts
module Kitos.Services { "use strict"; interface ISystemRoleModel { Id: number; HasReadAccess: boolean; HasWriteAccess: boolean; Name: string; IsActive: boolean; Description?: any; ObjectOwnerId: number; LastChanged: Date; LastChangedByUse...
rivate $http: IHttpServiceWithCustomConfig) { } GetSystemById = (id: number) => { return this.$http.get<Models.ItSystem.IItSystem>(`odata/ItSystems(${id})`); } GetAllSystems = () => { return this.$http.get<Models.ItSystem.IItSystem>(`odata/ItSystems`); }...
nstructor(p
identifier_name
http.py
import logging import ssl from typing import List # pylint: disable=unused-import import aiohttp import certifi import trio_asyncio from aiohttp.http_exceptions import HttpProcessingError from .base import BufferedFree, Limit, Sink, Source logger = logging.getLogger(__name__) class AiohttpClientSessionMixin: ...
buf = await self.response.content.read(count) if len(buf) == 0: await self._close() return buf async def _close(self): self._eof = True if not self.response is None: await self.response.release() self.response = None await self.cl...
count = DEFAULT_CHUNK_SIZE
conditional_block
http.py
import logging import ssl from typing import List # pylint: disable=unused-import import aiohttp import certifi import trio_asyncio from aiohttp.http_exceptions import HttpProcessingError from .base import BufferedFree, Limit, Sink, Source logger = logging.getLogger(__name__) class AiohttpClientSessionMixin: ...
(self, count=-1): if self._eof: return b"" if self.response is None: self.response = await self.client.get(self.url) self.response.raise_for_status() if count == -1: count = DEFAULT_CHUNK_SIZE buf = await self.response.content.read(count) ...
read
identifier_name
http.py
import logging import ssl from typing import List # pylint: disable=unused-import import aiohttp import certifi import trio_asyncio from aiohttp.http_exceptions import HttpProcessingError from .base import BufferedFree, Limit, Sink, Source logger = logging.getLogger(__name__) class AiohttpClientSessionMixin: ...
url = self._urls[self._url_idx] logger.debug("Uploading to: %s (max. %d bytes)", url, self._chunksize) size = ( None if self.total_size is None else min(self.total_size - self.bytes_written, self._chunksize) ) writer = ( self.input ...
async def read(self, count=-1): assert self.input is not None if self._url_idx >= len(self._urls): return b""
random_line_split
http.py
import logging import ssl from typing import List # pylint: disable=unused-import import aiohttp import certifi import trio_asyncio from aiohttp.http_exceptions import HttpProcessingError from .base import BufferedFree, Limit, Sink, Source logger = logging.getLogger(__name__) class AiohttpClientSessionMixin: ...
async def feed_http_upload(): while True: buf = await read_from_input() if len(buf) == 0: break yield buf self.bytes_written += len(buf) logger.debug('HTTP PUT %s', self.url...
assert self.input is not None return (await self.input.read())
identifier_body
terminalEditorSerializer.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(editorInput: TerminalEditorInput): string | undefined { if (!editorInput.terminalInstance?.persistentProcessId || !editorInput.terminalInstance.shouldPersist) { return; } const term = JSON.stringify(this._toJson(editorInput.terminalInstance)); return term; } public deserialize(instantiationService: IInst...
serialize
identifier_name
terminalEditorSerializer.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
const term = JSON.stringify(this._toJson(editorInput.terminalInstance)); return term; } public deserialize(instantiationService: IInstantiationService, serializedEditorInput: string): EditorInput | undefined { const terminalInstance = JSON.parse(serializedEditorInput); terminalInstance.resource = URI.parse(...
{ return; }
conditional_block
terminalEditorSerializer.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
terminalInstance.resource = URI.parse(terminalInstance.resource); return this._terminalEditorService.reviveInput(terminalInstance); } private _toJson(instance: ITerminalInstance): ISerializedTerminalEditorInput { return { id: instance.persistentProcessId!, pid: instance.processId || 0, title: instance...
const terminalInstance = JSON.parse(serializedEditorInput);
random_line_split
terminalEditorSerializer.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
public canSerialize(editorInput: TerminalEditorInput): boolean { return !!editorInput.terminalInstance?.persistentProcessId; } public serialize(editorInput: TerminalEditorInput): string | undefined { if (!editorInput.terminalInstance?.persistentProcessId || !editorInput.terminalInstance.shouldPersist) { re...
{ }
identifier_body
principal.py
from office365.runtime.paths.service_operation import ServiceOperationPath from office365.sharepoint.base_entity import BaseEntity class Principal(BaseEntity): """Represents a user or group that can be assigned permissions to control security.""" @property def id(self): """Gets a value that speci...
:rtype: bool or None """ return self.properties.get('IsHiddenInUI', None) @property def principal_type(self): """Gets the login name of the principal. :rtype: int or None """ return self.properties.get('PrincipalType', None) def set_property(self, n...
@property def is_hidden_in_ui(self): """Gets the login name of the principal.
random_line_split
principal.py
from office365.runtime.paths.service_operation import ServiceOperationPath from office365.sharepoint.base_entity import BaseEntity class Principal(BaseEntity): """Represents a user or group that can be assigned permissions to control security.""" @property def id(self): """Gets a value that speci...
(self): """Gets the login name of the principal. :rtype: int or None """ return self.properties.get('PrincipalType', None) def set_property(self, name, value, persist_changes=True): super(Principal, self).set_property(name, value, persist_changes) # fallback: create...
principal_type
identifier_name
principal.py
from office365.runtime.paths.service_operation import ServiceOperationPath from office365.sharepoint.base_entity import BaseEntity class Principal(BaseEntity): """Represents a user or group that can be assigned permissions to control security.""" @property def id(self): """Gets a value that speci...
def set_property(self, name, value, persist_changes=True): super(Principal, self).set_property(name, value, persist_changes) # fallback: create a new resource path if self._resource_path is None: if name == "Id": self._resource_path = ServiceOperationPath( ...
"""Gets the login name of the principal. :rtype: int or None """ return self.properties.get('PrincipalType', None)
identifier_body
principal.py
from office365.runtime.paths.service_operation import ServiceOperationPath from office365.sharepoint.base_entity import BaseEntity class Principal(BaseEntity): """Represents a user or group that can be assigned permissions to control security.""" @property def id(self): """Gets a value that speci...
return self
if name == "Id": self._resource_path = ServiceOperationPath( "GetById", [value], self._parent_collection.resource_path) elif name == "LoginName": self._resource_path = ServiceOperationPath( "GetByName", [value], self._parent_collection....
conditional_block
lib.rs
//! natural_constants: a collection of constants and helper functions //! //! Written by Willi Kappler, Version 0.1 (2017.02.20) //! //! Repository: https://github.com/willi-kappler/natural_constants //! //! License: MIT //! //! //! # Example: //! //! ``` //! extern crate natural_constants;
//! //! fn main() { //! let c = speed_of_light_vac; //! let m0 = 100.0; //! //! // Use c in your code: //! let E = m0 * c * c; //! } //! ``` // For clippy // #![feature(plugin)] // // #![plugin(clippy)] #![allow(non_upper_case_globals)] #![allow(dead_code)] pub mod math; pub mod physics; pub mod che...
//! use natural_constants::physics::*; //!
random_line_split
strings.js
define({ "_widgetLabel": "適合性モデラー", "general": { "clear": "消去", "cancel": "キャンセル", "save": "実行", "saveAs": "エクスポート" }, "saveModel": { "save": "エクスポート", "title": "タイトル: ", "summary": "サマリー: ", "description": "説明: ", "tags": "タグ: ", "folder": "フォルダー: ", "homeFolderPatte...
"validating": "整合チェックしています...", "invalidItemCaption": "加重オーバーレイ サービスの警告", "notAnImageService": "このアイテムはイメージ サービスではありません。", "notAWroService": "このアイテムは加重オーバーレイ サービスではありません。", "undefinedUrl": "このアイテムの URL が定義されていません。", "inaccessible": "サービスにアクセスできません。", "generalError": "アイテムを開けません...
"projectNotOpen": "プロジェクトが開いていません。", "readMore": "詳細", "validation": {
random_line_split
vehicle-features.service.ts
import * as mongodb from 'mongodb'; import Constants from '../../constants'; import { MongoIdMapperService } from '../mongo-id-mapper.service'; import { VehicleFeature } from './vehicle-feature.interface'; export class VehicleFeatureService { constructor(private mongoIdMapperService: MongoIdMapperService) { } pu...
}
{ return await mongodb.MongoClient.connect(Constants.data.mongoUrl); }
identifier_body
vehicle-features.service.ts
import * as mongodb from 'mongodb'; import Constants from '../../constants'; import { MongoIdMapperService } from '../mongo-id-mapper.service'; import { VehicleFeature } from './vehicle-feature.interface'; export class VehicleFeatureService { constructor(private mongoIdMapperService: MongoIdMapperService) { } pu...
const inserted = await collection.insertOne(feature); return inserted.insertedId.toString(); } public async get(): Promise<VehicleFeature[]> { const db = await this.getConnection(); const collection = db.collection(Constants.data.vehicleFeatureCollection); return await collection.find().map...
{ throw new Error('Cannot insert duplicate feature.'); }
conditional_block
vehicle-features.service.ts
import * as mongodb from 'mongodb'; import Constants from '../../constants'; import { MongoIdMapperService } from '../mongo-id-mapper.service'; import { VehicleFeature } from './vehicle-feature.interface'; export class VehicleFeatureService { constructor(private mongoIdMapperService: MongoIdMapperService) { } pu...
return inserted.insertedId.toString(); } public async get(): Promise<VehicleFeature[]> { const db = await this.getConnection(); const collection = db.collection(Constants.data.vehicleFeatureCollection); return await collection.find().map((feature) => this.mongoIdMapperService.map(feature) as Vehi...
const inserted = await collection.insertOne(feature);
random_line_split
vehicle-features.service.ts
import * as mongodb from 'mongodb'; import Constants from '../../constants'; import { MongoIdMapperService } from '../mongo-id-mapper.service'; import { VehicleFeature } from './vehicle-feature.interface'; export class VehicleFeatureService { constructor(private mongoIdMapperService: MongoIdMapperService) { } pu...
(): Promise<mongodb.Db> { return await mongodb.MongoClient.connect(Constants.data.mongoUrl); } }
getConnection
identifier_name
Header.tsx
/** @jsxRuntime classic */ /** @jsx jsx */ import { createContext, useContext, useCallback, useEffect, useState, useRef, ReactNode, } from 'react'; import { useRouter } from 'next/router'; import { jsx } from '@emotion/react'; import Link from 'next/link'; import debounce from 'lodash.debounce'; import ...
}; window.addEventListener('resize', debounce(listener, 130)); return () => { window.removeEventListener('resize', debounce(listener, 130)); }; }, [setDesktopOpenState]); useEffect(() => { document.body.style.overflow = 'auto'; // search - init field let searchAttempt = 0; /...
{ setDesktopOpenState(-1); }
conditional_block
Header.tsx
/** @jsxRuntime classic */ /** @jsx jsx */ import { createContext, useContext, useCallback, useEffect, useState, useRef, ReactNode, } from 'react'; import { useRouter } from 'next/router'; import { jsx } from '@emotion/react'; import Link from 'next/link'; import debounce from 'lodash.debounce'; import ...
padding: '0.25rem', cursor: 'pointer', color: 'var(--muted)', })} > <Search css={{ height: '1.4rem', marginTop: '0.2rem' }} /> </button> */} <Button as="a" href="/docs" shadow css={mq({ ...
display: ['inline-block', 'inline-block', 'none'], appearance: 'none', border: '0 none', boxShadow: 'none', background: 'transparent',
random_line_split
Header.tsx
/** @jsxRuntime classic */ /** @jsx jsx */ import { createContext, useContext, useCallback, useEffect, useState, useRef, ReactNode, } from 'react'; import { useRouter } from 'next/router'; import { jsx } from '@emotion/react'; import Link from 'next/link'; import debounce from 'lodash.debounce'; import ...
() { const mq = useMediaQuery(); return ( <div css={mq({ marginRight: [0, null, null, null, '1rem'], marginTop: '0.1rem', whiteSpace: 'nowrap', })} > <Link href="/" passHref> <a css={{ fontSize: 'var(--font-medium)', fontWe...
Logo
identifier_name
Header.tsx
/** @jsxRuntime classic */ /** @jsx jsx */ import { createContext, useContext, useCallback, useEffect, useState, useRef, ReactNode, } from 'react'; import { useRouter } from 'next/router'; import { jsx } from '@emotion/react'; import Link from 'next/link'; import debounce from 'lodash.debounce'; import ...
function LinkItem({ children, href }: { children: ReactNode; href: string }) { const mq = useMediaQuery(); const currentSection = useCurrentSection(); const isActive = href === currentSection; return ( <span css={mq({ display: ['none', 'inline'], fontWeight: 600 })}> <NavItem isActive={isAc...
{ const { pathname } = useRouter(); const check = (candidate: string) => pathname.startsWith(candidate); if (['/updates', '/releases'].some(check)) return '/updates'; if (['/why-keystone', '/for-'].some(check)) return '/why-keystone'; if (['/docs'].some(check)) return '/docs'; }
identifier_body
index.js
/*! * express-session * Copyright(c) 2010 Sencha Inc. * Copyright(c) 2011 TJ Holowaychuk * Copyright(c) 2014 Douglas Christopher Wilson * MIT Licensed */ /** * Module dependencies. * @private */ var cookie = require('cookie'); var crc = require('crc').crc32; var debug = require('debug')('express-session'); v...
(req) { // cannot set cookie without a session ID if (typeof req.sessionID !== 'string') { debug('session ignored because of bogus req.sessionID %o', req.sessionID); return false; } return cookieId === req.sessionID && !shouldSave(req); } // determine if cookie should b...
shouldTouch
identifier_name
index.js
/*! * express-session * Copyright(c) 2010 Sencha Inc. * Copyright(c) 2011 TJ Holowaychuk * Copyright(c) 2014 Douglas Christopher Wilson * MIT Licensed */ /** * Module dependencies. * @private */ var cookie = require('cookie'); var crc = require('crc').crc32; var debug = require('debug')('express-session'); v...
if (val === false) { debug('cookie signature invalid'); val = undefined; } } else { debug('cookie unsigned') } } } // back-compat read from cookieParser() signedCookies data if (!val && req.signedCookies) { val = req.signedCookies[name]; if (v...
random_line_split
index.js
/*! * express-session * Copyright(c) 2010 Sencha Inc. * Copyright(c) 2011 TJ Holowaychuk * Copyright(c) 2014 Douglas Christopher Wilson * MIT Licensed */ /** * Module dependencies. * @private */ var cookie = require('cookie'); var crc = require('crc').crc32; var debug = require('debug')('express-session'); v...
} } return val; } /** * Hash the given `sess` object omitting changes to `.cookie`. * * @param {Object} sess * @return {String} * @private */ function hash(sess) { return crc(JSON.stringify(sess, function (key, val) { if (key !== 'cookie') { return val; } })); } /** * Determine if ...
{ debug('cookie unsigned') }
conditional_block
index.js
/*! * express-session * Copyright(c) 2010 Sencha Inc. * Copyright(c) 2011 TJ Holowaychuk * Copyright(c) 2014 Douglas Christopher Wilson * MIT Licensed */ /** * Module dependencies. * @private */ var cookie = require('cookie'); var crc = require('crc').crc32; var debug = require('debug')('express-session'); v...
// determine if cookie should be set on response function shouldSetCookie(req) { // cannot set cookie without a session ID if (typeof req.sessionID !== 'string') { return false; } return cookieId != req.sessionID ? saveUninitializedSession || isModified(req.session) ...
{ // cannot set cookie without a session ID if (typeof req.sessionID !== 'string') { debug('session ignored because of bogus req.sessionID %o', req.sessionID); return false; } return cookieId === req.sessionID && !shouldSave(req); }
identifier_body
store.py
""" sentry.options.store ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2015 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function import logging import six from collections import namedtuple from time import time from ran...
def set_cache(self, key, value): if self.cache is None: return None cache_key = key.cache_key if key.ttl > 0: self._local_cache[cache_key] = _make_cache_value(key, value) try: self.cache.set(cache_key, value, self.ttl) return True ...
create_or_update( model=self.model, key=key.name, values={ 'value': value, 'last_updated': timezone.now(), } )
identifier_body
store.py
""" sentry.options.store ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2015 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function import logging import six from collections import namedtuple from time import time from ran...
(self, key): """ Remove key out of option stores. This operation must succeed on the database first. If database fails, an exception is raised. If database succeeds, caches are then allowed to fail silently. A boolean is returned to indicate if the network deletion succeeds. ...
delete
identifier_name
store.py
""" sentry.options.store ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2015 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function import logging import six from collections import namedtuple from time import time from ran...
# If we're able to accept within grace window, return it if force_grace and now < grace: return value # Let's clean up values if we're beyond grace. if now > grace: try: del self._local_cache[key.cache_key] except KeyError: ...
return value
conditional_block
store.py
""" sentry.options.store ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2015 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function import logging import six from collections import namedtuple from time import time from ran...
to_expire.append(k) except RuntimeError: # It's possible for the dictionary to be mutated in another thread # while iterating, but this case is rare, so instead of making a # copy and iterating that, it's more efficient to just let it fail # gr...
for k, (_, _, grace) in six.iteritems(self._local_cache): if now > grace:
random_line_split
iterable.rs
// Copyright 2012 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 ...
fn main() {}
{ //~^ ERROR lifetime parameters are not allowed on this type [E0110] it.iter().next() }
identifier_body
iterable.rs
// Copyright 2012 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 ...
//~^ ERROR lifetime parameters are not allowed on this type [E0110] fn iter<'a>(&'a self) -> Self::Iter<'a>; //~^ ERROR lifetime parameters are not allowed on this type [E0110] } // Impl for struct type impl<T> Iterable for Vec<T> { type Item<'a> = &'a T; type Iter<'a> = std::slice::Iter<'a, T>; ...
// follow-up PR. trait Iterable { type Item<'a>; type Iter<'a>: Iterator<Item = Self::Item<'a>>;
random_line_split
iterable.rs
// Copyright 2012 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, I: Iterable>(it: &'a I) -> Option<I::Item<'a>> { //~^ ERROR lifetime parameters are not allowed on this type [E0110] it.iter().next() } fn main() {}
get_first
identifier_name
xor-joiner.rs
// Exercise 2.3 use std::os; use std::io::File; fn xor(a: &[u8], b: &[u8]) -> ~[u8] { let mut ret = ~[]; for i in range(0, a.len()) {
} fn main() { let args: ~[~str] = os::args(); if args.len() != 3 { println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]); } else { let fname1 = &args[1]; let fname2 = &args[2]; let path1 = Path::new(fname1.clone()); let path2 = Path::new(fname2.clone()); ...
ret.push(a[i] ^ b[i]); } ret
random_line_split
xor-joiner.rs
// Exercise 2.3 use std::os; use std::io::File; fn xor(a: &[u8], b: &[u8]) -> ~[u8] { let mut ret = ~[]; for i in range(0, a.len()) { ret.push(a[i] ^ b[i]); } ret } fn main() { let args: ~[~str] = os::args(); if args.len() != 3 { println!("Usage: {:s} <inputfile1> <inputfile2>"...
, (_, _) => fail!("Error opening input files!") } } }
{ let share1bytes: ~[u8] = share1.read_to_end(); let share2bytes: ~[u8] = share2.read_to_end(); print!("{:s}", std::str::from_utf8_owned( xor(share1bytes, share2bytes))); }
conditional_block
xor-joiner.rs
// Exercise 2.3 use std::os; use std::io::File; fn xor(a: &[u8], b: &[u8]) -> ~[u8] { let mut ret = ~[]; for i in range(0, a.len()) { ret.push(a[i] ^ b[i]); } ret } fn
() { let args: ~[~str] = os::args(); if args.len() != 3 { println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]); } else { let fname1 = &args[1]; let fname2 = &args[2]; let path1 = Path::new(fname1.clone()); let path2 = Path::new(fname2.clone()); let shar...
main
identifier_name
xor-joiner.rs
// Exercise 2.3 use std::os; use std::io::File; fn xor(a: &[u8], b: &[u8]) -> ~[u8] { let mut ret = ~[]; for i in range(0, a.len()) { ret.push(a[i] ^ b[i]); } ret } fn main()
{ let args: ~[~str] = os::args(); if args.len() != 3 { println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]); } else { let fname1 = &args[1]; let fname2 = &args[2]; let path1 = Path::new(fname1.clone()); let path2 = Path::new(fname2.clone()); let share_f...
identifier_body
window.py
import types from sikwidgets.region_group import RegionGroup from sikwidgets.util import to_snakecase from sikwidgets.widgets import * def gen_widget_method(widget_class): def widget(self, *args, **kwargs): return self.create_widget(widget_class, *args, **kwargs) return widget class Window(RegionGroup...
(self): #pop_size = len(self.widgets) #n = sample_size(pop_size) #random.sample(self.widgets, n) seen_widgets = 0 unseen_widgets = 0 for widget in self.widgets: if seen_widgets >= 10: # we're confident enough it exists return T...
exists
identifier_name
window.py
import types from sikwidgets.region_group import RegionGroup from sikwidgets.util import to_snakecase from sikwidgets.widgets import * def gen_widget_method(widget_class):
class Window(RegionGroup): def __init__(self, region, parent=None): # FIXME: this is hacky RegionGroup.__init__(self, parent) # manually set the region to the given one rather # than the region from the parent self.search_region = region self.region = region ...
def widget(self, *args, **kwargs): return self.create_widget(widget_class, *args, **kwargs) return widget
identifier_body
window.py
import types from sikwidgets.region_group import RegionGroup from sikwidgets.util import to_snakecase from sikwidgets.widgets import * def gen_widget_method(widget_class): def widget(self, *args, **kwargs): return self.create_widget(widget_class, *args, **kwargs) return widget class Window(RegionGroup...
unseen_widgets = 0 for widget in self.widgets: if seen_widgets >= 10: # we're confident enough it exists return True if widget.exists(): seen_widgets += 1 else: unseen_widgets += 1 if seen_wi...
random_line_split
window.py
import types from sikwidgets.region_group import RegionGroup from sikwidgets.util import to_snakecase from sikwidgets.widgets import * def gen_widget_method(widget_class): def widget(self, *args, **kwargs): return self.create_widget(widget_class, *args, **kwargs) return widget class Window(RegionGroup...
if widget.exists(): seen_widgets += 1 else: unseen_widgets += 1 if seen_widgets > 2 * unseen_widgets + 1: return True if seen_widgets >= unseen_widgets: return True return False def cr...
return True
conditional_block
ChildWatch.spec.ts
import {assert} from 'chai'; import {Job} from '../Job'; import {BlockIO} from '../BlockProperty'; describe('Block Child Watch', function () { it('basic', function () { let job = new Job(); let watchLog: any[] = []; let watch = {
(property: BlockIO, saved: boolean) { watchLog.push([property._name, property._value != null, Boolean(saved)]); }, }; job.watch(watch); job.createBlock('a'); assert.deepEqual(watchLog, [['a', true, true]], 'new block'); watchLog = []; job.createOutputBlock('a'); assert.deepEq...
onChildChange
identifier_name
ChildWatch.spec.ts
import {assert} from 'chai'; import {Job} from '../Job'; import {BlockIO} from '../BlockProperty';
describe('Block Child Watch', function () { it('basic', function () { let job = new Job(); let watchLog: any[] = []; let watch = { onChildChange(property: BlockIO, saved: boolean) { watchLog.push([property._name, property._value != null, Boolean(saved)]); }, }; job.watch(watch...
random_line_split
ChildWatch.spec.ts
import {assert} from 'chai'; import {Job} from '../Job'; import {BlockIO} from '../BlockProperty'; describe('Block Child Watch', function () { it('basic', function () { let job = new Job(); let watchLog: any[] = []; let watch = { onChildChange(property: BlockIO, saved: boolean)
, }; job.watch(watch); job.createBlock('a'); assert.deepEqual(watchLog, [['a', true, true]], 'new block'); watchLog = []; job.createOutputBlock('a'); assert.deepEqual(watchLog, [['a', true, false]], 'replace with temp block'); watchLog = []; job.createBlock('a'); assert.deepEq...
{ watchLog.push([property._name, property._value != null, Boolean(saved)]); }
identifier_body
24_touch_switch.py
#!/usr/bin/env python3 import RPi.GPIO as GPIO TouchPin = 11 Gpin = 13 Rpin = 12 tmp = 0 def setup(): GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output GPIO.setu...
if __name__ == '__main__': # Program start from here setup() try: loop() except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. destroy()
GPIO.output(Gpin, GPIO.HIGH) # Green led off GPIO.output(Rpin, GPIO.HIGH) # Red led off GPIO.cleanup() # Release resource
identifier_body
24_touch_switch.py
#!/usr/bin/env python3 import RPi.GPIO as GPIO TouchPin = 11 Gpin = 13 Rpin = 12 tmp = 0 def setup(): GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output GPIO.setu...
if x == 1: print (' **********') print (' * OFF *') print (' **********') tmp = x def loop(): while True: Led(GPIO.input(TouchPin)) Print(GPIO.input(TouchPin)) def destroy(): GPIO.output(Gpin, GPIO.HIGH) # Green led off GPIO.output(Rpin, GPIO.HIGH) # Red led off GPIO.cl...
print (' **********') print (' * ON *') print (' **********')
conditional_block
24_touch_switch.py
#!/usr/bin/env python3 import RPi.GPIO as GPIO TouchPin = 11 Gpin = 13 Rpin = 12 tmp = 0 def setup(): GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output GPIO.setu...
(x): global tmp if x != tmp: if x == 0: print (' **********') print (' * ON *') print (' **********') if x == 1: print (' **********') print (' * OFF *') print (' **********') tmp = x def loop(): while True: Led(GPIO.input(TouchPin)) Print(GPIO.input(TouchPin))...
Print
identifier_name
24_touch_switch.py
#!/usr/bin/env python3
TouchPin = 11 Gpin = 13 Rpin = 12 tmp = 0 def setup(): GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output GPIO.setup(TouchPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) ...
import RPi.GPIO as GPIO
random_line_split
Date.js
/*! * ${copyright} */ // Provides the base implementation for all model implementations sap.ui.define(['jquery.sap.global', 'sap/ui/core/format/DateFormat', 'sap/ui/model/SimpleType', 'sap/ui/model/FormatException', 'sap/ui/model/ParseException', 'sap/ui/model/ValidateException'], function(jQuery, DateFormat, Simpl...
} else { return SimpleType.prototype.getModelFormat.call(this); } }; Date1.prototype.setFormatOptions = function(oFormatOptions) { this.oFormatOptions = oFormatOptions; this._createFormats(); }; /** * @protected */ Date1.prototype.getOutputPattern = function() { return this.oOutputFormat.oForma...
{ return this.oInputFormat; }
conditional_block
Date.js
/*! * ${copyright} */ // Provides the base implementation for all model implementations sap.ui.define(['jquery.sap.global', 'sap/ui/core/format/DateFormat', 'sap/ui/model/SimpleType', 'sap/ui/model/FormatException', 'sap/ui/model/ParseException', 'sap/ui/model/ValidateException'], function(jQuery, DateFormat, Simpl...
aMessages.push(oBundle.getText(that.sName + ".Minimum", [oContent])); } break; case "maximum": if (oValue > oContent) { aViolatedConstraints.push("maximum"); aMessages.push(oBundle.getText(that.sName + ".Maximum", [oContent])); } } }); if (aViolatedConstraints...
switch (sName) { case "minimum": if (oValue < oContent) { aViolatedConstraints.push("minimum");
random_line_split
filters.js
angular.module('app') .filter('date', function(){ 'use strict'; return function(timestamp, format){ return timestamp ? moment(timestamp).format(format ? format : 'll') : '<date>'; }; }) .filter('datetime', function(){ 'use strict'; return function(timestamp, format){ return timestamp ? moment(timest...
}; }) .filter('mynumber', function($filter){ 'use strict'; return function(number, round){ var mul = Math.pow(10, round ? round : 0); return $filter('number')(Math.round(number*mul)/mul); }; }) .filter('rating', function($filter){ 'use strict'; return function(rating, max, withText){ var star...
{ console.warn('Unable to format duration', seconds); return '<duration>'; }
conditional_block
filters.js
angular.module('app') .filter('date', function(){ 'use strict'; return function(timestamp, format){ return timestamp ? moment(timestamp).format(format ? format : 'll') : '<date>'; }; }) .filter('datetime', function(){ 'use strict'; return function(timestamp, format){ return timestamp ? moment(timest...
return function(seconds, humanize){ if(seconds || seconds === 0){ if(humanize){ return moment.duration(seconds, 'seconds').humanize(); } else { var prefix = -60 < seconds && seconds < 60 ? '00:' : ''; return prefix + moment.duration(seconds, 'seconds').format('hh:mm:ss'); ...
'use strict';
random_line_split
IQRCode.d.ts
/// <reference path="IAdaptiveRPGroup.d.ts" /> /// <reference path="IBaseReader.d.ts" /> /** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. Licensed under the Apach...
/** @class Adaptive.IQRCode */ interface IQRCode extends IBaseReader { } }
@version 1.0 */
random_line_split
bootstrap-datetimepicker.ms.js
/** * Malay translation for bootstrap-datetimepicker * Ateman Faiz <noorulfaiz@gmail.com> */ ;(function ($) { $.fn.datetimepicker.dates['ms'] = { days: ["Ahad", "Isnin", "Selasa", "Rabu", "Khamis", "Jumaat", "Sabtu", "Ahad"], daysShort: ["Aha", "Isn", "Sel", "Rab", "Kha", "Jum", "Sab", "Aha"], ...
}(jQuery));
random_line_split
upsert_resolution.rs
// Copyright 2016 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software...
}, &Term::AddOrRetract(OpType::Add, Right(ref t), a, ref x @ Left(_)) => { temp_ids.insert(t.clone()); let attribute: &Attribute = schema.require_attribute_for_entid(a)?; if attribute.unique == Some(attribute::Unique::Identity)...
{ tempid_avs.entry((a, Right(t2.clone()))).or_insert(vec![]).push(t1.clone()); }
conditional_block
upsert_resolution.rs
// Copyright 2016 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software...
/// Evolve potential upserts that haven't resolved into allocations. pub(crate) fn allocate_unresolved_upserts(&mut self) -> Result<()> { let mut upserts_ev = vec![]; ::std::mem::swap(&mut self.upserts_ev, &mut upserts_ev); self.allocations.extend(upserts_ev.into_iter().map(|UpsertEV(...
{ let mut temp_id_avs: Vec<(TempIdHandle, AVPair)> = vec![]; // TODO: map/collect. for &UpsertE(ref t, ref a, ref v) in &self.upserts_e { // TODO: figure out how to make this less expensive, i.e., don't require // clone() of an arbitrary value. temp_id_avs.pus...
identifier_body
upsert_resolution.rs
// Copyright 2016 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software...
&Term::AddOrRetract(OpType::Add, Right(ref t1), a, Right(ref t2)) => { temp_ids.insert(t1.clone()); temp_ids.insert(t2.clone()); let attribute: &Attribute = schema.require_attribute_for_entid(a)?; if attribute.unique == Some...
random_line_split
upsert_resolution.rs
// Copyright 2016 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software...
(&self) -> bool { !self.upserts_e.is_empty() } /// Evolve this generation one step further by rewriting the existing :db/add entities using the /// given temporary IDs. /// /// TODO: Considering doing this in place; the function already consumes `self`. pub(crate) fn evolve_one_step(sel...
can_evolve
identifier_name
test_main.py
#!/usr/bin/env python3 import glob import os import re import subprocess import pytest @pytest.fixture(autouse=True, scope="module") def
(request): with pytest.raises(Exception): subprocess.check_call(['certbot', '--version']) try: snap_folder = request.config.getoption("snap_folder") snap_arch = request.config.getoption("snap_arch") snap_path = glob.glob(os.path.join(snap_folder, 'certbot_*_{0}.snap'.format(snap_...
install_certbot_snap
identifier_name
test_main.py
#!/usr/bin/env python3 import glob import os import re import subprocess import pytest @pytest.fixture(autouse=True, scope="module") def install_certbot_snap(request): with pytest.raises(Exception): subprocess.check_call(['certbot', '--version']) try: snap_folder = request.config.getoption("s...
universal_newlines=True) subprocess.check_call(['snap', 'connect', snap_name + ':certbot-metadata', 'certbot:certbot-metadata']) subprocess.check_call(['snap', 'install', '--dangerous', dns_snap_path]) finally: subprocess.call...
random_line_split
test_main.py
#!/usr/bin/env python3 import glob import os import re import subprocess import pytest @pytest.fixture(autouse=True, scope="module") def install_certbot_snap(request):
def test_dns_plugin_install(dns_snap_path): """ Test that each DNS plugin Certbot snap can be installed and is usable with the Certbot snap. """ plugin_name = re.match(r'^certbot-(dns-\w+)_.*\.snap$', os.path.basename(dns_snap_path)).group(1) snap_name = 'certbot-{0...
with pytest.raises(Exception): subprocess.check_call(['certbot', '--version']) try: snap_folder = request.config.getoption("snap_folder") snap_arch = request.config.getoption("snap_arch") snap_path = glob.glob(os.path.join(snap_folder, 'certbot_*_{0}.snap'.format(snap_arch)))[0] ...
identifier_body
early-vtbl-resolution.rs
// Copyright 2012 The Rust Project Developers. See the 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait thing<A> { ...
// file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
random_line_split
early-vtbl-resolution.rs
// Copyright 2012 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, B: thing<A>>(x: B) -> Option<A> { x.foo() } struct A { a: int } pub fn main() { for old_iter::eachi(&(Some(A {a: 0}))) |i, a| { debug!("%u %d", i, a.a); } let _x: Option<float> = foo_func(0); }
foo_func
identifier_name
early-vtbl-resolution.rs
// Copyright 2012 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: Option<float> = foo_func(0); }
{ for old_iter::eachi(&(Some(A {a: 0}))) |i, a| { debug!("%u %d", i, a.a); }
identifier_body
properties.ts
import {defineMIME, defineMode} from '../index'; defineMode('properties', () => ({ token: (stream, state) => { const sol = stream.sol() || state.afterSection; const eol = stream.eol(); state.afterSection = false; if (sol) { if (state.nextMultiline) { st...
else if (ch === '=' || ch === ':') { state.position = 'quote'; return null; } else if (ch === '\\' && state.position === 'quote') { if (stream.eol()) { // end of line? // Multiline value state.nextMultiline = true; } } ...
{ state.afterSection = true; stream.skipTo(']'); stream.eat(']'); return 'header'; }
conditional_block
properties.ts
import {defineMIME, defineMode} from '../index'; defineMode('properties', () => ({ token: (stream, state) => { const sol = stream.sol() || state.afterSection; const eol = stream.eol(); state.afterSection = false; if (sol) { if (state.nextMultiline) { st...
state.afterSection = true; stream.skipTo(']'); stream.eat(']'); return 'header'; } else if (ch === '=' || ch === ':') { state.position = 'quote'; return null; } else if (ch === '\\' && state.position === 'quote') { if (s...
random_line_split
download.rs
use std::fmt::{self, Display, Formatter}; use uuid::Uuid; /// Details of a package for downloading. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub struct Package { pub name: String, pub version: String } impl Display for Package { fn fmt(&self, f: &mut Formatter) -> fmt::Result { ...
pub struct UpdateRequest { pub requestId: Uuid, pub status: RequestStatus, pub packageId: Package, pub installPos: i32, pub createdAt: String, } /// The current status of an `UpdateRequest`. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub enum RequestStatus { Pending, ...
/// A request for the device to install a new update. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] #[allow(non_snake_case)]
random_line_split
download.rs
use std::fmt::{self, Display, Formatter}; use uuid::Uuid; /// Details of a package for downloading. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub struct Package { pub name: String, pub version: String } impl Display for Package { fn fmt(&self, f: &mut Formatter) -> fmt::Result
} /// A request for the device to install a new update. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] #[allow(non_snake_case)] pub struct UpdateRequest { pub requestId: Uuid, pub status: RequestStatus, pub packageId: Package, pub installPos: i32, pub createdAt: String, } ...
{ write!(f, "{} {}", self.name, self.version) }
identifier_body
download.rs
use std::fmt::{self, Display, Formatter}; use uuid::Uuid; /// Details of a package for downloading. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] pub struct Package { pub name: String, pub version: String } impl Display for Package { fn
(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{} {}", self.name, self.version) } } /// A request for the device to install a new update. #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)] #[allow(non_snake_case)] pub struct UpdateRequest { pub requestId: Uuid, pub status: ...
fmt
identifier_name
0002_auto_20191121_1640.py
# Generated by Django 2.2.7 on 2019-11-21 15:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('smmapdfs_edit', '0001_initial'), ] operations = [ migrations.AlterField( model_name='pdfsandwic...
), migrations.AlterField( model_name='pdfsandwichfontconnector', name='administrative_unit', field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='aklub.AdministrativeUnit'), ), migrations.AlterField( ...
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='aklub.AdministrativeUnit'),
random_line_split
0002_auto_20191121_1640.py
# Generated by Django 2.2.7 on 2019-11-21 15:40 from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): dependencies = [ ('smmapdfs_edit', '0001_initial'), ] operations = [ migrations.AlterField( model_name='pdfsandwichemailconnector', name='administrative_unit', field=models.OneToOneField(blank=True, null=True, on_delete=django.db....
Migration
identifier_name
0002_auto_20191121_1640.py
# Generated by Django 2.2.7 on 2019-11-21 15:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
dependencies = [ ('smmapdfs_edit', '0001_initial'), ] operations = [ migrations.AlterField( model_name='pdfsandwichemailconnector', name='administrative_unit', field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='...
identifier_body
ConfigSet.py
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2005-2010 (ita) """ ConfigSet: a special dict The values put in :py:class:`ConfigSet` must be lists """ import copy, re, os from waflib import Logs, Utils re_imp = re.compile('^(#)*?([^#=]*?)\ =\ (.*?)$', re.M) class ConfigSet(object): """ A dict that honor ...
self.table[var] = val + self._get_list_value_for_modification(var) def append_unique(self, var, val): """ Append a value to the specified item only if it's not already present:: def build(bld): bld.env.append_unique('CFLAGS', ['-O2', '-g']) The value must be a list or a tuple """ if isinstance(...
val = [val]
conditional_block
ConfigSet.py
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2005-2010 (ita) """ ConfigSet: a special dict The values put in :py:class:`ConfigSet` must be lists """ import copy, re, os from waflib import Logs, Utils re_imp = re.compile('^(#)*?([^#=]*?)\ =\ (.*?)$', re.M) class ConfigSet(object): """ A dict that honor ...
def store(self, filename): """ Write the :py:class:`ConfigSet` data into a file. See :py:meth:`ConfigSet.load` for reading such files. :param filename: file to use :type filename: string """ try: os.makedirs(os.path.split(filename)[0]) except OSError: pass buf = [] merged_table = self.get_m...
""" Compute the merged dictionary from the fusion of self and all its parent :rtype: a ConfigSet object """ table_list = [] env = self while 1: table_list.insert(0, env.table) try: env = env.parent except AttributeError: break merged_table = {} for table in table_list: merged_table.update(t...
identifier_body
ConfigSet.py
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2005-2010 (ita) """ ConfigSet: a special dict The values put in :py:class:`ConfigSet` must be lists """ import copy, re, os from waflib import Logs, Utils re_imp = re.compile('^(#)*?([^#=]*?)\ =\ (.*?)$', re.M) class ConfigSet(object): """ A dict that honor ...
Return a value as a string. If the input is a list, the value returned is space-separated. :param key: key to use :type key: string """ s = self[key] if isinstance(s, str): return s return ' '.join(s) def _get_list_value_for_modification(self, key): """ Return a list value for further modification....
def get_flat(self, key): """
random_line_split
ConfigSet.py
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2005-2010 (ita) """ ConfigSet: a special dict The values put in :py:class:`ConfigSet` must be lists """ import copy, re, os from waflib import Logs, Utils re_imp = re.compile('^(#)*?([^#=]*?)\ =\ (.*?)$', re.M) class ConfigSet(object): """ A dict that honor ...
(self): """Dict interface (unknown purpose)""" keys = set() cur = self while cur: keys.update(cur.table.keys()) cur = getattr(cur, 'parent', None) keys = list(keys) keys.sort() return keys def __str__(self): """Text representation of the ConfigSet (for debugging purposes)""" return "\n".join([...
keys
identifier_name
imgwin.rs
use glium; use glium::index::PrimitiveType; use glium::Surface; use image; use std::time::{Duration, Instant}; use glium::glutin::event::{ElementState, Event, StartCause, VirtualKeyCode, WindowEvent}; use glium::glutin::event_loop::{ControlFlow, EventLoop}; use glium::glutin::window::WindowBuilder; use glium::glutin::...
pub fn new_window(&self, title: impl Into<String>) -> ImgWindow { ImgWindow::new(title, &self.main_loop) } /// Execute the main loop without ever returning. Events are delegated to the given `handler` /// and `handler.next_frame` is called `fps` times per seconds. /// Whenever `handler.sh...
{ Application { main_loop: EventLoop::new(), } }
identifier_body
imgwin.rs
use glium; use glium::index::PrimitiveType; use glium::Surface; use image; use std::time::{Duration, Instant}; use glium::glutin::event::{ElementState, Event, StartCause, VirtualKeyCode, WindowEvent}; use glium::glutin::event_loop::{ControlFlow, EventLoop}; use glium::glutin::window::WindowBuilder; use glium::glutin::...
_ => (), }, Event::NewEvents(StartCause::ResumeTimeReached { .. }) | Event::NewEvents(StartCause::Init) => handler.next_frame(), _ => (), } if handler.should_exit() { *control_flow = ControlFlow...
{ handler.key_event(input.virtual_keycode) }
conditional_block
imgwin.rs
use glium; use glium::index::PrimitiveType; use glium::Surface; use image; use std::time::{Duration, Instant}; use glium::glutin::event::{ElementState, Event, StartCause, VirtualKeyCode, WindowEvent}; use glium::glutin::event_loop::{ControlFlow, EventLoop}; use glium::glutin::window::WindowBuilder; use glium::glutin::...
struct Vertex { position: [f32; 2], tex_coords: [f32; 2], } implement_vertex!(Vertex, position, tex_coords); /// An Application creates windows and runs a main loop pub struct Application { main_loop: EventLoop<()>, } impl Application { pub fn new() -> Application { Application { ...
use glium::texture::{CompressedSrgbTexture2d, RawImage2d}; use glium::{implement_vertex, program, uniform}; #[derive(Copy, Clone)]
random_line_split
imgwin.rs
use glium; use glium::index::PrimitiveType; use glium::Surface; use image; use std::time::{Duration, Instant}; use glium::glutin::event::{ElementState, Event, StartCause, VirtualKeyCode, WindowEvent}; use glium::glutin::event_loop::{ControlFlow, EventLoop}; use glium::glutin::window::WindowBuilder; use glium::glutin::...
(&self) { let mut target = self.facade.draw(); target.clear_color(0.0, 0.0, 0.0, 0.0); if let Some(ref texture) = self.texture { let uniforms = uniform! { matrix: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], ...
redraw
identifier_name
router.js
'use strict' require('./controllers/listCtrl.js'); require('./controllers/loginCtrl.js'); require('./services/pageService.js'); angular.module('app.router', ['ui.router', 'app.list', 'app.login']) .config(configFn); configFn.$inject = ['$locationProvider', '$stateProvider', '$urlRouterProvider']; function ...
}
});
random_line_split
router.js
'use strict' require('./controllers/listCtrl.js'); require('./controllers/loginCtrl.js'); require('./services/pageService.js'); angular.module('app.router', ['ui.router', 'app.list', 'app.login']) .config(configFn); configFn.$inject = ['$locationProvider', '$stateProvider', '$urlRouterProvider']; function ...
{ $urlRouterProvider.when('', '/'); $urlRouterProvider.otherwise("/404"); $stateProvider .state('list', { url: "/", template: require('ng-cache!./views/list.html'), // controller: 'listCtrl' }) .state('signin', { url: "/login", template: require('ng...
identifier_body
router.js
'use strict' require('./controllers/listCtrl.js'); require('./controllers/loginCtrl.js'); require('./services/pageService.js'); angular.module('app.router', ['ui.router', 'app.list', 'app.login']) .config(configFn); configFn.$inject = ['$locationProvider', '$stateProvider', '$urlRouterProvider']; function
($locationProvider, $stateProvider, $urlRouterProvider){ $urlRouterProvider.when('', '/'); $urlRouterProvider.otherwise("/404"); $stateProvider .state('list', { url: "/", template: require('ng-cache!./views/list.html'), // controller: 'listCtrl' }) .state('signin',...
configFn
identifier_name
common.py
""" Define common steps for instructor dashboard acceptance tests. """ # pylint: disable=missing-docstring # pylint: disable=redefined-outer-name from __future__ import absolute_import from lettuce import step, world from mock import patch from nose.tools import assert_in from courseware.tests.factories import Inst...
) elif button == "Grading Configuration": # Go to the data download section of the instructor dash go_to_section("data_download") world.css_click('input[name="dump-gradeconf"]') elif button == "List enrolled students' profile information": # Go to the data download sec...
msg="Could not find grade report generation success message."
random_line_split
common.py
""" Define common steps for instructor dashboard acceptance tests. """ # pylint: disable=missing-docstring # pylint: disable=redefined-outer-name from __future__ import absolute_import from lettuce import step, world from mock import patch from nose.tools import assert_in from courseware.tests.factories import Inst...
elif button == "List enrolled students' profile information": # Go to the data download section of the instructor dash go_to_section("data_download") world.css_click('input[name="list-profiles"]') elif button == "Download profile information as a CSV": # Go to the data downlo...
go_to_section("data_download") world.css_click('input[name="dump-gradeconf"]')
conditional_block
common.py
""" Define common steps for instructor dashboard acceptance tests. """ # pylint: disable=missing-docstring # pylint: disable=redefined-outer-name from __future__ import absolute_import from lettuce import step, world from mock import patch from nose.tools import assert_in from courseware.tests.factories import Inst...
@patch.dict('courseware.access.settings.FEATURES', {"MAX_ENROLLMENT_INSTR_BUTTONS": 0}) def make_large_course(step, role): i_am_staff_or_instructor(step, role) @step(u'Given I am "([^"]*)" for a course') def i_am_staff_or_instructor(step, role): # pylint: disable=unused-argument ## In summary: makes a tes...
make_large_course(step, role)
identifier_body
common.py
""" Define common steps for instructor dashboard acceptance tests. """ # pylint: disable=missing-docstring # pylint: disable=redefined-outer-name from __future__ import absolute_import from lettuce import step, world from mock import patch from nose.tools import assert_in from courseware.tests.factories import Inst...
(section_name): # section name should be one of # course_info, membership, student_admin, data_download, analytics, send_email world.visit(u'/courses/{}'.format(world.course_key)) world.css_click(u'a[href="/courses/{}/instructor"]'.format(world.course_key)) world.css_click('[data-section="{0}"]'.for...
go_to_section
identifier_name
swap_network_trotter_hubbard.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribu...
(p, q, x_dim, y_dim, periodic): n_sites = x_dim*y_dim if p < n_sites and q >= n_sites or q < n_sites and p >= n_sites: return False if p >= n_sites and q >= n_sites: p -= n_sites q -= n_sites return (q == _right_neighbor(p, x_dim, y_dim, periodic) or p == _right_neigh...
_is_horizontal_edge
identifier_name
swap_network_trotter_hubbard.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribu...
return site + 1 def _bottom_neighbor(site, x_dimension, y_dimension, periodic): if y_dimension == 1: return None if site + x_dimension + 1 > x_dimension*y_dimension: if periodic: return site + x_dimension - x_dimension*y_dimension else: return None retu...
if periodic: return site + 1 - x_dimension else: return None
conditional_block
swap_network_trotter_hubbard.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribu...
fermionic=True, offset=True) qubits = qubits[::-1] def default_initial_params(self) -> numpy.ndarray: """Approximate evolution by H(t) = T + (t/A)V. Sets the parameters so that the ansatz circuit consists of a sequence of second-order Trotter steps approxima...
yield swap_network( qubits, one_and_two_body_interaction_reversed_order,
random_line_split
swap_network_trotter_hubbard.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribu...
def operations(self, qubits: Sequence[cirq.Qid]) -> cirq.OP_TREE: """Produce the operations of the ansatz circuit.""" for i in range(self.iterations): # Apply one- and two-body interactions with a swap network that # reverses the order of the modes def one_and...
"""Produce qubits that can be used by the ansatz circuit.""" n_qubits = 2*self.x_dim*self.y_dim return cirq.LineQubit.range(n_qubits)
identifier_body
f23.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 mut x = 23; let mut y = 23; let mut z = 23; while x > 0 { x -= 1; while y > 0 { y -= 1; while z > 0 { z -= 1; } if x > 10 { return; "unreachable"; } } } }
expr_while_23
identifier_name
f23.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 ...
} } }
{ return; "unreachable"; }
conditional_block
f23.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 ...
#[allow(unreachable_code)] pub fn expr_while_23() { let mut x = 23; let mut y = 23; let mut z = 23; while x > 0 { x -= 1; while y > 0 { y -= 1; while z > 0 { z -= 1; } if x > 10 { return; "unreachable"; }...
// option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
f23.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 mut x = 23; let mut y = 23; let mut z = 23; while x > 0 { x -= 1; while y > 0 { y -= 1; while z > 0 { z -= 1; } if x > 10 { return; "unreachable"; } } } }
identifier_body
download.py
# This file is part of the "upq" program used on springfiles.com to manage file # uploads, mirror distribution etc. It is published under the GPLv3. # #Copyright (C) 2011 Daniel Troeder (daniel #at# admin-box #dot# com) # #You should have received a copy of the GNU General Public License #along with this program. If n...
""" "download url:$url" """ def run(self): url=self.jobdata['url'] filename=os.path.basename(url) tmpfile=os.path.join(self.getcfg('temppath', '/tmp'), filename) self.jobdata['file']=tmpfile self.logger.debug("going to download %s", url) try: response = requests.get(url, stream=True, verify=False) ...
identifier_body
download.py
# This file is part of the "upq" program used on springfiles.com to manage file # uploads, mirror distribution etc. It is published under the GPLv3. # #Copyright (C) 2011 Daniel Troeder (daniel #at# admin-box #dot# com) # #You should have received a copy of the GNU General Public License #along with this program. If n...
self.logger.debug("going to download %s", url) try: response = requests.get(url, stream=True, verify=False) with open(tmpfile, 'wb') as out_file: shutil.copyfileobj(response.raw, out_file) del response self.logger.debug("downloaded to %s", tmpfile) except Exception as e: self.logger.error(str(e...
url=self.jobdata['url'] filename=os.path.basename(url) tmpfile=os.path.join(self.getcfg('temppath', '/tmp'), filename) self.jobdata['file']=tmpfile
random_line_split
download.py
# This file is part of the "upq" program used on springfiles.com to manage file # uploads, mirror distribution etc. It is published under the GPLv3. # #Copyright (C) 2011 Daniel Troeder (daniel #at# admin-box #dot# com) # #You should have received a copy of the GNU General Public License #along with this program. If n...
(self): url=self.jobdata['url'] filename=os.path.basename(url) tmpfile=os.path.join(self.getcfg('temppath', '/tmp'), filename) self.jobdata['file']=tmpfile self.logger.debug("going to download %s", url) try: response = requests.get(url, stream=True, verify=False) with open(tmpfile, 'wb') as out_file: ...
run
identifier_name