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
IndexedTriangleStripSet.js
/* -*- Mode: JavaScript; coding: utf-8; tab-width: 3; indent-tabs-mode: tab; c-basic-offset: 3 -*- ******************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright create3000, Scheffelstraße 31a, Leipzig, Germany 2011. ...
(executionContext) { X3DComposedGeometryNode .call (this, executionContext); this .addType (X3DConstants .IndexedTriangleStripSet); this .triangleIndex = [ ]; } IndexedTriangleStripSet .prototype = $.extend (Object .create (X3DComposedGeometryNode .prototype), { constructor: IndexedTriangleStripSet, fi...
ndexedTriangleStripSet
identifier_name
conf.py
have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the
sys.path.insert(0, os.path.abspath('../')) sys.path.insert(0, os.path.abspath('./')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They...
# documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../../'))
random_line_split
usePath.test.tsx
/** * Copyright 2021 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to...
const { result } = renderHook(() => usePath(), { wrapper: Wrapper }); const [path, setPath] = result.current; return { path, setPath, history, }; } it('picks up path from the URL', async () => { const { path } = setup(); expect(path).toBe(initialPath); }); it('update...
{children} </Route> </Router> ); };
random_line_split
usePath.test.tsx
/** * Copyright 2021 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to...
history, }; } it('picks up path from the URL', async () => { const { path } = setup(); expect(path).toBe(initialPath); }); it('updates the URL', async () => { const newPath = 'new/path'; const { setPath, history } = setup(); setPath(newPath); expect(history.location.pathname...
{ const history = createMemoryHistory({ initialEntries: [`/storage/${bucket}/${initialPath}`], }); const Wrapper: React.FC = ({ children }) => { return ( <Router history={history}> <Route exact path={storagePath + `:bucket/:path*`}> {children} </Route> ...
identifier_body
usePath.test.tsx
/** * Copyright 2021 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to...
() { const history = createMemoryHistory({ initialEntries: [`/storage/${bucket}/${initialPath}`], }); const Wrapper: React.FC = ({ children }) => { return ( <Router history={history}> <Route exact path={storagePath + `:bucket/:path*`}> {children} </Route>...
setup
identifier_name
data_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use hyper::mime::{Attr, Mime, SubLevel, TopLevel, Value}; use mime_classifier::MimeClassifier; use net_traits::{Lo...
}, Err(DecodeError::InvalidDataUri) => send_error(url, NetworkError::Internal("invalid data uri".to_owned()), start_chan), Err(DecodeError::NonBase64DataUri) => send_error(url, NetworkError::Internal("non-base64 data uri".to_owned()), start_chan), } }
let _ = chan.send(Payload(bytes)); let _ = chan.send(Done(Ok(()))); }
conditional_block
data_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use hyper::mime::{Attr, Mime, SubLevel, TopLevel, Value}; use mime_classifier::MimeClassifier; use net_traits::{Lo...
pub fn decode(url: &Url) -> Result<DecodeData, DecodeError> { assert!(url.scheme() == "data"); // Split out content type and data. let parts: Vec<&str> = url[Position::BeforePath..Position::AfterQuery].splitn(2, ',').collect(); if parts.len() != 2 { return Err(DecodeError::InvalidDataUri); }...
pub type DecodeData = (Mime, Vec<u8>);
random_line_split
data_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use hyper::mime::{Attr, Mime, SubLevel, TopLevel, Value}; use mime_classifier::MimeClassifier; use net_traits::{Lo...
{ InvalidDataUri, NonBase64DataUri, } pub type DecodeData = (Mime, Vec<u8>); pub fn decode(url: &Url) -> Result<DecodeData, DecodeError> { assert!(url.scheme() == "data"); // Split out content type and data. let parts: Vec<&str> = url[Position::BeforePath..Position::AfterQuery].splitn(2, ',').col...
DecodeError
identifier_name
data_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use hyper::mime::{Attr, Mime, SubLevel, TopLevel, Value}; use mime_classifier::MimeClassifier; use net_traits::{Lo...
send_error(url, NetworkError::Internal("invalid data uri".to_owned()), start_chan), Err(DecodeError::NonBase64DataUri) => send_error(url, NetworkError::Internal("non-base64 data uri".to_owned()), start_chan), } }
let url = load_data.url; if cancel_listener.is_cancelled() { return; } match decode(&url) { Ok((content_type, bytes)) => { let mut metadata = Metadata::default(url); metadata.set_content_type(Some(content_type).as_ref()); if let Ok(chan) = start_send...
identifier_body
l3agentscheduler.py
# Copyright (c) 2013 OpenStack Foundation. # All rights reserved. # # 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...
(cls): return "Schedule routers among l3 agents" @classmethod def get_namespace(cls): return "http://docs.openstack.org/ext/l3_agent_scheduler/api/v1.0" @classmethod def get_updated(cls): return "2013-02-07T10:00:00-00:00" @classmethod def get_resources(cls): "...
get_description
identifier_name
l3agentscheduler.py
# Copyright (c) 2013 OpenStack Foundation. # All rights reserved. # # 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...
class RouterReschedulingFailed(exceptions.Conflict): message = _("Failed rescheduling router %(router_id)s: " "no eligible l3 agent found.") class RouterNotHostedByL3Agent(exceptions.Conflict): message = _("The router %(router_id)s is not hosted" " by L3 agent %(agent_id)s."...
message = _("Failed scheduling router %(router_id)s to" " the L3 Agent %(agent_id)s.")
identifier_body
l3agentscheduler.py
# Copyright (c) 2013 OpenStack Foundation. # All rights reserved. # # 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...
message = _("Not allowed to manually assign a %(router_type)s " "router %(router_id)s from an existing DVR node " "to another L3 agent %(agent_id)s.") class L3AgentSchedulerPluginBase(object): """REST API to operate the l3 agent scheduler. All of method must be in an admin...
class DVRL3CannotAssignToDvrAgent(exceptions.Conflict):
random_line_split
l3agentscheduler.py
# Copyright (c) 2013 OpenStack Foundation. # All rights reserved. # # 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...
return plugin def index(self, request, **kwargs): plugin = self.get_plugin() policy.enforce(request.context, "get_%s" % L3_ROUTERS, {}) return plugin.list_routers_on_l3_agent( request.context, kwargs['agent_id']) def cr...
LOG.error(_LE('No plugin for L3 routing registered to handle ' 'router scheduling')) msg = _('The resource could not be found.') raise webob.exc.HTTPNotFound(msg)
conditional_block
ToDoWebPart.ts
import { BaseClientSideWebPart, IPropertyPaneSettings, IWebPartContext, PropertyPaneToggle } from '@microsoft/sp-client-preview'; import ModuleLoader from '@microsoft/sp-module-loader'; import styles from './ToDo.module.scss'; import * as strings from 'toDoStrings'; import { IToDoWebPartProps } from './IToDoW...
} protected get disableReactivePropertyChanges(): boolean { return true; } }
{ return { pages: [ { header: { description: strings.PropertyPaneDescription }, groups: [ { groupName: strings.ViewGroupName, groupFields: [ PropertyPaneToggle('hideFinishedTasks', { lab...
identifier_body
ToDoWebPart.ts
import { BaseClientSideWebPart, IPropertyPaneSettings, IWebPartContext, PropertyPaneToggle } from '@microsoft/sp-client-preview'; import ModuleLoader from '@microsoft/sp-module-loader'; import styles from './ToDo.module.scss'; import * as strings from 'toDoStrings'; import { IToDoWebPartProps } from './IToDoW...
return true; } }
random_line_split
ToDoWebPart.ts
import { BaseClientSideWebPart, IPropertyPaneSettings, IWebPartContext, PropertyPaneToggle } from '@microsoft/sp-client-preview'; import ModuleLoader from '@microsoft/sp-module-loader'; import styles from './ToDo.module.scss'; import * as strings from 'toDoStrings'; import { IToDoWebPartProps } from './IToDoW...
(context: IWebPartContext) { super(context); ModuleLoader.loadCss('https://appsforoffice.microsoft.com/fabric/2.6.1/fabric.min.css'); ModuleLoader.loadCss('https://appsforoffice.microsoft.com/fabric/2.6.1/fabric.components.min.css'); } public render(): void { if (this.renderedOnce === false) { ...
constructor
identifier_name
ToDoWebPart.ts
import { BaseClientSideWebPart, IPropertyPaneSettings, IWebPartContext, PropertyPaneToggle } from '@microsoft/sp-client-preview'; import ModuleLoader from '@microsoft/sp-module-loader'; import styles from './ToDo.module.scss'; import * as strings from 'toDoStrings'; import { IToDoWebPartProps } from './IToDoW...
<uif-list-item-action ng-click="vm.deleteTodo(todo)"> <uif-icon uif-type="trash"></uif-icon> </uif-list-item-action> </uif-list-item-actions> </uif-list-item> </uif-list> </div> </div>`; this.$injector = angular.bootstrap(this.domElement, ['todoapp']); } ...
{ this.domElement.innerHTML = ` <div class="${styles.toDoWebPart}"> <div data-ng-controller="HomeController as vm"> <div class="${styles.loading}" ng-show="vm.isLoading"> <uif-spinner>Loading...</uif-spinner> </div> <div id="entryform" ng-show="vm.isLoading === false"> <uif-textfield uif...
conditional_block
convmixer.py
import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.models.registry import register_model from .helpers import build_model_with_cfg def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, ...
self.stem = nn.Sequential( nn.Conv2d(in_chans, dim, kernel_size=patch_size, stride=patch_size), activation(), nn.BatchNorm2d(dim) ) self.blocks = nn.Sequential( *[nn.Sequential( Residual(nn.Sequential( nn...
random_line_split
convmixer.py
import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.models.registry import register_model from .helpers import build_model_with_cfg def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, ...
(nn.Module): def __init__(self, dim, depth, kernel_size=9, patch_size=7, in_chans=3, num_classes=1000, activation=nn.GELU, **kwargs): super().__init__() self.num_classes = num_classes self.num_features = dim self.head = nn.Linear(dim, num_classes) if num_classes > 0 else nn.Identity(...
ConvMixer
identifier_name
convmixer.py
import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.models.registry import register_model from .helpers import build_model_with_cfg def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, ...
) self.pooling = nn.Sequential( nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten() ) def get_classifier(self): return self.head def reset_classifier(self, num_classes, global_pool=''): self.num_classes = num_classes self.head = nn.Linear(self.nu...
super().__init__() self.num_classes = num_classes self.num_features = dim self.head = nn.Linear(dim, num_classes) if num_classes > 0 else nn.Identity() self.stem = nn.Sequential( nn.Conv2d(in_chans, dim, kernel_size=patch_size, stride=patch_size), activation(), ...
identifier_body
cart_model.js
/* * 定义购物车模型 * [购物车]: 顾客 产品 订单账单 发货数据 */ var mongoose = require('mongoose'), Schema = mongoose.Schema; //地址模型,用于发货信息和账单信息的一部分 var AddressSchema = new Schema({ name: String, address: String, city: String, state: String, zip: String }, {_id: false}); //禁止id自动分配,因为并不需要根据ID查找地址 mongoose.mo...
shipping: [AddressSchema], billing: [BillingSchema], status: {type: String, default: "Pending"}, timestamp: {type: Date, default: Date.now} }); mongoose.model('Order', OrderSchema); //顾客模型 var CutsomerSchema = new Schema({ userid: {type: String, unique: true, required: true}, shipping: [AddressS...
mongoose.model('ProductQuantity', ProductQuantitySchema); //订单模型 var OrderSchema = new Schema({ userid: String, items: [ProductQuantitySchema],
random_line_split
pipeline.py
# Copyright 2020 Google LLC. All Rights Reserved. # # 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 a...
( pipeline_name: str, pipeline_root: str, data_path: str, preprocessing_fn: str, run_fn: str, train_args: tfx.proto.TrainArgs, eval_args: tfx.proto.EvalArgs, eval_accuracy_threshold: float, serving_model_dir: str, schema_path: Optional[str] = None, metadata_connection_config:...
create_pipeline
identifier_name
pipeline.py
# Copyright 2020 Google LLC. All Rights Reserved. # # 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 a...
schema_path: Optional[str] = None, metadata_connection_config: Optional[ metadata_store_pb2.ConnectionConfig] = None, beam_pipeline_args: Optional[List[str]] = None, ) -> tfx.dsl.Pipeline: """Implements the penguin pipeline with TFX.""" components = [] # Brings data into the pipeline or othe...
eval_args: tfx.proto.EvalArgs, eval_accuracy_threshold: float, serving_model_dir: str,
random_line_split
pipeline.py
# Copyright 2020 Google LLC. All Rights Reserved. # # 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 a...
# Performs transformations and feature engineering in training and serving. transform = tfx.components.Transform( # pylint: disable=unused-variable examples=example_gen.outputs['examples'], schema=schema_gen.outputs['schema'], preprocessing_fn=preprocessing_fn) # TODO(step 3): Uncomment here ...
schema_gen = tfx.components.ImportSchemaGen(schema_file=schema_path) components.append(schema_gen) # Performs anomaly detection based on statistics and data schema. example_validator = tfx.components.ExampleValidator( # pylint: disable=unused-variable statistics=statistics_gen.outputs['statistics'...
conditional_block
pipeline.py
# Copyright 2020 Google LLC. All Rights Reserved. # # 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 a...
# Import user provided schema into the pipeline. schema_gen = tfx.components.ImportSchemaGen(schema_file=schema_path) components.append(schema_gen) # Performs anomaly detection based on statistics and data schema. example_validator = tfx.components.ExampleValidator( # pylint: disable=unused-variab...
"""Implements the penguin pipeline with TFX.""" components = [] # Brings data into the pipeline or otherwise joins/converts training data. # TODO(step 2): Might use another ExampleGen class for your data. example_gen = tfx.components.CsvExampleGen(input_base=data_path) components.append(example_gen) # Co...
identifier_body
TestGridFS.js
module.exports = (function() { var mongoose = require('mongoose'), Schema = mongoose.Schema; var Test = Schema({ name:String, age:Number, job:Number
}); Test.statics.test = function() { //this.testWrite(); this.testRead(); }; Test.statics.testWrite = function() { var mongo = app.mongo; var db = app.db; var gridStore = new mongo.GridStore(db, new mongo.ObjectID(), 'w', {root: 'fs'}); gridStor...
}, { collection: 'test'
random_line_split
version.js
/*! * ---------- * XFDB®-Data * ---------- * Data of XFDB — A manually curated dedicated xylella fastidiosa database. * ___________________________________________________________________________ * * Grunt, http://gruntjs.com/ — The JavaScript Task Runner. * _____________________________________________________...
* ___________________________________________________________________________ */
* * --/The Heart of Build System/-- of "XFDB®-Data".
random_line_split
util.js
var DAL = require('../db/DAL').DAL; var debug = require('debug')('scorm-profile-viewer:util'); module.exports = { mustBeLoggedIn: function(req, res, next) { if (req.user) return next(); else res.redirect('/users/login?r=' + encodeURIComponent(req.originalUrl)); }, testAuth: function (req, r...
} }); }); } }, testForParams: function (params) { return function (req, res, next) { params.forEach((param) => { if (!req.query[param]) return res.status(400).send(`Bad Request - missing ${param} param`); })...
{ var credentials = new Buffer(auth.split(" ").pop(), "base64").toString("ascii").split(":"); var username = credentials[0], password = credentials[1]; DAL.getUser(username, function (err, user) { debug(username, user._id, user.username); ...
conditional_block
util.js
var DAL = require('../db/DAL').DAL; var debug = require('debug')('scorm-profile-viewer:util'); module.exports = { mustBeLoggedIn: function(req, res, next) { if (req.user) return next(); else res.redirect('/users/login?r=' + encodeURIComponent(req.originalUrl)); }, testAuth: function (req, r...
DAL.validatePassword(user, password, function (err, valid) { if (err || !valid) { debug('invalid password on existing user'); return res.status(403).send("Access Denied (incorrect credentials)"); } else { ...
random_line_split
limitTo.js
'use strict'; /** * @ngdoc function * @name ng.filter:limitTo * @function * * @description * Creates a new array or string containing only a specified number of elements. The elements * are taken from either the beginning or the end of the source array or string, as specified by * the value and sign (positive ...
expect(letterLimitInput.getAttribute('value')).toBe('3'); expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]'); expect(limitedLetters.getText()).toEqual('Output letters: abc'); }); it('should update the output when -3 is entered', function() { numLimitIn...
random_line_split
limitTo.js
'use strict'; /** * @ngdoc function * @name ng.filter:limitTo * @function * * @description * Creates a new array or string containing only a specified number of elements. The elements * are taken from either the beginning or the end of the source array or string, as specified by * the value and sign (positive ...
(){ return function(input, limit) { if (!isArray(input) && !isString(input)) return input; limit = int(limit); if (isString(input)) { //NaN check on limit if (limit) { return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); } else { return ""; ...
limitToFilter
identifier_name
limitTo.js
'use strict'; /** * @ngdoc function * @name ng.filter:limitTo * @function * * @description * Creates a new array or string containing only a specified number of elements. The elements * are taken from either the beginning or the end of the source array or string, as specified by * the value and sign (positive ...
limit = input.length; else if (limit < -input.length) limit = -input.length; if (limit > 0) { i = 0; n = limit; } else { i = input.length + limit; n = input.length; } for (; i<n; i++) { out.push(input[i]); } return out; }; }
{ return function(input, limit) { if (!isArray(input) && !isString(input)) return input; limit = int(limit); if (isString(input)) { //NaN check on limit if (limit) { return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); } else { return ""; ...
identifier_body
deleteUserAuthorization.js
import jwt from 'jsonwebtoken'; import ErrorConstants from '../constants/ErrorConstants'; import { User } from '../models'; import Constants from '../constants/Constants'; const { userDeleteUnauthorizedError, voidUserDeleteError, } = ErrorConstants; /** * @description allows users to delete only his account. * ...
const expectedUserId = queryResult.dataValues.id; if (expectedUserId !== user.id && user.roleId !== Constants.adminRole) { error.message = userDeleteUnauthorizedError; statusCode = 403; throw error; } next(); }) .catch(error => response .status(statusCode) ...
{ statusCode = 404; error.message = voidUserDeleteError; throw error; }
conditional_block
deleteUserAuthorization.js
import jwt from 'jsonwebtoken'; import ErrorConstants from '../constants/ErrorConstants'; import { User } from '../models'; import Constants from '../constants/Constants'; const { userDeleteUnauthorizedError, voidUserDeleteError, } = ErrorConstants; /** * @description allows users to delete only his account. * ...
export default deleteUserAuthorization;
.json({ error: error.message }) ); };
random_line_split
colors_template_json.py
""" Example loading all specs from JSON template """ from flask import Flask, jsonify from flasgger import Swagger app = Flask(__name__) app.config['SWAGGER'] = { 'title': 'Colors API', 'uiversion': 2 } swag = Swagger(app, template_file='colors_template.json') @app.route('/colors/<palette>/') def colors(pal...
'cmyk': ['cian', 'magenta', 'yellow', 'black'], 'rgb': ['red', 'green', 'blue'] } if palette == 'all': result = all_colors else: result = {palette: all_colors.get(palette)} return jsonify(result) if __name__ == "__main__": app.run(debug=True)
all_colors = {
random_line_split
colors_template_json.py
""" Example loading all specs from JSON template """ from flask import Flask, jsonify from flasgger import Swagger app = Flask(__name__) app.config['SWAGGER'] = { 'title': 'Colors API', 'uiversion': 2 } swag = Swagger(app, template_file='colors_template.json') @app.route('/colors/<palette>/') def colors(pal...
else: result = {palette: all_colors.get(palette)} return jsonify(result) if __name__ == "__main__": app.run(debug=True)
result = all_colors
conditional_block
colors_template_json.py
""" Example loading all specs from JSON template """ from flask import Flask, jsonify from flasgger import Swagger app = Flask(__name__) app.config['SWAGGER'] = { 'title': 'Colors API', 'uiversion': 2 } swag = Swagger(app, template_file='colors_template.json') @app.route('/colors/<palette>/') def colors(pal...
if __name__ == "__main__": app.run(debug=True)
""" Example using a dictionary as specification This is the description You can also set 'summary' and 'description' in specs_dict --- # values here overrides the specs dict deprecated: true """ all_colors = { 'cmyk': ['cian', 'magenta', 'yellow', 'black'], 'rgb': ['r...
identifier_body
colors_template_json.py
""" Example loading all specs from JSON template """ from flask import Flask, jsonify from flasgger import Swagger app = Flask(__name__) app.config['SWAGGER'] = { 'title': 'Colors API', 'uiversion': 2 } swag = Swagger(app, template_file='colors_template.json') @app.route('/colors/<palette>/') def
(palette): """ Example using a dictionary as specification This is the description You can also set 'summary' and 'description' in specs_dict --- # values here overrides the specs dict deprecated: true """ all_colors = { 'cmyk': ['cian', 'magenta', 'yellow', 'black'], ...
colors
identifier_name
InfoBar.py
Decoder, \ InfoBarEPG, InfoBarSeek, InfoBarInstantRecord, \ InfoBarAudioSelection, InfoBarAdditionalInfo, InfoBarNotifications, InfoBarDish, InfoBarUnhandledKey, \ InfoBarSubserviceSelection, InfoBarShowMovies, InfoBarTimeshift, \ InfoBarServiceNotifications, InfoBarPVRState, InfoBarCueSheetSupport, InfoBarSimpleE...
(self): if config.usage.e1like_radio_mode.value: self.showRadioChannelList(True) else: self.rds_display.hide() # in InfoBarRdsDecoder from Screens.ChannelSelection import ChannelSelectionRadio self.session.openWithCallback(self.ChannelSelectionRadioClosed, ChannelSelectionRadio, self) def ChannelSelec...
showRadio
identifier_name
InfoBar.py
Decoder, \ InfoBarEPG, InfoBarSeek, InfoBarInstantRecord, \ InfoBarAudioSelection, InfoBarAdditionalInfo, InfoBarNotifications, InfoBarDish, InfoBarUnhandledKey, \ InfoBarSubserviceSelection, InfoBarShowMovies, InfoBarTimeshift, \ InfoBarServiceNotifications, InfoBarPVRState, InfoBarCueSheetSupport, InfoBarSimpleE...
def deleteConfirmed(self, answer): if answer: self.leavePlayerConfirmed((True, "quitanddeleteconfirmed")) def leavePlayerConfirmed(self, answer): answer = answer and answer[1] if answer in ("quitanddelete", "quitanddeleteconfirmed"): ref = self.session.nav.getCurrentlyPlayingServiceReference() from...
self.handleLeave(config.usage.on_movie_stop.value)
identifier_body
InfoBar.py
dsDecoder, \ InfoBarEPG, InfoBarSeek, InfoBarInstantRecord, \ InfoBarAudioSelection, InfoBarAdditionalInfo, InfoBarNotifications, InfoBarDish, InfoBarUnhandledKey, \ InfoBarSubserviceSelection, InfoBarShowMovies, InfoBarTimeshift, \ InfoBarServiceNotifications, InfoBarPVRState, InfoBarCueSheetSupport, InfoBarSimpl...
def showMovies(self): from Screens.MovieSelection import MovieSelection self.session.openWithCallback(self.movieSelected, MovieSelection) def movieSelected(self, service): if service is not None: self.session.open(MoviePlayer, service) class MoviePlayer(InfoBarBase, InfoBarShowHide, \ InfoBarMenu, \ In...
self.session.openWithCallback(self.ChannelSelectionRadioClosed, ChannelSelectionRadio, self) def ChannelSelectionRadioClosed(self, *arg): self.rds_display.show() # in InfoBarRdsDecoder
random_line_split
InfoBar.py
Decoder, \ InfoBarEPG, InfoBarSeek, InfoBarInstantRecord, \ InfoBarAudioSelection, InfoBarAdditionalInfo, InfoBarNotifications, InfoBarDish, InfoBarUnhandledKey, \ InfoBarSubserviceSelection, InfoBarShowMovies, InfoBarTimeshift, \ InfoBarServiceNotifications, InfoBarPVRState, InfoBarCueSheetSupport, InfoBarSimpleE...
class MoviePlayer(InfoBarBase, InfoBarShowHide, \ InfoBarMenu, \ InfoBarSeek, InfoBarShowMovies, InfoBarAudioSelection, HelpableScreen, InfoBarNotifications, InfoBarServiceNotifications, InfoBarPVRState, InfoBarCueSheetSupport, InfoBarSimpleEventView, InfoBarMoviePlayerSummarySupport, InfoBarSubtitleSupport, ...
self.session.open(MoviePlayer, service)
conditional_block
headers.py
from webob.multidict import MultiDict from flanker.mime.message.headers import encodedword from flanker.mime.message.headers.parsing import normalize, parse_stream from flanker.mime.message.headers.encoding import to_mime from flanker.mime.message.errors import EncodingError class MimeHeaders(object): """Diction...
else: return value
return value.replace('\r', '').replace('\n', '')
conditional_block
headers.py
from webob.multidict import MultiDict from flanker.mime.message.headers import encodedword from flanker.mime.message.headers.parsing import normalize, parse_stream from flanker.mime.message.headers.encoding import to_mime from flanker.mime.message.errors import EncodingError class MimeHeaders(object): """Diction...
def transform(self, fn, decode=False): """Accepts a function, getting a key, val and returning a new pair of key, val and applies the function to all header, value pairs in the message. """ changed = [False] def tracking_fn(key, val): new_key, new_val ...
""" Returns the keys. (message header names) It remembers the order in which they were added, what is really important """ return self._v.keys()
identifier_body
headers.py
from webob.multidict import MultiDict from flanker.mime.message.headers import encodedword from flanker.mime.message.headers.parsing import normalize, parse_stream from flanker.mime.message.headers.encoding import to_mime from flanker.mime.message.errors import EncodingError class MimeHeaders(object): """Diction...
(self): return str(self._v) @classmethod def from_stream(cls, stream): """ Takes a stream and reads the headers, decodes headers to unicode dict like object. """ return cls(parse_stream(stream)) def to_stream(self, stream, prepends_only=False): """ ...
__str__
identifier_name
headers.py
from webob.multidict import MultiDict from flanker.mime.message.headers import encodedword from flanker.mime.message.headers.parsing import normalize, parse_stream from flanker.mime.message.headers.encoding import to_mime from flanker.mime.message.errors import EncodingError class MimeHeaders(object): """Diction...
for (key, val) in items]) self.changed = False self.num_prepends = 0 def __getitem__(self, key): v = self._v.get(normalize(key), None) if v is not None: return encodedword.decode(v) return None def __len__(self): return l...
def __init__(self, items=()): self._v = MultiDict([(normalize(key), remove_newlines(val))
random_line_split
ProjectInfo.ts
var projectInfo = { richang: { uuid: '1' }, hunjia: { uuid: '2' }, lvyou: { uuid: '3' }, zhuangxiu: { uuid: '4' }, gongsi: { uuid: '5' }, fangchan: { uuid: '6' }, feilvbin: { uuid: '7e9801051...
}, qingrenjie: { uuid: 'B59C168E0CA8476F8CCBCA2C70795DF4' }, duanzu: { uuid: 'b4179bdc59f2420190c41b70d1305876' } }; module.exports = projectInfo;
}, banjia: { uuid: '96a907313f64487f913cb04ad1d45870'
random_line_split
keys_to_twist_with_ramps.py
#!/usr/bin/env python # BEGIN ALL import rospy import math from std_msgs.msg import String from geometry_msgs.msg import Twist key_mapping = { 'w': [ 0, 1], 'x': [ 0, -1], 'a': [ 1, 0], 'd': [-1, 0], 's': [ 0, 0] } g_twist_pub = None g_target_twist = None g_last_twist = None g_last_...
def fetch_param(name, default): if rospy.has_param(name): return rospy.get_param(name) else: print "parameter [%s] not defined. Defaulting to %.3f" % (name, default) return default if __name__ == '__main__': rospy.init_node('keys_to_twist') g_last_twist_send_time = rospy.Time.now() g_twist_pub ...
global g_target_twist, g_last_twist, g_vel_scales if len(msg.data) == 0 or not key_mapping.has_key(msg.data[0]): return # unknown key. vels = key_mapping[msg.data[0]] g_target_twist.angular.z = vels[0] * g_vel_scales[0] g_target_twist.linear.x = vels[1] * g_vel_scales[1]
identifier_body
keys_to_twist_with_ramps.py
#!/usr/bin/env python # BEGIN ALL import rospy import math from std_msgs.msg import String from geometry_msgs.msg import Twist key_mapping = { 'w': [ 0, 1], 'x': [ 0, -1], 'a': [ 1, 0], 'd': [-1, 0], 's': [ 0, 0] } g_twist_pub = None g_target_twist = None g_last_twist = None g_last_...
# END ALL
send_twist() rate.sleep()
conditional_block
keys_to_twist_with_ramps.py
#!/usr/bin/env python # BEGIN ALL import rospy import math from std_msgs.msg import String from geometry_msgs.msg import Twist key_mapping = { 'w': [ 0, 1], 'x': [ 0, -1], 'a': [ 1, 0], 'd': [-1, 0], 's': [ 0, 0] } g_twist_pub = None g_target_twist = None g_last_twist = None g_last_...
(prev, target, t_prev, t_now, ramps): tw = Twist() tw.angular.z = ramped_vel(prev.angular.z, target.angular.z, t_prev, t_now, ramps[0]) tw.linear.x = ramped_vel(prev.linear.x, target.linear.x, t_prev, t_now, ramps[1]) return tw def send_twist(): global g...
ramped_twist
identifier_name
keys_to_twist_with_ramps.py
#!/usr/bin/env python # BEGIN ALL import rospy import math from std_msgs.msg import String from geometry_msgs.msg import Twist
key_mapping = { 'w': [ 0, 1], 'x': [ 0, -1], 'a': [ 1, 0], 'd': [-1, 0], 's': [ 0, 0] } g_twist_pub = None g_target_twist = None g_last_twist = None g_last_send_time = None g_vel_scales = [0.1, 0.1] # default to very slow g_vel_ramps = [1, 1] # units: meters per second^2 # BEGIN RA...
random_line_split
stdlib_2.py
# output formatting # reprlib provides a version of repr() import reprlib print(reprlib.repr(set('supercalifragilisticexpialidocious'))) # pprint - more sophisticated control over printing objects in a way readable by the interpreter import pprint t = [[[['black','cyan'],'white',['green','red']],[['magenta','yellow'],...
background = AsyncZip('mydata.txt', 'myarchive.zip') print('Task in another thread is starting...', '\n') background.start() print('The main program continues to run in foreground.') print('Something happens in here...', '\n') background.join() # wait for the background task to finish print('Main program waited unt...
f = zipfile.ZipFile(self.outfile,'w',zipfile.ZIP_DEFLATED) f.write(self.infile) f.close() print('Finished background zip of:', self.infile)
identifier_body
stdlib_2.py
# output formatting # reprlib provides a version of repr() import reprlib print(reprlib.repr(set('supercalifragilisticexpialidocious'))) # pprint - more sophisticated control over printing objects in a way readable by the interpreter import pprint t = [[[['black','cyan'],'white',['green','red']],[['magenta','yellow'],...
start += 16 filename = data[start:start+filenamesize] start += filenamesize extra = data[start:start+extra_size] print(filename, hex(crc32), comp_size, uncomp_size) start += extra_size + comp_size # skip to the next header """ # multi-threading # how the high level threading module can run ta...
crc32, comp_size, uncomp_size, filenamesize, extra_size = fields
random_line_split
stdlib_2.py
# output formatting # reprlib provides a version of repr() import reprlib print(reprlib.repr(set('supercalifragilisticexpialidocious'))) # pprint - more sophisticated control over printing objects in a way readable by the interpreter import pprint t = [[[['black','cyan'],'white',['green','red']],[['magenta','yellow'],...
# another application for templating is separating program logic from the details of multiple output formats # the struct module provides pack() and unpack() functions for working with variable length binary record formats # following example shows how to loop through header information in a ZIP file without using th...
base, ext = os.path.splitext(filename) newname = t.substitute(d=date, n=i, f=ext) print('{0} -> {1}'.format(filename, newname))
conditional_block
stdlib_2.py
# output formatting # reprlib provides a version of repr() import reprlib print(reprlib.repr(set('supercalifragilisticexpialidocious'))) # pprint - more sophisticated control over printing objects in a way readable by the interpreter import pprint t = [[[['black','cyan'],'white',['green','red']],[['magenta','yellow'],...
(Template): delimiter = '%' # fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ') fmt = 'Cajetan_%n%f' t = BatchRename(fmt) date = time.strftime('%d%b%y') for i, filename in enumerate(photofiles): base, ext = os.path.splitext(filename) newname = t.substitute(d=date, n=i, f=ext) print('{0}...
BatchRename
identifier_name
input.py
# -*- coding: utf-8 -*- # Copyright (c) 2015-2022, Exa Analytics Development Team # Distributed under the terms of the Apache License 2.0 #''' #PW Module Input File Editor #==================================== # #'''
#import numpy as np #from exatomic.exa import DataFrame #from exatomic import Length, Frame, Atom #from exqe.input import QEInput #from exqe.types import lengths # # #class PWInput(QEInput): # ''' # Editor representation of QE's pw.x input file. # ''' # def parse_frame(self): # ''' # Parse the...
random_line_split
dunces-and-dungeons.py
from dungeon.dungeon import Dungeon, Hub from entity.player.players import Player, Party import entity.item.items as items import sys, os import base import web.server try: import dill except: dill = None PARTY = Party() class Manager: def __init__(self): self.checked = False def
(self): latest = None try: import requests latest = requests.get('https://api.github.com/repos/microwaveabletoaster/dunces-and-dungeons/releases/latest').json()['tag_name'] except: base.put("could not reach the update service :'(") return latest def update_check(self): base.put('checking for update...
get_current_release
identifier_name
dunces-and-dungeons.py
from dungeon.dungeon import Dungeon, Hub from entity.player.players import Player, Party import entity.item.items as items import sys, os import base import web.server try: import dill except: dill = None PARTY = Party() class Manager: def __init__(self): self.checked = False def get_current_release(self): ...
intro = """ ______ _ _______ _______ _______ ( __ \ |\ /|( ( /|( ____ \( ____ \( ____ \\ | ( \ )| ) ( || \ ( || ( \/| ( \/| ( \/ | | ) || | | || \ | || | | (__ | (_____ | | | || | | || (\ \) || | | __) (_____ ) | | ) || | | || | \ || | ...
self.webbed = webbed if webbed: # ha amphibian joke base.IS_WEB_VERSION = True base.SERVER = web.server web.server.party = PARTY print 'MOVED ON' base.BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ver = [] with open('%s/version.dunce' % base.BASE_DIR, 'r+') as f: contents = f.read() if ...
identifier_body
dunces-and-dungeons.py
from dungeon.dungeon import Dungeon, Hub from entity.player.players import Player, Party import entity.item.items as items import sys, os import base import web.server try: import dill except: dill = None PARTY = Party() class Manager: def __init__(self): self.checked = False def get_current_release(self): ...
if __name__ == '__main__': game = Manager() try: if sys.argv[1] == 'web': print 'initializing web server. point your browser to http://localhost:5000.' game.main(True) else: game.main() except IndexError: game.main()
PARTY.handle_player_turn() if(PARTY.end): PARTY.current_dungeon.handle_monster_turn() base.put("\n\n------------=========GAME OVER=========------------")
random_line_split
dunces-and-dungeons.py
from dungeon.dungeon import Dungeon, Hub from entity.player.players import Player, Party import entity.item.items as items import sys, os import base import web.server try: import dill except: dill = None PARTY = Party() class Manager: def __init__(self): self.checked = False def get_current_release(self): ...
base.put("\n\n------------=========GAME OVER=========------------") else: party_size = base.get_input('enter the size of your party: ') if int(party_size) is 0: base.put("you can't play with zero people, dingus") sys.exit() # creating all the players in the party for a in range(int(party_size)...
PARTY.handle_player_turn() if(PARTY.end): PARTY.current_dungeon.handle_monster_turn()
conditional_block
persistence.d.ts
/** * Copyright 2017 Google Inc. * * 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 ag...
* durable storage until the transaction resolves its PersistencePromise. * Since memory-only storage components do not alter durable storage, they are * free to ignore the transaction. * * This contract is enough to allow the LocalStore be be written * independently of whether or not the stored state actuall...
random_line_split
fist.ts
import Weapon from './weapon'; import Character from '../../objects/character'; import Mob from '../../objects/mob'; import GameObject from '../../objects/game_object'; import { PendingTurnAction, TurnDirector } from '../../objects/pending_actions/pending_turn_actions'; import Env from '../../env'; import Player from '...
} public static preload(load : Phaser.Loader) : void { } public getIconName() : string { return null; } }
{ turnDirector.addSingle(new PendingMeleeAttackAction(env, this.owner, target, damage, true)); }
conditional_block
fist.ts
import Weapon from './weapon'; import Character from '../../objects/character'; import Mob from '../../objects/mob'; import GameObject from '../../objects/game_object'; import { PendingTurnAction, TurnDirector } from '../../objects/pending_actions/pending_turn_actions'; import Env from '../../env'; import Player from '...
(load : Phaser.Loader) : void { } public getIconName() : string { return null; } }
preload
identifier_name
fist.ts
import Weapon from './weapon'; import Character from '../../objects/character'; import Mob from '../../objects/mob'; import GameObject from '../../objects/game_object'; import { PendingTurnAction, TurnDirector } from '../../objects/pending_actions/pending_turn_actions'; import Env from '../../env'; import Player from '...
/** * Pefrorm attack and create {PendingTurnAction} */ public performAttack(target : Player | Character | Mob, env : Env, turnDirector : TurnDirector) : void { if (this.owner.stats.rollLuck(target.stats, env.game.rnd) >= 0) { var damage : number = this.owner.stats.rollDamage(target.stats, this.stats...
{ return this.owner.distance(target) == 1 && this.owner.canSee(target); }
identifier_body
fist.ts
import Weapon from './weapon'; import Character from '../../objects/character'; import Mob from '../../objects/mob'; import GameObject from '../../objects/game_object'; import { PendingTurnAction, TurnDirector } from '../../objects/pending_actions/pending_turn_actions'; import Env from '../../env'; import Player from '...
public static preload(load : Phaser.Loader) : void { } public getIconName() : string { return null; } }
} else { turnDirector.addSingle(new PendingMeleeAttackAction(env, this.owner, target, damage, true)); } }
random_line_split
cacheprovider.py
except (IOError, OSError): self.warn("could not create cache path {path}", path=path) return try: f = path.open("wb" if PY2 else "w") except (IOError, OSError): self.warn("cache could not write path {path}", path=path) else: with f: ...
key = valpath.relative_to(vdir) val = config.cache.get(key, dummy) if val is dummy: tw.line("%s contains unreadable content, will be ignored" % key) else: tw.line("%s contains:" % key) for line in pformat(val).splitlines(): tw.line(" " + line)
conditional_block
cacheprovider.py
) cachedir.mkdir() return cls(cachedir, config) @staticmethod def cache_dir_from_config(config): return resolve_from_str(config.getini("cache_dir"), config.rootdir) def warn(self, fmt, **args): from _pytest.warnings import _issue_warning_captured from _pytest.wa...
random_line_split
cacheprovider.py
ir = cls.cache_dir_from_config(config) if config.getoption("cacheclear") and cachedir.exists(): rmtree(cachedir, force=True) cachedir.mkdir() return cls(cachedir, config) @staticmethod def cache_dir_from_config(config): return resolve_from_str(config.getini("cach...
def pytest_report_collectionfinish(self): if self.active and self.config.getoption("verbose") >= 0: if not self._previously_failed_count: return None noun = "failure" if self._previously_failed_count == 1 else "failures" suffix = " first" if self.config....
self.config = config active_keys = "lf", "failedfirst" self.active = any(config.getoption(key) for key in active_keys) self.lastfailed = config.cache.get("cache/lastfailed", {}) self._previously_failed_count = None self._no_failures_behavior = self.config.getoption("last_failed_n...
identifier_body
cacheprovider.py
ir = cls.cache_dir_from_config(config) if config.getoption("cacheclear") and cachedir.exists(): rmtree(cachedir, force=True) cachedir.mkdir() return cls(cachedir, config) @staticmethod def cache_dir_from_config(config): return resolve_from_str(config.getini("cach...
(self): """Create supporting files in the cache dir that are not really part of the cache.""" if self._cachedir.is_dir(): readme_path = self._cachedir / "README.md" if not readme_path.is_file(): readme_path.write_text(README_CONTENT) gitignore_path = ...
_ensure_supporting_files
identifier_name
mod.rs
//! **Canonicalization** is the key to constructing a query in the //! middle of type inference. Ordinarily, it is not possible to store //! types from type inference in query keys, because they contain //! references to inference variables whose lifetimes are too short //! and so forth. Canonicalizing a value T1 using...
<T>( &self, span: Span, canonical: &Canonical<'tcx, T>, ) -> (T, CanonicalVarValues<'tcx>) where T: TypeFoldable<'tcx>, { // For each universe that is referred to in the incoming // query, create a universe in our local inference context. In // practic...
instantiate_canonical_with_fresh_inference_vars
identifier_name
mod.rs
//! **Canonicalization** is the key to constructing a query in the //! middle of type inference. Ordinarily, it is not possible to store //! types from type inference in query keys, because they contain //! references to inference variables whose lifetimes are too short //! and so forth. Canonicalizing a value T1 using...
/// Given the "infos" about the canonical variables from some /// canonical, creates fresh variables with the same /// characteristics (see `instantiate_canonical_var` for /// details). You can then use `substitute` to instantiate the /// canonical variable with these inference variables. fn i...
{ // For each universe that is referred to in the incoming // query, create a universe in our local inference context. In // practice, as of this writing, all queries have no universes // in them, so this code has no effect, but it is looking // forward to the day when we *do* wa...
identifier_body
mod.rs
//! **Canonicalization** is the key to constructing a query in the //! middle of type inference. Ordinarily, it is not possible to store //! types from type inference in query keys, because they contain //! references to inference variables whose lifetimes are too short
//! - a value T2 where each unbound inference variable has been //! replaced with a **canonical variable**; //! - a map M (of type `CanonicalVarValues`) from those canonical //! variables back to the original. //! //! We can then do queries using T2. These will give back constraints //! on the canonical variables w...
//! and so forth. Canonicalizing a value T1 using `canonicalize_query` //! produces two things: //!
random_line_split
mod.rs
//! **Canonicalization** is the key to constructing a query in the //! middle of type inference. Ordinarily, it is not possible to store //! types from type inference in query keys, because they contain //! references to inference variables whose lifetimes are too short //! and so forth. Canonicalizing a value T1 using...
CanonicalVarKind::Region(ui) => self .next_region_var_in_universe( RegionVariableOrigin::MiscVariable(span), universe_map(ui), ) .into(), CanonicalVarKind::PlaceholderRegion(ty::PlaceholderRegion { univers...
{ let universe_mapped = universe_map(universe); let placeholder_mapped = ty::PlaceholderType { universe: universe_mapped, name }; self.tcx.mk_ty(ty::Placeholder(placeholder_mapped)).into() }
conditional_block
dropRepeats.ts
import {Operator, Stream} from '../index'; const empty = {}; export class DropRepeatsOperator<T> implements Operator<T, T> { public type = 'dropRepeats'; public out: Stream<T> = null as any; public isEq: (x: T, y: T) => boolean; private v: T = <any> empty; constructor(public ins: Stream<T>, fn...
(err: any) { const u = this.out; if (!u) return; u._e(err); } _c() { const u = this.out; if (!u) return; u._c(); } } /** * Drops consecutive duplicate values in a stream. * * Marble diagram: * * ```text * --1--2--1--1--1--2--3--4--3--3| * dropRepeats * --1--2--1--------2--3--...
_e
identifier_name
dropRepeats.ts
import {Operator, Stream} from '../index'; const empty = {}; export class DropRepeatsOperator<T> implements Operator<T, T> { public type = 'dropRepeats'; public out: Stream<T> = null as any; public isEq: (x: T, y: T) => boolean; private v: T = <any> empty; constructor(public ins: Stream<T>, fn...
_stop(): void { this.ins._remove(this); this.out = null as any; this.v = empty as any; } _n(t: T) { const u = this.out; if (!u) return; const v = this.v; if (v !== empty && this.isEq(t, v)) return; this.v = t; u._n(t); } _e(err: any) { const u = this.out; if (!u...
{ this.out = out; this.ins._add(this); }
identifier_body
dropRepeats.ts
import {Operator, Stream} from '../index'; const empty = {}; export class DropRepeatsOperator<T> implements Operator<T, T> { public type = 'dropRepeats'; public out: Stream<T> = null as any; public isEq: (x: T, y: T) => boolean; private v: T = <any> empty; constructor(public ins: Stream<T>, fn...
* import dropRepeats from 'xstream/extra/dropRepeats' * * const stream = xs.of(1, 2, 1, 1, 1, 2, 3, 4, 3, 3) * .compose(dropRepeats()) * * stream.addListener({ * next: i => console.log(i), * error: err => console.error(err), * complete: () => console.log('completed') * }) * ``` * * ```text * > 1 ...
* Example: * * ```js
random_line_split
prime_test.py
""" prime_test(n) returns a True if n is a prime number else it returns False """ import unittest def prime_test(n): if n <= 1:
j = 5 while j * j <= n: if n % j == 0 or n % (j + 2) == 0: return False j += 6 return True def prime_test2(n): # prime numbers are greater than 1 if n > 1: # check for factors for i in range(2, int(n ** 0.5) + 1): if (n % i) == 0: ...
return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False
random_line_split
prime_test.py
""" prime_test(n) returns a True if n is a prime number else it returns False """ import unittest def prime_test(n): if n <= 1: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False j = 5 while j * j <= n: if n % j == 0 or n % (j + ...
self.assertEqual(25, counter) if __name__ == "__main__": unittest.main()
counter += 1
conditional_block
prime_test.py
""" prime_test(n) returns a True if n is a prime number else it returns False """ import unittest def prime_test(n): if n <= 1: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False j = 5 while j * j <= n: if n % j == 0 or n % (j + ...
self.assertEqual(25, counter) if __name__ == "__main__": unittest.main()
def test_prime_test(self): """ checks all prime numbers between 2 up to 100. Between 2 up to 100 exists 25 prime numbers! """ counter = 0 for i in range(2, 101): if prime_test(i): counter += 1 self.assertEqual(25, counter) ...
identifier_body
prime_test.py
""" prime_test(n) returns a True if n is a prime number else it returns False """ import unittest def
(n): if n <= 1: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False j = 5 while j * j <= n: if n % j == 0 or n % (j + 2) == 0: return False j += 6 return True def prime_test2(n): # prime numbers are gre...
prime_test
identifier_name
vega-yellow-orange-red-4.js
and swatches. build(config.colors, config.document.mode); /** * Creates and adds swatch groups and swatches. * * @param {Array} colors * @param {String} mode */ function build(colors, mode) { var colorGroups = getColorGroups(colors); colorGroups.forEach(function (colorGroup, colorGroupIndex) { // Cr...
() { // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Polyfill if (!Array.prototype.filter) { Array.prototype.filter = function (fun /*, thisArg*/ ) { 'use strict'; if (this === void 0 || this === null) { throw new TypeError(); } var...
polyfill
identifier_name
vega-yellow-orange-red-4.js
{Array} colors * @returns {Number} */ function getMaxShades(colors) { var max = 0; var colorGroups = getColorGroups(colors); colorGroups.forEach(function (colorGroup, colorGroupIndex) { // Gets colors that belong to group. var groupColors = colors.filter(function (o) { return o.group === colorGr...
{ // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of o with argument Pk. // This step can be combined with c // c. If kPresent is true, then ...
conditional_block
vega-yellow-orange-red-4.js
and swatches. build(config.colors, config.document.mode); /** * Creates and adds swatch groups and swatches. * * @param {Array} colors * @param {String} mode */ function build(colors, mode) { var colorGroups = getColorGroups(colors); colorGroups.forEach(function (colorGroup, colorGroupIndex) { // Cr...
/** * Removes all swatches. */ function removeAllSwatches() { for (var i = 0; i < doc.swatches.length; i++) { doc.swatches[i].remove(); } } /** * Removes all swatch groups. */ function removeAllSwatchGroups() { for (var i = 0; i < doc.swatchGroups.length; i++) { doc.swatchGroups[i].remove(); } } ...
swatch.name = name; return swatch; }
random_line_split
vega-yellow-orange-red-4.js
and swatches. build(config.colors, config.document.mode); /** * Creates and adds swatch groups and swatches. * * @param {Array} colors * @param {String} mode */ function build(colors, mode) { var colorGroups = getColorGroups(colors); colorGroups.forEach(function (colorGroup, colorGroupIndex) { // Cr...
/** * Draws rectangle on artboard. * * @param {Number} top * @param {Number} left * @param {Number} width * @param {Number} height * @param {String} name * @param {Color} color * @returns {PathItem} */ function drawSwatchRect(top, left, width, height, name, color) { var layer = doc.layers[0]; ...
{ for (var i = 0; i < doc.swatchGroups.length; i++) { doc.swatchGroups[i].remove(); } }
identifier_body
index.d.ts
/** * Copyright (c) 2002-2017 "Neo Technology,"," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * 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 t...
error: typeof error; Driver: Driver; AuthToken: AuthToken; Config: Config; Session: Session; Transaction: Transaction; }; export { driver, int, isInt, integer, Neo4jError, auth, types, session, error, AuthToken, Session, Config, } export default forExport;
Neo4jError: typeof Neo4jError; auth: typeof auth; types: typeof types; session: typeof session;
random_line_split
__init__.py
# Copyright 2016 Amazon Web Services, Inc. or its affiliates. All Rights Reserved. # This file is licensed to you under the AWS Customer Agreement (the "License"). # You may not use this file except in compliance with the License. # A copy of the License is located at http://aws.amazon.com/agreement/ . # This file...
print responseUrl responseBody = {} responseBody['Status'] = responseStatus responseBody['Reason'] = 'See the details in CloudWatch Log Stream: ' + context.log_stream_name responseBody['PhysicalResourceId'] = physicalResourceId or context.log_stream_name responseBody['StackId'] = event['StackI...
def send(event, context, responseStatus, responseData, physicalResourceId=None): responseUrl = event['ResponseURL']
random_line_split
__init__.py
# Copyright 2016 Amazon Web Services, Inc. or its affiliates. All Rights Reserved. # This file is licensed to you under the AWS Customer Agreement (the "License"). # You may not use this file except in compliance with the License. # A copy of the License is located at http://aws.amazon.com/agreement/ . # This file...
(event, context, responseStatus, responseData, physicalResourceId=None): responseUrl = event['ResponseURL'] print responseUrl responseBody = {} responseBody['Status'] = responseStatus responseBody['Reason'] = 'See the details in CloudWatch Log Stream: ' + context.log_stream_name responseBody['...
send
identifier_name
__init__.py
# Copyright 2016 Amazon Web Services, Inc. or its affiliates. All Rights Reserved. # This file is licensed to you under the AWS Customer Agreement (the "License"). # You may not use this file except in compliance with the License. # A copy of the License is located at http://aws.amazon.com/agreement/ . # This file...
} try: response = requests.put(responseUrl, data=json_responseBody, headers=headers) print "Status code: " + response.reason except Exception as e: print "send(..) failed executing requests.put(..): " + str(e)
responseUrl = event['ResponseURL'] print responseUrl responseBody = {} responseBody['Status'] = responseStatus responseBody['Reason'] = 'See the details in CloudWatch Log Stream: ' + context.log_stream_name responseBody['PhysicalResourceId'] = physicalResourceId or context.log_stream_name resp...
identifier_body
inquiry.py
import gtk import highgtk.entity import highgtk.present.default.layout def add (inquiry): window = getattr (inquiry, "present_window", None) if window is None: inquiry.present_window = gtk.Dialog() title = getattr (inquiry, "title", None) if title is None: root = highgtk.en...
method_name = getattr (inquiry, "ok_method", "inquiry_okay") error = inquiry.present_layout.get_error() if error is not None: inquiry.error_report.primary = error inquiry.add (inquiry.error_report) else: method = getattr (inquiry.parent, method_name) method (inquiry, inqu...
method (inquiry) inquiry.remove (inquiry) def okay (inquiry):
random_line_split
inquiry.py
import gtk import highgtk.entity import highgtk.present.default.layout def add (inquiry): window = getattr (inquiry, "present_window", None) if window is None: inquiry.present_window = gtk.Dialog() title = getattr (inquiry, "title", None) if title is None: root = highgtk.e...
def response (widget, response_id, inquiry): if response_id==gtk.RESPONSE_OK: okay (inquiry) elif response_id==gtk.RESPONSE_CANCEL: cancel (inquiry) return True def delete_event (widget, event, inquiry): cancel (inquiry) return True
method_name = getattr (inquiry, "ok_method", "inquiry_okay") error = inquiry.present_layout.get_error() if error is not None: inquiry.error_report.primary = error inquiry.add (inquiry.error_report) else: method = getattr (inquiry.parent, method_name) method (inquiry, inquiry....
identifier_body
inquiry.py
import gtk import highgtk.entity import highgtk.present.default.layout def add (inquiry): window = getattr (inquiry, "present_window", None) if window is None:
else: window.present() def remove (inquiry): window = getattr (inquiry, "present_window", None) if window is not None: window.hide() del inquiry.present_window def cancel (inquiry): method_name = getattr (inquiry, "cancel_method", None) if method_name is not None: ...
inquiry.present_window = gtk.Dialog() title = getattr (inquiry, "title", None) if title is None: root = highgtk.entity.get_root (inquiry) title = "Inquiry from %s" % root.name inquiry.present_window.add_button (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) ok_text = geta...
conditional_block
inquiry.py
import gtk import highgtk.entity import highgtk.present.default.layout def
(inquiry): window = getattr (inquiry, "present_window", None) if window is None: inquiry.present_window = gtk.Dialog() title = getattr (inquiry, "title", None) if title is None: root = highgtk.entity.get_root (inquiry) title = "Inquiry from %s" % root.name ...
add
identifier_name
6.py
import urllib2 import zipfile import re url = "http://www.pythonchallenge.com/pc/def/channel.zip" data = urllib2.urlopen(url).read() file1='ttt.zip' with open(file1,'wb+') as fzip: fzip.write(data) #dd=re.compile(r'[from|is] (\d+$)') dd = re.compile(r'(?<=[from|is] )(\d+)') zf = zipfile.ZipFile(file1,'r') text=...
print text print data1
text = zf.read(cc.group()+'.txt') data1 += zf.getinfo(cc.group()+'.txt').comment cc = dd.search(text)
conditional_block
6.py
import urllib2
data = urllib2.urlopen(url).read() file1='ttt.zip' with open(file1,'wb+') as fzip: fzip.write(data) #dd=re.compile(r'[from|is] (\d+$)') dd = re.compile(r'(?<=[from|is] )(\d+)') zf = zipfile.ZipFile(file1,'r') text=zf.read('readme.txt') cc = dd.search(text) while cc: #print text text = zf.read(cc.group()+...
import zipfile import re url = "http://www.pythonchallenge.com/pc/def/channel.zip"
random_line_split
Separator.js
var baidu = require('common:widget/lib/tangram/base/base.js'); require('common:widget/lib/tangram/uiBase/uiBase.js'); /** * Tangram * Copyright 2009 Baidu Inc. All rights reserved. */ require('common:widget/lib/tangram/ui/Toolbar/Toolbar.js'); /** * @private * @class Toolbar类 * @param {Object} op...
tplMain: '<span id="#{id}" class="#{class}" style="display:block"></span>', /** * 获取HTML字符串 * @private * @return {String} HTMLString. */ getString: function() { var me = this; return baidu.format(me.tplMain, { ...
* @private */
random_line_split
stream.py
import io import json class Stream(object): __shortname__ = "stream" """ This is a base class that should be inherited when implementing different stream types. Should only be created by plugins. """ def __init__(self, session): self.session = session def __repr__(self): ...
@property def json(self): obj = self.__json__() return json.dumps(obj) @classmethod def shortname(cls): return cls.__shortname__ class StreamIO(io.IOBase): pass __all__ = ["Stream", "StreamIO"]
Raises :exc:`StreamError` on failure. """ raise NotImplementedError
random_line_split
stream.py
import io import json class Stream(object): __shortname__ = "stream" """ This is a base class that should be inherited when implementing different stream types. Should only be created by plugins. """ def __init__(self, session): self.session = session def __repr__(self): ...
def open(self): """ Attempts to open a connection to the stream. Returns a file-like object that can be used to read the stream data. Raises :exc:`StreamError` on failure. """ raise NotImplementedError @property def json(self): obj = self.__json__(...
return dict(type=type(self).shortname())
identifier_body
stream.py
import io import json class Stream(object): __shortname__ = "stream" """ This is a base class that should be inherited when implementing different stream types. Should only be created by plugins. """ def __init__(self, session): self.session = session def
(self): return "<Stream()>" def __json__(self): return dict(type=type(self).shortname()) def open(self): """ Attempts to open a connection to the stream. Returns a file-like object that can be used to read the stream data. Raises :exc:`StreamError` on failure. ...
__repr__
identifier_name
S15.10.4.1_A4_T3.js
// Copyright 2009 the Sputnik authors. All rights reserved. /** * let F be the empty string if flags is undefined * * @path ch15/15.10/15.10.4/S15.10.4.1_A4_T3.js * @description Use undefined properties of object as flags of RegExp */
if (__re.multiline !== false) { $ERROR('#2: __re = new RegExp({}.p, {}.q); __re.multiline === false. Actual: ' + (__re.multiline)); } //CHECK#3 if (__re.global !== false) { $ERROR('#3: __re = new RegExp({}.p, {}.q); __re.global === false. Actual: ' + (__re.global)); } //CHECK#4 if (__re.ignoreCase !== false) { ...
__re = new RegExp({}.p, {}.q); //CHECK#2
random_line_split
S15.10.4.1_A4_T3.js
// Copyright 2009 the Sputnik authors. All rights reserved. /** * let F be the empty string if flags is undefined * * @path ch15/15.10/15.10.4/S15.10.4.1_A4_T3.js * @description Use undefined properties of object as flags of RegExp */ __re = new RegExp({}.p, {}.q); //CHECK#2 if (__re.multiline !== false)
//CHECK#3 if (__re.global !== false) { $ERROR('#3: __re = new RegExp({}.p, {}.q); __re.global === false. Actual: ' + (__re.global)); } //CHECK#4 if (__re.ignoreCase !== false) { $ERROR('#4: __re = new RegExp({}.p, {}.q); __re.ignoreCase === false. Actual: ' + (__re.ignoreCase)); }
{ $ERROR('#2: __re = new RegExp({}.p, {}.q); __re.multiline === false. Actual: ' + (__re.multiline)); }
conditional_block