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
thermo.py
import scipy.integrate as intg import numpy as np #Physical Constants #Everything is in MKS units #Planck constant [J/s] h = 6.6261e-34 #Boltzmann constant [J/K] kB = 1.3806e-23 #Speed of light [m/s] c = 299792458.0 #Pi PI = 3.14159265 #Vacuum Permitivity eps0 = 8.85e-12 #Resistivity of the mirror rho=2.417e-8 GHz = ...
(freq, index=None): """Convert from from frequency [Hz] to wavelength [m]""" if index == None: index = 1. return c/(freq*index) def dielectricLoss( lossTan, thickness, index, freq, atmScatter=0): """Dielectric loss coefficient with thickness [m] and freq [Hz]""" return 1.0 - np.exp((-2...
lamb
identifier_name
thermo.py
import scipy.integrate as intg import numpy as np #Physical Constants #Everything is in MKS units #Planck constant [J/s] h = 6.6261e-34 #Boltzmann constant [J/K] kB = 1.3806e-23 #Speed of light [m/s] c = 299792458.0 #Pi PI = 3.14159265 #Vacuum Permitivity eps0 = 8.85e-12 #Resistivity of the mirror rho=2.417e-8 GHz = ...
def getLambdaOpt(nu, chi): geom = (1 / np.cos(chi) - np.cos(chi)) return - 2 * geom * np.sqrt(4 * PI * eps0 * rho * nu) def aniPowSpec(emissivity, freq, temp=None): if temp == None: temp = Tcmb occ = 1.0/(np.exp(h*freq/(temp*kB)) - 1) return ((h**2)/kB)*emissivity*(occ**...
geom = (1 / np.cos(chi) - np.cos(chi)) return - 2 * geom * np.sqrt(4 * PI * eps0 * rho )
identifier_body
coercion.rs
b` variable, which could mean that we'd auto-borrow later arguments but not earlier ones, which seems very confusing. ## Subtler note However, right now, if the user manually specifies the values for the type variables, as so: foo::<&int>(@1, @2) then we *will* auto-borrow, because we can't distinguish this from...
a: ty::t, sty_a: &ty::sty, b: ty::t) -> CoerceResult {
random_line_split
coercion.rs
{ return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_string(a, sty_a, b) }; } ty::ty_evec(mt_b, vstore_slice(_)) => { return do self.unpack_actual_value(a) |sty_a| { self.coerce_borrowed_v...
coerce_unsafe_ptr
identifier_name
coercion.rs
`foo(&1, @2)`, we will not auto-borrow either argument. In older code we went to some lengths to resolve the `b` variable, which could mean that we'd auto-borrow later arguments but not earlier ones, which seems very confusing. ## Subtler note However, right now, if the user manually specifies the values for the ty...
}; let r_a = self.infcx.next_region_var(Coercion(self.trace)); let a_borrowed = ty::mk_estr(self.infcx.tcx, vstore_slice(r_a)); if_ok!(self.subtype(a_borrowed, b)); Ok(Some(@AutoDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(AutoBorrowVec(r_a, m_im...
{ return self.subtype(a, b); }
conditional_block
coercion.rs
actually determine the kind of coercions that should occur separately and pass them in. Or maybe it's ok as is. Anyway, it's sort of a minor point so I've opted to leave it for later---after all we may want to adjust precisely when coercions occur. */ use middle::ty::{AutoPtr, AutoBorrowVec, AutoBorrowFn}; use mi...
{ debug!("coerce_borrowed_fn(a=%s, sty_a=%?, b=%s)", a.inf_str(self.infcx), sty_a, b.inf_str(self.infcx)); let fn_ty = match *sty_a { ty::ty_closure(ref f) if f.sigil == ast::ManagedSigil => copy *f, ty::ty_closure(ref f) if f.sigil == ast::OwnedSig...
identifier_body
ShrdluAI.ts
class ShrdluAI extends RobotAI { constructor(o:Ontology, nlp:NLParser, shrdlu:A4AICharacter, game:ShrdluA4Game, rulesFileNames:string[]) { super(o, nlp, shrdlu, game, rulesFileNames); console.log("ShrdluAI.constructor end..."); this.robot.ID = "shrdlu"; this.selfID = "shrdlu"; this.visionActive = false;...
} return super.canSatisfyActionRequest(ir); } executeIntention(ir:IntentionRecord) : boolean { let intention:Term = ir.action; let repairSort:Sort = this.o.getSort("verb.repair"); if (intention.functor.is_a(repairSort)) { // just ignore, the story script will take charge of making shrdlu do the re...
{ return ACTION_REQUEST_CANNOT_BE_SATISFIED; }
conditional_block
ShrdluAI.ts
class ShrdluAI extends RobotAI { constructor(o:Ontology, nlp:NLParser, shrdlu:A4AICharacter, game:ShrdluA4Game, rulesFileNames:string[]) { super(o, nlp, shrdlu, game, rulesFileNames); console.log("ShrdluAI.constructor end..."); this.robot.ID = "shrdlu"; this.selfID = "shrdlu"; this.visionActive = false;...
app.achievement_nlp_all_robot_actions[11] = true; app.trigger_achievement_complete_alert(); return ACTION_REQUEST_CAN_BE_SATISFIED; } } else { return ACTION_REQUEST_CANNOT_BE_SATISFIED; } } return super.canSatisfyActionRequest(ir); } executeIntention(ir:IntentionRecord) : boolean...
app.trigger_achievement_complete_alert(); return ACTION_REQUEST_CAN_BE_SATISFIED; } else if (thingToRepair_id == "tardis-broken-cable") {
random_line_split
ShrdluAI.ts
class ShrdluAI extends RobotAI { constructor(o:Ontology, nlp:NLParser, shrdlu:A4AICharacter, game:ShrdluA4Game, rulesFileNames:string[]) { super(o, nlp, shrdlu, game, rulesFileNames); console.log("ShrdluAI.constructor end..."); this.robot.ID = "shrdlu"; this.selfID = "shrdlu"; this.visionActive = false;...
(ir:IntentionRecord) : boolean { let intention:Term = ir.action; let repairSort:Sort = this.o.getSort("verb.repair"); if (intention.functor.is_a(repairSort)) { // just ignore, the story script will take charge of making shrdlu do the repair... this.clearCurrentAction(); return true; } return super....
executeIntention
identifier_name
line_points.js
= dx * dx0 + dy * dy0; if(dot > 0 && dot < norm2) { var cross = dx0 * dy - dy0 * dx; if(cross * cross < norm2) return true; } } var latestXFrac, latestYFrac; // if we're off-screen, increase tolerance over baseTolerance function getTolerance(pt, nextPt) { ...
{ if(xSame2) pti--; else pts[pti - 1] = pt; }
conditional_block
line_points.js
var dx = xFrac1 - xFrac0; var dy = yFrac1 - yFrac0; var dx0 = 0.5 - xFrac0; var dy0 = 0.5 - yFrac0; var norm2 = dx * dx + dy * dy; var dot = dx * dx0 + dy * dy0; if(dot > 0 && dot < norm2) { var cross = dx0 * dy - dy0 * dx; if(cross * cross < norm...
(pt) { var x = pt[0]; var y = pt[1]; var xSame = x === pts[pti - 1][0]; var ySame = y === pts[pti - 1][1]; // duplicate point? if(xSame && ySame) return; if(pti > 1) { // backtracking along an edge? var xSame2 = x === pts[pti - 2][0]; ...
updateEdge
identifier_name
line_points.js
var dx = xFrac1 - xFrac0; var dy = yFrac1 - yFrac0; var dx0 = 0.5 - xFrac0; var dy0 = 0.5 - yFrac0; var norm2 = dx * dx + dy * dy; var dot = dx * dx0 + dy * dy0; if(dot > 0 && dot < norm2) { var cross = dx0 * dy - dy0 * dx; if(cross * cross < norm...
ptToAlter[dim] += midShift; } return out; }; } var getEdgeIntersections; if(shape === 'linear' || shape === 'spline') { getEdgeIntersections = getLinearEdgeIntersections; } else if(shape === 'hv' || shape === 'vh') { getEdgeIntersect...
{ return function(pt1, pt2) { var ptInt1 = onlyConstrainedPoint(pt1); var ptInt2 = onlyConstrainedPoint(pt2); var out = []; if(ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out; if(ptInt1) out.push(ptInt1); if(ptInt2) out.push(ptIn...
identifier_body
line_points.js
var dx = xFrac1 - xFrac0; var dy = yFrac1 - yFrac0; var dx0 = 0.5 - xFrac0; var dy0 = 0.5 - yFrac0; var norm2 = dx * dx + dy * dy; var dot = dx * dx0 + dy * dy0; if(dot > 0 && dot < norm2) { var cross = dx0 * dy - dy0 * dx; if(cross * cross < norm...
// duplicate point? if(xSame && ySame) return; if(pti > 1) { // backtracking along an edge? var xSame2 = x === pts[pti - 2][0]; var ySame2 = y === pts[pti - 2][1]; if(xSame && (x === xEdge0 || x === xEdge1) && xSame2) { if(ySame2) p...
var y = pt[1]; var xSame = x === pts[pti - 1][0]; var ySame = y === pts[pti - 1][1];
random_line_split
AlertIOSExample.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow */ 'use strict'; const React = require('react'); const {SimpleAlertExampleBlock} = require('./AlertExample')...
onPress={() => Alert.prompt( 'Type a value', null, this.customButtons, 'login-password', 'admin@site.com', ) }> <View style={styles.button}> <Text> prompt with title, cus...
style={styles.wrapper}
random_line_split
index.ts
import styled from 'styled-components' import type { TTestable } from '@/spec' import Img from '@/Img' import { TYPE } from '@/constant' import { theme } from '@/utils/themes' import css from '@/utils/css' type TMenuIcon = { active: boolean; colorTheme: string; raw?: string } export const Wrapper = styled.div.attrs(...
return css.size(14) }}; :last-child { margin-right: 0; } ` export const MenuDesc = styled.div` color: ${theme('thread.articleTitle')}; font-size: 12px; margin-left: 5px; margin-top: -1px; `
if (raw === TYPE.MM_TYPE.UPVOTE) return css.size(10)
random_line_split
eo.js
/*
CKEDITOR.plugins.setLang( 'image', 'eo', { alertUrl: 'Bonvolu tajpi la retadreson de la bildo', alt: 'Anstataŭiga Teksto', border: 'Bordero', btnUpload: 'Sendu al Servilo', button2Img: 'Ĉu vi volas transformi la selektitan bildbutonon en simplan bildon?', hSpace: 'Horizontala Spaco', img2Button: 'Ĉu vi volas tra...
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */
random_line_split
fixhtml.py
#!/usr/bin/env python2 """ Quick helper to add HTML5 DOCTYPE and <title> to every testcase. """ import os import re import sys def
(folder): changed = 0 for dirpath, _, filenames in os.walk(folder): for file in filenames: name, ext = os.path.splitext(file) if ext != '.html': continue path = '%s/%s' % (dirpath, file) title = ' '.join(name.split('-')) shouldb...
fixhtml
identifier_name
fixhtml.py
#!/usr/bin/env python2 """ Quick helper to add HTML5 DOCTYPE and <title> to every testcase. """ import os import re import sys def fixhtml(folder): changed = 0 for dirpath, _, filenames in os.walk(folder): for file in filenames: name, ext = os.path.splitext(file) if ext != '.ht...
folder = '.' if len(sys.argv) < 2 else sys.argv[1] changed = fixhtml(folder) print('Fixed %d files.' % changed)
random_line_split
fixhtml.py
#!/usr/bin/env python2 """ Quick helper to add HTML5 DOCTYPE and <title> to every testcase. """ import os import re import sys def fixhtml(folder): changed = 0 for dirpath, _, filenames in os.walk(folder):
return changed if __name__ == '__main__': folder = '.' if len(sys.argv) < 2 else sys.argv[1] changed = fixhtml(folder) print('Fixed %d files.' % changed)
for file in filenames: name, ext = os.path.splitext(file) if ext != '.html': continue path = '%s/%s' % (dirpath, file) title = ' '.join(name.split('-')) shouldbe = '<!DOCTYPE html>\n<title>%s</title>\n' % title with open(path, 'r') ...
conditional_block
fixhtml.py
#!/usr/bin/env python2 """ Quick helper to add HTML5 DOCTYPE and <title> to every testcase. """ import os import re import sys def fixhtml(folder):
if __name__ == '__main__': folder = '.' if len(sys.argv) < 2 else sys.argv[1] changed = fixhtml(folder) print('Fixed %d files.' % changed)
changed = 0 for dirpath, _, filenames in os.walk(folder): for file in filenames: name, ext = os.path.splitext(file) if ext != '.html': continue path = '%s/%s' % (dirpath, file) title = ' '.join(name.split('-')) shouldbe = '<!DOCTYPE...
identifier_body
url.js
or "https://". Invalid value: %s', urlString); return parseUrlDeprecated(urlString).href; } /** * Parses the query string of an URL. This method returns a simple key/value * map. If there are duplicate keys the latest value is returned. * * This function is implemented in a separate file to avoid a circu...
{ return tryDecodeUriComponent_(component, opt_fallback); }
identifier_body
url.js
a = /** @type {!HTMLAnchorElement} */ (self.document.createElement('a')); cache = self.UrlCache || (self.UrlCache = new LruCache(100)); } return parseUrlWithA(a, url, opt_nocache ? null : cache); } /** * Returns a Location-like object for the given URL. If it is relative, * the URL gets resolved. * Con...
* @param {boolean=} opt_addToFront * @return {string} */ export function addParamToUrl(url, key, value, opt_addToFront) { const field = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; return appendEncodedParamStringToUrl(url, field, opt_addToFront); } /** * Appends query string fields and values to ...
* @param {string} key * @param {string} value
random_line_split
url.js
(!a.protocol) { a.href = a.href; } const info = /** @type {!Location} */({ href: a.href, protocol: a.protocol, host: a.host, hostname: a.hostname, port: a.port == '0' ? '' : a.port, pathname: a.pathname, search: a.search, hash: a.hash, origin: null, // Set below. }); /...
isLocalhostOrigin
identifier_name
nodeinfo.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use serde_derive::{Deserialize, Serialize}; use crate::{hgid::HgId, key::Key}; #[derive( Clone, Debug, Default, Eq, Has...
}
{ NodeInfo { parents: [Key::arbitrary(g), Key::arbitrary(g)], linknode: HgId::arbitrary(g), } }
identifier_body
nodeinfo.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use serde_derive::{Deserialize, Serialize}; use crate::{hgid::HgId, key::Key}; #[derive( Clone, Debug, Default, Eq, Has...
linknode: HgId::arbitrary(g), } } }
random_line_split
nodeinfo.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use serde_derive::{Deserialize, Serialize}; use crate::{hgid::HgId, key::Key}; #[derive( Clone, Debug, Default, Eq, Has...
(g: &mut quickcheck::Gen) -> Self { NodeInfo { parents: [Key::arbitrary(g), Key::arbitrary(g)], linknode: HgId::arbitrary(g), } } }
arbitrary
identifier_name
OpenVRRenderer.py
from ctypes import c_float, cast, POINTER import numpy as np import OpenGL.GL as gl import openvr from openvr.gl_renderer import OpenVrFramebuffer as OpenVRFramebuffer from openvr.gl_renderer import matrixForOpenVrMatrix as matrixForOpenVRMatrix from openvr.tracked_devices_actor import TrackedDevicesActor import g...
self.controllers.dispose_gl() openvr.shutdown()
identifier_body
OpenVRRenderer.py
from ctypes import c_float, cast, POINTER import numpy as np import OpenGL.GL as gl import openvr from openvr.gl_renderer import OpenVrFramebuffer as OpenVRFramebuffer from openvr.gl_renderer import matrixForOpenVrMatrix as matrixForOpenVRMatrix from openvr.tracked_devices_actor import TrackedDevicesActor import g...
raise Exception('unable to create compositor') self.vr_framebuffers[0].init_gl() self.vr_framebuffers[1].init_gl() poses_t = openvr.TrackedDevicePose_t * openvr.k_unMaxTrackedDeviceCount self.poses = poses_t() self.projection_matrices = (np.asarray(matrixForOpenVRMatr...
self.vr_framebuffers = (OpenVRFramebuffer(w, h, multisample=multisample), OpenVRFramebuffer(w, h, multisample=multisample)) self.vr_compositor = openvr.VRCompositor() if self.vr_compositor is None:
random_line_split
OpenVRRenderer.py
from ctypes import c_float, cast, POINTER import numpy as np import OpenGL.GL as gl import openvr from openvr.gl_renderer import OpenVrFramebuffer as OpenVRFramebuffer from openvr.gl_renderer import matrixForOpenVrMatrix as matrixForOpenVRMatrix from openvr.tracked_devices_actor import TrackedDevicesActor import g...
self.vr_compositor.submit(openvr.Eye_Left, self.vr_framebuffers[0].texture) self.vr_compositor.submit(openvr.Eye_Right, self.vr_framebuffers[1].texture) # mirror left eye framebuffer to screen: gl.glBlitNamedFramebuffer(self.vr_framebuffers[0].fb, 0, 0,...
gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.vr_framebuffers[eye].fb) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gltfu.set_material_state.current_material = None gltfu.set_technique_state.current_technique = None for node in nodes: gltfu.d...
conditional_block
OpenVRRenderer.py
from ctypes import c_float, cast, POINTER import numpy as np import OpenGL.GL as gl import openvr from openvr.gl_renderer import OpenVrFramebuffer as OpenVRFramebuffer from openvr.gl_renderer import matrixForOpenVrMatrix as matrixForOpenVRMatrix from openvr.tracked_devices_actor import TrackedDevicesActor import g...
(self): self.controllers.dispose_gl() openvr.shutdown()
shutdown
identifier_name
plugin.py
"""Coverage plugin for pytest.""" import os import pytest from coverage.misc import CoverageException from . import embed from . import engine class CoverageError(Exception): """Indicates that our coverage is too low""" def pytest_addoption(parser): """Add options to control coverage.""" group = pars...
(object): option = self.options config = Config() self.cov_controller = controller_cls( self.options.cov_source, self.options.cov_report, self.options.cov_config, self.options.cov_append, config, nodeid ...
Config
identifier_name
plugin.py
"""Coverage plugin for pytest.""" import os import pytest from coverage.misc import CoverageException from . import embed from . import engine class CoverageError(Exception): """Indicates that our coverage is too low""" def pytest_addoption(parser): """Add options to control coverage.""" group = pars...
'cov', 'coverage reporting with distributed testing support') group.addoption('--cov', action='append', default=[], metavar='path', nargs='?', const=True, dest='cov_source', help='measure coverage for filesystem path ' '(multi-allowed)') group....
random_line_split
plugin.py
"""Coverage plugin for pytest.""" import os import pytest from coverage.misc import CoverageException from . import embed from . import engine class CoverageError(Exception): """Indicates that our coverage is too low""" def pytest_addoption(parser): """Add options to control coverage.""" group = pars...
def pytest_configure_node(self, node): """Delegate to our implementation. Mark this hook as optional in case xdist is not installed. """ self.cov_controller.configure_node(node) pytest_configure_node.optionalhook = True def pytest_testnodedown(self, node, error): ...
"""At session start determine our implementation and delegate to it.""" self.pid = os.getpid() is_slave = hasattr(session.config, 'slaveinput') if is_slave: nodeid = session.config.slaveinput.get('slaveid', getattr(session, 'nodeid')...
identifier_body
plugin.py
"""Coverage plugin for pytest.""" import os import pytest from coverage.misc import CoverageException from . import embed from . import engine class CoverageError(Exception): """Indicates that our coverage is too low""" def pytest_addoption(parser): """Add options to control coverage.""" group = pars...
def pytest_terminal_summary(self, terminalreporter): """Delegate to our implementation.""" if self.cov_controller is None: return if not (self.failed and self.options.no_cov_on_fail): try: total = self.cov_controller.summary(terminalreporter.writer) ...
self.cov_controller.finish()
conditional_block
memberable.ts
import Client from '../client' import { Constructor } from '../util' import { SiteArgs } from '../client.type' import { DeleteMemberArgs, DeleteMemberResult, SaveMemberArgs, SaveMemberResult, SearchMemberArgs, SearchMemberResult, UpdateMemberArgs, UpdateMemberResult, } from './memberable.type' // eslin...
public async deleteMember(args: DeleteMemberArgs): Promise<DeleteMemberResult> { return this.post<DeleteMemberArgs, DeleteMemberResult>('/payment/DeleteMember.idPass', { ...this.defaultMemberData(), ...args, }) } public async searchMember(args: SearchMemberArgs): Promise<Searc...
{ return this.post<UpdateMemberArgs, UpdateMemberResult>('/payment/UpdateMember.idPass', { ...this.defaultMemberData(), ...args, }) }
identifier_body
memberable.ts
import Client from '../client' import { Constructor } from '../util' import { SiteArgs } from '../client.type' import { DeleteMemberArgs, DeleteMemberResult, SaveMemberArgs, SaveMemberResult, SearchMemberArgs, SearchMemberResult, UpdateMemberArgs, UpdateMemberResult, } from './memberable.type' // eslin...
(args: UpdateMemberArgs): Promise<UpdateMemberResult> { return this.post<UpdateMemberArgs, UpdateMemberResult>('/payment/UpdateMember.idPass', { ...this.defaultMemberData(), ...args, }) } public async deleteMember(args: DeleteMemberArgs): Promise<DeleteMemberResult> { return t...
updateMember
identifier_name
memberable.ts
import Client from '../client' import { Constructor } from '../util' import { SiteArgs } from '../client.type' import { DeleteMemberArgs, DeleteMemberResult, SaveMemberArgs, SaveMemberResult, SearchMemberArgs, SearchMemberResult, UpdateMemberArgs, UpdateMemberResult, } from './memberable.type' // eslin...
const { SiteID, SitePass } = this.config return { SiteID, SitePass, MemberID: undefined, } } public async saveMember(args: SaveMemberArgs): Promise<SaveMemberResult> { return this.post<SaveMemberArgs, SaveMemberResult>('/payment/SaveMember.idPass', { ......
class extends Base { public defaultMemberData(): SiteArgs {
random_line_split
index.js
import React from 'react'; import { connect } from 'react-redux'; import { browserHistory } from 'react-router'; import { recosActions } from '../../core/recos'; import { getRecommenders, getReco } from '../../core/recos'; import { isEditing } from '../../core/loading'; import Header from '../Header'; import TextField...
() { browserHistory.goBack(); } getHeaderSaveButton() { if(this.state.name) { return <FlatButton label="Save" />; } else { return null; } } render() { if(this.props.isLoading) { return <LoadingIndicator />; } return ( <div> <Header title={'...
closeButtonClicked
identifier_name
index.js
import React from 'react'; import { connect } from 'react-redux'; import { browserHistory } from 'react-router'; import { recosActions } from '../../core/recos'; import { getRecommenders, getReco } from '../../core/recos'; import { isEditing } from '../../core/loading'; import Header from '../Header'; import TextField...
else { return null; } } render() { if(this.props.isLoading) { return <LoadingIndicator />; } return ( <div> <Header title={'Edit Reco'} iconElementLeft={<IconButton><NavigationClose /></IconButton>} onLeftIconButtonTouchTap={this.closeButtonC...
{ return <FlatButton label="Save" />; }
conditional_block
index.js
import React from 'react'; import { connect } from 'react-redux'; import { browserHistory } from 'react-router'; import { recosActions } from '../../core/recos'; import { getRecommenders, getReco } from '../../core/recos'; import { isEditing } from '../../core/loading'; import Header from '../Header'; import TextField...
handleNameChange(event) { this.setState({ name: event.target.value }); } handleRecommenderChange(value) { this.setState({ recommender: value }); } handleCategoryChange(newCategory) { if(this.state.category === newCategory) { newCategory = null; } this.setState({ categor...
{ super(); this.state = { ...props.reco }; this.handleNameChange = this.handleNameChange.bind(this); this.handleRecommenderChange = this.handleRecommenderChange.bind(this); this.handleCategoryChange = this.handleCategoryChange.bind(this); this.saveButtonClicked = this.saveButtonClicked...
identifier_body
index.js
import React from 'react'; import { connect } from 'react-redux'; import { browserHistory } from 'react-router';
import { recosActions } from '../../core/recos'; import { getRecommenders, getReco } from '../../core/recos'; import { isEditing } from '../../core/loading'; import Header from '../Header'; import TextField from 'material-ui/TextField'; import RaisedButton from 'material-ui/RaisedButton'; import { Card, CardText } fro...
random_line_split
mini-files.js
var _ = require("underscore"); var os = require("os"); var path = require("path"); var assert = require("assert"); // All of these functions are attached to files.js for the tool; // they live here because we need them in boot.js as well to avoid duplicating // a lot of the code. // // Note that this file does NOT con...
var convertToOSPath = function (standardPath, partialPath) { if (process.platform === "win32") { return toDosPath(standardPath, partialPath); } return standardPath; }; var convertToStandardPath = function (osPath, partialPath) { if (process.platform === "win32") { return toPosixPath(osPath, partialP...
p = p.replace(/\//g, '\\'); return p; };
random_line_split
mini-files.js
var _ = require("underscore"); var os = require("os"); var path = require("path"); var assert = require("assert"); // All of these functions are attached to files.js for the tool; // they live here because we need them in boot.js as well to avoid duplicating // a lot of the code. // // Note that this file does NOT con...
return standardPath; }; var convertToStandardPath = function (osPath, partialPath) { if (process.platform === "win32") { return toPosixPath(osPath, partialPath); } return osPath; } var convertToOSLineEndings = function (fileContents) { return fileContents.replace(/\n/g, os.EOL); }; var convertToStan...
{ return toDosPath(standardPath, partialPath); }
conditional_block
utilities.py
# Logic for listing and running tests. # # * @author Ben Gardner October 2009 # * @author Guy Maurel October 2015 # * @author Matthew Woehlke June 2018 # import argparse import os import subprocess import sys from .ansicolor import printc from .config import config, all_tests, FAIL_ATTRS, PASS_AT...
fail_count += 1 return { 'passing': pass_count, 'failing': fail_count, 'mismatch': mismatch_count, 'unstable': unstable_count, 'xpass': unexpectedly_passing_count } # ----------------------------------------------------------------------------- def report(c...
except Failure:
random_line_split
utilities.py
# Logic for listing and running tests. # # * @author Ben Gardner October 2009 # * @author Guy Maurel October 2015 # * @author Matthew Woehlke June 2018 # import argparse import os import subprocess import sys from .ansicolor import printc from .config import config, all_tests, FAIL_ATTRS, PASS_AT...
(parser): _add_common_arguments(parser) parser.add_argument('-p', '--show-all', action='store_true', help='show passed/skipped tests') parser.add_argument('-r', '--select', metavar='CASE(S)', type=str, help='select tests to be executed') parser.add_argu...
add_format_tests_arguments
identifier_name
utilities.py
# Logic for listing and running tests. # # * @author Ben Gardner October 2009 # * @author Guy Maurel October 2015 # * @author Matthew Woehlke June 2018 # import argparse import os import subprocess import sys from .ansicolor import printc from .config import config, all_tests, FAIL_ATTRS, PASS_AT...
# ----------------------------------------------------------------------------- def read_format_tests(filename, group): tests = [] print("Processing " + filename) with open(filename, 'rt') as f: for line_number, line in enumerate(f, 1): line = line.strip() if not len(line...
total = sum(counts.values()) print('{passing} / {total} tests passed'.format(total=total, **counts)) if counts['failing'] > 0: printc('{failing} tests failed to execute'.format(**counts), **FAIL_ATTRS) if counts['mismatch'] > 0: printc( '{mismatch} tests did not ma...
identifier_body
utilities.py
# Logic for listing and running tests. # # * @author Ben Gardner October 2009 # * @author Guy Maurel October 2015 # * @author Matthew Woehlke June 2018 # import argparse import os import subprocess import sys from .ansicolor import printc from .config import config, all_tests, FAIL_ATTRS, PASS_AT...
if counts['mismatch'] > 0: printc( '{mismatch} tests did not match the expected output'.format( **counts), **FAIL_ATTRS) if counts['unstable'] > 0: printc('{unstable} tests were unstable'.format(**counts), **FAIL_ATTRS) if counts['xpass...
printc('{failing} tests failed to execute'.format(**counts), **FAIL_ATTRS)
conditional_block
protractor.conf.js
// A reference configuration file. exports.config = { // ----- How to setup Selenium ----- // // There are three ways to specify how to use Selenium. Specify one of the // following: // // 1. seleniumServerJar - to start Selenium Standalone locally. // 2. seleniumAddress - to connect to a Selenium server ...
// ----- What tests to run ----- // // Spec patterns are relative to the location of this config. specs: [ 'e2e/*.js', ], // ----- Capabilities to be passed to the webdriver instance ---- // // For a full list of available capabilities, see // https://code.google.com/p/selenium/wiki/DesiredCapab...
allScriptsTimeout: 11000,
random_line_split
model_licenseinfo.py
# -*- coding:utf-8 -*- # This code is automatically transpiled by Saklient Translator import six from ..client import Client from .model import Model from ..resources.resource import Resource from ..resources.licenseinfo import LicenseInfo from ...util import Util import saklient str = six.text_type # module saklien...
t_key(self): return "LicenseInfo" ## @private # @return {str} def _root_key_m(self): return "LicenseInfo" ## @private # @return {str} def _class_name(self): return "LicenseInfo" ## @private # @param {any} obj # @param {bool} wrapped=False # ...
return {str} def _roo
identifier_body
model_licenseinfo.py
# -*- coding:utf-8 -*- # This code is automatically transpiled by Saklient Translator import six from ..client import Client from .model import Model from ..resources.resource import Resource from ..resources.licenseinfo import LicenseInfo from ...util import Util import saklient str = six.text_type # module saklien...
@private # @return {str} def _root_key(self): return "LicenseInfo" ## @private # @return {str} def _root_key_m(self): return "LicenseInfo" ## @private # @return {str} def _class_name(self): return "LicenseInfo" ## @private # @param {any} obj...
##
identifier_name
model_licenseinfo.py
# -*- coding:utf-8 -*- # This code is automatically transpiled by Saklient Translator import six from ..client import Client from .model import Model from ..resources.resource import Resource from ..resources.licenseinfo import LicenseInfo from ...util import Util import saklient str = six.text_type # module saklien...
## リソースの検索リクエストを実行し、結果をリストで取得します。 # # @return {saklient.cloud.resources.licenseinfo.LicenseInfo[]} リソースオブジェクトの配列 def find(self): return self._find() ## 指定した文字列を名前に含むリソースに絞り込みます。 # # 大文字・小文字は区別されません。 # 半角スペースで区切られた複数の文字列は、それらをすべて含むことが条件とみなされます。 # # @todo Imple...
# @return {saklient.cloud.resources.licenseinfo.LicenseInfo} リソースオブジェクト def get_by_id(self, id): Util.validate_type(id, "str") return self._get_by_id(id)
random_line_split
vfpclasssd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn vfpclasssd_1() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Dir...
}
run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(IndirectScaledIndexed(RSI, RDX, Eight, Some(OperandSize::Qword), None)), operand3: Some(Literal8(3)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K1), broadcast:...
random_line_split
vfpclasssd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn vfpclasssd_1() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Dir...
fn vfpclasssd_4() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(IndirectScaledIndexed(RSI, RDX, Eight, Some(OperandSize::Qword), None)), operand3: Some(Literal8(3)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(Ma...
{ run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Direct(XMM16)), operand3: Some(Literal8(38)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 179, 253, 10, 103, 208, 38], OperandSiz...
identifier_body
vfpclasssd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn
() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Direct(XMM4)), operand3: Some(Literal8(5)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 243, 253, 11, 103, 212, 5], OperandSiz...
vfpclasssd_1
identifier_name
authorization.rs
use std::fmt; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// The `Authorization` header field. #[derive(Clone, PartialEq, Show)] pub struct Authorization<S: Scheme>(pub S); impl<S: S...
() { let headers = Headers::from_raw(&mut mem("Authorization: foo bar baz\r\n\r\n")).unwrap(); assert_eq!(&headers.get::<Authorization<String>>().unwrap().0[], "foo bar baz"); } #[test] fn test_basic_auth() { let mut headers = Headers::new(); headers.set(Authorization(Basic ...
test_raw_auth_parse
identifier_name
authorization.rs
use std::fmt; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// The `Authorization` header field. #[derive(Clone, PartialEq, Show)] pub struct Authorization<S: Scheme>(pub S); impl<S: S...
}, Err(e) => { debug!("Basic::from_base64 error={:?}", e); None } } } } #[cfg(test)] mod tests { use std::io::MemReader; use super::{Authorization, Basic}; use super::super::super::{Headers}; fn mem(s: &str) -> MemReader ...
{ debug!("Basic::from_utf8 error={:?}", e); None }
conditional_block
authorization.rs
use std::fmt; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// The `Authorization` header field. #[derive(Clone, PartialEq, Show)] pub struct Authorization<S: Scheme>(pub S); impl<S: S...
None } }, Err(e) => { debug!("Basic::from_base64 error={:?}", e); None } } } } #[cfg(test)] mod tests { use std::io::MemReader; use super::{Authorization, Basic}; use super::super::super::{H...
{ match s.from_base64() { Ok(decoded) => match String::from_utf8(decoded) { Ok(text) => { let mut parts = &mut text[].split(':'); let user = match parts.next() { Some(part) => part.to_string(), No...
identifier_body
authorization.rs
use std::fmt; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// The `Authorization` header field. #[derive(Clone, PartialEq, Show)] pub struct Authorization<S: Scheme>(pub S); impl<S: S...
headers.set(Authorization(Basic { username: "Aladdin".to_string(), password: None })); assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjo=\r\n".to_string()); } #[test] fn test_basic_auth_parse() { let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRp...
random_line_split
ridged.rs
// example.rs extern crate noise; extern crate image; extern crate time; use noise::gen::NoiseGen; use noise::gen::ridgedmulti::RidgedMulti; use image::GenericImage; use std::io::File; use time::precise_time_s; fn main() { // octaves, gain, lac, offset, h let mut ngen = RidgedMulti::new_rand(24...
println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0); }
random_line_split
ridged.rs
// example.rs extern crate noise; extern crate image; extern crate time; use noise::gen::NoiseGen; use noise::gen::ridgedmulti::RidgedMulti; use image::GenericImage; use std::io::File; use time::precise_time_s; fn main()
let fout = File::create(&Path::new("ridged.png")).unwrap(); let _ = image::ImageLuma8(imbuf).save(fout, image::PNG); println!("ridged.png saved") println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0); }
{ // octaves, gain, lac, offset, h let mut ngen = RidgedMulti::new_rand(24, 1.7, 1.9, 1.0, 0.75, 100.0); println!("Noise seed is {}", ngen.get_seed()); let img_size = 512 as u32; let mut imbuf = image::ImageBuf::new(img_size, img_size); let start = precise_time_s(); for ...
identifier_body
ridged.rs
// example.rs extern crate noise; extern crate image; extern crate time; use noise::gen::NoiseGen; use noise::gen::ridgedmulti::RidgedMulti; use image::GenericImage; use std::io::File; use time::precise_time_s; fn
() { // octaves, gain, lac, offset, h let mut ngen = RidgedMulti::new_rand(24, 1.7, 1.9, 1.0, 0.75, 100.0); println!("Noise seed is {}", ngen.get_seed()); let img_size = 512 as u32; let mut imbuf = image::ImageBuf::new(img_size, img_size); let start = precise_time_s(); f...
main
identifier_name
tracer_demo.py
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Softwa...
(): import xpcom.server, xpcom.components xpcom.server.tracer = MakeTracer contractid = "Python.TestComponent" for i in range(100): c = xpcom.components.classes[contractid].createInstance().queryInterface(xpcom.components.interfaces.nsIPythonTestInterface) c.boolean_value = 0 a =...
test
identifier_name
tracer_demo.py
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Softwa...
def __setattr__(self, attr, val): if self.__dict__.has_key(attr): self.__dict__[attr] = val return setters[attr] = setters.setdefault(attr,0) + 1 setattr(self._ob, attr, val) # Installed as a global XPCOM function that if exists, will be called # to wrap each XPCOM ...
ret = getattr(self._ob, attr) # Attribute error just goes up if callable(ret): return TracerDelegate(ret) else: if not attr.startswith("_com_") and not attr.startswith("_reg_"): getters[attr] = getters.setdefault(attr,0) + 1 return ret
identifier_body
tracer_demo.py
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Softwa...
def __repr__(self): return "<Tracer around %r>" % (self._ob,) def __str__(self): return "<Tracer around %r>" % (self._ob,) def __getattr__(self, attr): ret = getattr(self._ob, attr) # Attribute error just goes up if callable(ret): return TracerDelegate(ret) ...
def __init__(self, ob): self.__dict__['_ob'] = ob
random_line_split
tracer_demo.py
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Softwa...
def __setattr__(self, attr, val): if self.__dict__.has_key(attr): self.__dict__[attr] = val return setters[attr] = setters.setdefault(attr,0) + 1 setattr(self._ob, attr, val) # Installed as a global XPCOM function that if exists, will be called # to wrap each XPCOM ...
if not attr.startswith("_com_") and not attr.startswith("_reg_"): getters[attr] = getters.setdefault(attr,0) + 1 return ret
conditional_block
index.js
/** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
* // returns [...] * * var table = { * 'default': add, * 'complex64': caddf, * 'complex128': cadd * }; * * var list = callbacks( table, sigs ); * // returns [...] */ // MODULES // var main = require( './main.js' ); // EXPORTS // module.exports = main;
* var sigs = signatures( dtypes, dtypes, dtypes );
random_line_split
middleware.rs
use std::error::Error; use std::result::Result; use nickel::{Request, Response, Middleware, Continue, MiddlewareResult}; use nickel::status::StatusCode; use r2d2_postgres::{PostgresConnectionManager, SslMode}; use r2d2::{Config, Pool, PooledConnection, GetTimeout}; use typemap::Key; use plugin::Extensible; pub struct ...
/// /// Example: /// /// ```ignore /// app.get("/my_counter", middleware! { |request, response| /// let db = try_with!(response, request.pg_conn()); /// }); /// ``` pub trait PostgresRequestExtensions { fn pg_conn(&self) -> Result<PooledConnection<PostgresConnectionManager>, (StatusCode, GetTimeout)>; } impl<'a, ...
/// /// On error, the method returns a tuple per Nickel convention. This allows the route to use the /// `try_with!` macro.
random_line_split
middleware.rs
use std::error::Error; use std::result::Result; use nickel::{Request, Response, Middleware, Continue, MiddlewareResult}; use nickel::status::StatusCode; use r2d2_postgres::{PostgresConnectionManager, SslMode}; use r2d2::{Config, Pool, PooledConnection, GetTimeout}; use typemap::Key; use plugin::Extensible; pub struct ...
} /// Add `pg_conn()` helper method to `nickel::Request` /// /// This trait must only be used in conjunction with `PostgresMiddleware`. /// /// On error, the method returns a tuple per Nickel convention. This allows the route to use the /// `try_with!` macro. /// /// Example: /// /// ```ignore /// app.get("/my_counte...
{ req.extensions_mut().insert::<PostgresMiddleware>(self.pool.clone()); Ok(Continue(res)) }
identifier_body
middleware.rs
use std::error::Error; use std::result::Result; use nickel::{Request, Response, Middleware, Continue, MiddlewareResult}; use nickel::status::StatusCode; use r2d2_postgres::{PostgresConnectionManager, SslMode}; use r2d2::{Config, Pool, PooledConnection, GetTimeout}; use typemap::Key; use plugin::Extensible; pub struct ...
<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, res: Response<'mw, D>) -> MiddlewareResult<'mw, D> { req.extensions_mut().insert::<PostgresMiddleware>(self.pool.clone()); Ok(Continue(res)) } } /// Add `pg_conn()` helper method to `nickel::Request` /// /// This trait must only be used in conj...
invoke
identifier_name
htmlhtmlelement.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 dom::bindings::codegen::Bindings::HTMLHtmlElementBinding; use dom::bindings::js::Root; use dom::bindings::str:...
Node::reflect_node(box element, document, HTMLHtmlElementBinding::Wrap) } }
random_line_split
htmlhtmlelement.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 dom::bindings::codegen::Bindings::HTMLHtmlElementBinding; use dom::bindings::js::Root; use dom::bindings::str:...
{ htmlelement: HTMLElement } impl HTMLHtmlElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLHtmlElement { HTMLHtmlElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)...
HTMLHtmlElement
identifier_name
htmlhtmlelement.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 dom::bindings::codegen::Bindings::HTMLHtmlElementBinding; use dom::bindings::js::Root; use dom::bindings::str:...
#[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLHtmlElement> { let element = HTMLHtmlElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLHtmlElement...
{ HTMLHtmlElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } }
identifier_body
lsloader.js
* 如果value值中取出的版本号和线上模版的一致,命中缓存用本地, * 否则 调用requestResource 请求资源 * jsname 文件name值,取相对路径,对应存在localStroage里的key * jspath 文件线上路径,带md5版本号,用于加载资源,区分资源版本 * cssonload css加载成功时候调用,用于配合页面展现 * */ lsloader.load = function (jsname, jspath, cssonload, isJs) { if (typeof cssonload === 'boolean...
r that = this if (isJs) { this.iojs(path, name, function (path, name, code) { that.setLS(name, path + versionString + code) that.runjs(path, name, code); }) } else { this.iocss(path, name, function (code) { document.getE...
调用cssonload 帮助控制 * 异步加载样式造车的dom树渲染错乱问题 * */ lsloader.requestResource = function (name, path, cssonload, isJs) { va
conditional_block
lsloader.js
* 如果value值中取出的版本号和线上模版的一致,命中缓存用本地, * 否则 调用requestResource 请求资源 * jsname 文件name值,取相对路径,对应存在localStroage里的key * jspath 文件线上路径,带md5版本号,用于加载资源,区分资源版本 * cssonload css加载成功时候调用,用于配合页面展现
* */ lsloader.load = function (jsname, jspath, cssonload, isJs) { if (typeof cssonload === 'boolean') { isJs = cssonload; cssonload = undefined; } isJs = isJs || false; cssonload = cssonload || function () { }; var code; code = this.getLS(...
random_line_split
entity.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import re class EntityException(Exception): """Wrap entity specific errors""" pass class Entity(object): """Base implementation for an Asana entity containing common funcitonality""" # Keys which are filtered as part of the HTTP request _filter_k...
if attr in self._children.keys(): if not attr in self._childrenValues.keys(): self._childrenValues[attr] = self.get_subitem(self._children[attr]) return self._childrenValues[attr] if attr != 'id': #todo throw standard exception for no property raise Exception("Could not locate key " + attr) ...
self.load() return self.__dict__['_data'][attr]
conditional_block
entity.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import re class EntityException(Exception): """Wrap entity specific errors""" pass class Entity(object): """Base implementation for an Asana entity containing common funcitonality""" # Keys which are filtered as part of the HTTP request _filter_k...
if attr in self._fields: self._data[attr] = value self._dirty.add(attr) else: raise Exception("Cannot set attribute {0} - unknown name".foramt(attr)) def __str__(self): return vars(self).__repr__() def __repr__(self): return self.__str__() def __hash__(self): return hash(self.id if hasattr...
elif self._ready:
random_line_split
entity.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import re class EntityException(Exception): """Wrap entity specific errors""" pass class Entity(object): """Base implementation for an Asana entity containing common funcitonality""" # Keys which are filtered as part of the HTTP request _filter_k...
(self): """Handles both creating and updating content The assumption is if there is no ID set this is a creation request """ if self.id: return self._do_update() else: #performing create - post return self._do_create() def _do_update(self): data = {} for key in self._dirty: data[key] = s...
save
identifier_name
entity.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import re class EntityException(Exception): """Wrap entity specific errors""" pass class Entity(object): """Base implementation for an Asana entity containing common funcitonality""" # Keys which are filtered as part of the HTTP request _filter_k...
def delete(self): """Deletes the specified resource. The ID must be set""" self._get_api().delete(self._get_item_url()) def __getattr__(self, attr): if attr in self.__dict__: return self.__dict__[attr] if attr in self.__dict__['_data']: return self.__dict__['_data'][attr] if attr in self._field...
return self._init(self._get_api().post(self._get_api_endpoint(), data=self._data))
identifier_body
estimate-null-insert-sizes.py
#!/usr/bin/env python """ Copyright (C) 2015 Louis Dijkstra This file is part of error-model-aligner This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your opt...
return p def loglikelihood(mu, sigma, isizes, counts, n): """Returns the loglikelihood of mu and sigma given the data (isizes, counts and n)""" l = n * math.log(normalizationFactor(mu, sigma)) for isize, count in zip(isizes, counts): l += count * math.log(f(isize, mu, sigma)) return l def aux_loglikelih...
return sys.float_info.min
conditional_block
estimate-null-insert-sizes.py
#!/usr/bin/env python """ Copyright (C) 2015 Louis Dijkstra This file is part of error-model-aligner This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your opt...
sys.exit(main())
random_line_split
estimate-null-insert-sizes.py
#!/usr/bin/env python """ Copyright (C) 2015 Louis Dijkstra This file is part of error-model-aligner This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your opt...
(var, isizes, counts, n): mu = var[0] sigma = var[1] return -1.0 * loglikelihood(mu, sigma, isizes, counts, n) def main(): parser = OptionParser(usage=usage) parser.add_option("-f", action="store", dest="maxfun", default=1000, type=int, help="Maximum number of function evaluations (Defaul...
aux_loglikelihood
identifier_name
estimate-null-insert-sizes.py
#!/usr/bin/env python """ Copyright (C) 2015 Louis Dijkstra This file is part of error-model-aligner This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your opt...
def f(isize, mu, sigma): p = norm.cdf((isize + 0.5 - mu)/sigma) - norm.cdf((isize - 0.5 - mu)/sigma) if p < sys.float_info.min: return sys.float_info.min return p def loglikelihood(mu, sigma, isizes, counts, n): """Returns the loglikelihood of mu and sigma given the data (isizes, counts and n)""" l = n * ma...
"""Returns the normalization factor given mean mu and STD sigma""" return 1.0 / (1.0 - norm.cdf((-mu - 0.5)/sigma))
identifier_body
some.js
/** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whet...
new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, observer.onError.bind(observer), function () { observer.onNext(false); observer.onCompleted(); }); }, ...
*/ observableProto.some = function (predicate, thisArg) { var source = this; return predicate ? source.filter(predicate, thisArg).some() :
random_line_split
http.ts
import * as got from "got"; import { HTTPError, JSONParseError, ReadError, RequestError, } from "./exceptions"; const pkg = require("../package.json"); // tslint:disable-line no-var-requires function parseJSON(raw: string): any { try { return JSON.parse(raw); } catch (err) { throw new JSONParseErr...
// otherwise, just rethrow throw err; } const userAgent = `${pkg.name}/${pkg.version}`; export function stream(url: string, headers: any): NodeJS.ReadableStream { headers["User-Agent"] = userAgent; return got.stream(url, { headers }); } export function get(url: string, headers: any): Promise<any> { heade...
{ throw new HTTPError(err as any); }
conditional_block
http.ts
import * as got from "got"; import { HTTPError, JSONParseError, ReadError, RequestError, } from "./exceptions"; const pkg = require("../package.json"); // tslint:disable-line no-var-requires function parseJSON(raw: string): any { try { return JSON.parse(raw); } catch (err) { throw new JSONParseErr...
export function get(url: string, headers: any): Promise<any> { headers["User-Agent"] = userAgent; return got .get(url, { headers }) .then((res: any) => parseJSON(res.body)) .catch(wrapError); } export function post(url: string, headers: any, body?: any): Promise<any> { headers["Content-Type"] = "ap...
{ headers["User-Agent"] = userAgent; return got.stream(url, { headers }); }
identifier_body
http.ts
import * as got from "got"; import { HTTPError, JSONParseError, ReadError, RequestError, } from "./exceptions"; const pkg = require("../package.json"); // tslint:disable-line no-var-requires function parseJSON(raw: string): any { try { return JSON.parse(raw); } catch (err) { throw new JSONParseErr...
(url: string, headers: any): NodeJS.ReadableStream { headers["User-Agent"] = userAgent; return got.stream(url, { headers }); } export function get(url: string, headers: any): Promise<any> { headers["User-Agent"] = userAgent; return got .get(url, { headers }) .then((res: any) => parseJSON(res.body)) ...
stream
identifier_name
http.ts
import * as got from "got"; import { HTTPError, JSONParseError, ReadError, RequestError, } from "./exceptions"; const pkg = require("../package.json"); // tslint:disable-line no-var-requires function parseJSON(raw: string): any { try { return JSON.parse(raw); } catch (err) { throw new JSONParseErr...
// otherwise, just rethrow throw err; } const userAgent = `${pkg.name}/${pkg.version}`; export function stream(url: string, headers: any): NodeJS.ReadableStream { headers["User-Agent"] = userAgent; return got.stream(url, { headers }); } export function get(url: string, headers: any): Promise<any> { headers...
random_line_split
example.rs
extern crate bmfont; #[macro_use] extern crate glium; extern crate image; use bmfont::{BMFont, OrdinateOrientation}; use glium::{Display, Program, VertexBuffer}; use std::io::Cursor; fn create_program(display: &Display) -> Program { let vertex_shader_src = r#" #version 140 in vec2 position; ...
.to_rgba(); let image_dimensions = image.dimensions(); println!("{:?}", image_dimensions); let image = glium::texture::RawImage2d::from_raw_rgba(image.into_raw(), image_dimensions); let texture = glium::texture::Texture2d::new(&display, image).unwrap(); #[derive(Copy, Clone, Debug)] str...
.unwrap()
random_line_split
example.rs
extern crate bmfont; #[macro_use] extern crate glium; extern crate image; use bmfont::{BMFont, OrdinateOrientation}; use glium::{Display, Program, VertexBuffer}; use std::io::Cursor; fn create_program(display: &Display) -> Program { let vertex_shader_src = r#" #version 140 in vec2 position; ...
() { use glium::{DisplayBuild, DrawParameters, Surface}; let display = glium::glutin::WindowBuilder::new().build_glium().unwrap(); let image = image::load(Cursor::new(&include_bytes!("../font.png")[..]), image::PNG) .unwrap() .to_rgba(); let image_dimensions = image.dimensions(); pr...
main
identifier_name
formidable-exemple.js
var formidable = require('formidable'), http = require('http'),
// parse a file upload var form = new formidable.IncomingForm(); form.parse(req, function(error, fields, files) { res.writeHead(200, { 'content-type': 'text/plain' }); res.write('received upload:\n\n'); }); return; } // show file upload form res.writeHead(200, { 'content-type': 't...
sys = require('sys'); http.createServer(function(req, res) { if(req.url == '/upload' && req.method.toLowerCase() == 'post') {
random_line_split
formidable-exemple.js
var formidable = require('formidable'), http = require('http'), sys = require('sys'); http.createServer(function(req, res) { if(req.url == '/upload' && req.method.toLowerCase() == 'post')
// show file upload form res.writeHead(200, { 'content-type': 'text/html' }); res.end('<form action="/upload" enctype="multiplart/form-data" ' + 'method="post' + '<input type="text" name="title"><br>' + '<input type="file" name="upload" multiple="multiple"><br>' + '<input...
{ // parse a file upload var form = new formidable.IncomingForm(); form.parse(req, function(error, fields, files) { res.writeHead(200, { 'content-type': 'text/plain' }); res.write('received upload:\n\n'); }); return; }
conditional_block
p027.rs
//! [Problem 27](https://projecteuler.net/problem=27) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(iter_cmp)] #[macro_use(problem)] extern crate common; extern crate prime; use prime::PrimeSet; // p(n) = n^2 + an ...
fn solve() -> String { compute(1000).to_string() } problem!("-59231", solve); #[cfg(test)] mod tests { use prime::PrimeSet; #[test] fn primes() { let ps = PrimeSet::new(); assert_eq!(39, super::get_limit_n(&ps, 1, 41)); assert_eq!(79, super::get_limit_n(&ps, -79, 1601)) ...
{ let ps = PrimeSet::new(); let (a, b, _len) = ps.iter() .take_while(|&p| p < limit) .filter_map(|p| { let b = p as i32; (-b .. 1000) .map(|a| (a, b, get_limit_n(&ps, a, b))) .max_by(|&(_a, _b, len)| len) }).max_by(|&(_a, _b, len)| ...
identifier_body
p027.rs
//! [Problem 27](https://projecteuler.net/problem=27) solver.
unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(iter_cmp)] #[macro_use(problem)] extern crate common; extern crate prime; use prime::PrimeSet; // p(n) = n^2 + an + b is prime for n = 0 .. N // p(0) = b => b must be prime // p(1) = 1 + a...
#![warn(bad_style,
random_line_split
p027.rs
//! [Problem 27](https://projecteuler.net/problem=27) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![feature(iter_cmp)] #[macro_use(problem)] extern crate common; extern crate prime; use prime::PrimeSet; // p(n) = n^2 + an ...
() -> String { compute(1000).to_string() } problem!("-59231", solve); #[cfg(test)] mod tests { use prime::PrimeSet; #[test] fn primes() { let ps = PrimeSet::new(); assert_eq!(39, super::get_limit_n(&ps, 1, 41)); assert_eq!(79, super::get_limit_n(&ps, -79, 1601)) } }
solve
identifier_name
Embed.ts
/// <reference path="../../../../lib2/types/angular.d.ts"/> import * as _ from "lodash"; import * as AdhConfig from "../Config/Config"; import * as AdhTopLevelState from "../TopLevelState/TopLevelState"; import * as AdhUtil from "../Util/Util"; var metaParams = [ "autoresize", "initialUrl", "locale", ...
} }); } } }; }; export var headerDirective = (adhEmbed : Service) => { return { restrict: "E", template: () => { return adhEmbed.getContextHeader(); }, scope: {} }; }; export var canonicalUrl = (adhConfig...
})); event.preventDefault(); } }); }
random_line_split
Embed.ts
/// <reference path="../../../../lib2/types/angular.d.ts"/> import * as _ from "lodash"; import * as AdhConfig from "../Config/Config"; import * as AdhTopLevelState from "../TopLevelState/TopLevelState"; import * as AdhUtil from "../Util/Util"; var metaParams = [ "autoresize", "initialUrl", "locale", ...
public route($location : angular.ILocationService) : AdhTopLevelState.IAreaInput { var widget : string = $location.path().split("/")[2]; var search = $location.search(); var directiveName = this.provider.normalizeDirective(widget); var contextName = this.provider.normalizeContext(...
{ var context = this.getContext(); var template = this.provider.contextHeaders[context]; return template || "<adh-default-header></adh-default-header>"; }
identifier_body
Embed.ts
/// <reference path="../../../../lib2/types/angular.d.ts"/> import * as _ from "lodash"; import * as AdhConfig from "../Config/Config"; import * as AdhTopLevelState from "../TopLevelState/TopLevelState"; import * as AdhUtil from "../Util/Util"; var metaParams = [ "autoresize", "initialUrl", "locale", ...
() : string { if (!this.isEmbedded() || this.widget === "plain") { return ""; } else { return this.widget; } } public getContextHeader() : string { var context = this.getContext(); var template = this.provider.contextHeaders[context]; ret...
getContext
identifier_name
Embed.ts
/// <reference path="../../../../lib2/types/angular.d.ts"/> import * as _ from "lodash"; import * as AdhConfig from "../Config/Config"; import * as AdhTopLevelState from "../TopLevelState/TopLevelState"; import * as AdhUtil from "../Util/Util"; var metaParams = [ "autoresize", "initialUrl", "locale", ...
return this; } public normalizeDirective(name : string) : string { return this.directiveAliases[name] || name; } public hasDirective(name : string) { return _.includes(this.directives, name); } public registerContext(name : string, aliases : string[] = []) : Provider...
{ this.directiveAliases[aliases[i]] = name; }
conditional_block
system_model.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. /* | Video | # of | Visible | Cycles/ | Visible Type | system | lines | lines | line | pixels/line ----...
pub fn c64_pal() -> SystemModel { SystemModel { color_ram: 1024, cpu_freq: 985_248, cycles_per_frame: 19656, frame_buffer_size: (504, 312), memory_size: 65536, refresh_rate: 50.125, sid_model: SidModel::Mos6581, ...
{ SystemModel { color_ram: 1024, cpu_freq: 1_022_727, cycles_per_frame: 17095, frame_buffer_size: (512, 263), memory_size: 65536, refresh_rate: 59.826, sid_model: SidModel::Mos6581, vic_model: VicModel::Mos6567, ...
identifier_body
system_model.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. /* | Video | # of | Visible | Cycles/ | Visible Type | system | lines | lines | line | pixels/line ----...
frame_buffer_size: (512, 263), memory_size: 65536, refresh_rate: 59.826, sid_model: SidModel::Mos6581, vic_model: VicModel::Mos6567, viewport_offset: (77, 16), viewport_size: (418, 235), } } pub fn c64_pal() -> SystemMo...
pub fn c64_ntsc() -> SystemModel { SystemModel { color_ram: 1024, cpu_freq: 1_022_727, cycles_per_frame: 17095,
random_line_split