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
ranks.tsx
/* tslint:disable:max-line-length */ import { KUNGFU_EXTERNAL, KUNGFU_INTERNAL } from "../data/kungfu/types"; import { VIRTUE_CHIVALROUS, VIRTUE_SELFISH } from "../data/virtues"; import { bonusChi, bonusDestiny } from "../perks/actions/bonuses"; import { discountKungfuFactory, discountSkillFactory, discountVirtu...
return ranks.find((dataRank: IDataRank) => dataRank.value === rank); }
} } export function getRank(rank: any) {
random_line_split
ranks.tsx
/* tslint:disable:max-line-length */ import { KUNGFU_EXTERNAL, KUNGFU_INTERNAL } from "../data/kungfu/types"; import { VIRTUE_CHIVALROUS, VIRTUE_SELFISH } from "../data/virtues"; import { bonusChi, bonusDestiny } from "../perks/actions/bonuses"; import { discountKungfuFactory, discountSkillFactory, discountVirtu...
() { const virtues: { name: string; type: VIRTUE_SELFISH | VIRTUE_CHIVALROUS; }[] = [ // TODO : handle virtues more clearly { name: "Honor", type: VIRTUE_CHIVALROUS }, { name: "Benevolence", type: VIRTUE_CHIVALROUS }, { name: "Righteousness", type: VIRTUE_CHIVALROUS }, { name: "Loyalty",...
_defaultVirtues
identifier_name
ranks.tsx
/* tslint:disable:max-line-length */ import { KUNGFU_EXTERNAL, KUNGFU_INTERNAL } from "../data/kungfu/types"; import { VIRTUE_CHIVALROUS, VIRTUE_SELFISH } from "../data/virtues"; import { bonusChi, bonusDestiny } from "../perks/actions/bonuses"; import { discountKungfuFactory, discountSkillFactory, discountVirtu...
{ return ranks.find((dataRank: IDataRank) => dataRank.value === rank); }
identifier_body
ranks.tsx
/* tslint:disable:max-line-length */ import { KUNGFU_EXTERNAL, KUNGFU_INTERNAL } from "../data/kungfu/types"; import { VIRTUE_CHIVALROUS, VIRTUE_SELFISH } from "../data/virtues"; import { bonusChi, bonusDestiny } from "../perks/actions/bonuses"; import { discountKungfuFactory, discountSkillFactory, discountVirtu...
} export function getRank(rank: any) { return ranks.find((dataRank: IDataRank) => dataRank.value === rank); }
{ throw new Error('Invalid rank "' + rank + '"'); }
conditional_block
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
(AutotoolsPackage): """GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating-point numbers.""" homepage = "https://gmplib.org" url = "https://ftp.gnu.org/gnu/gmp/gmp-6.1.2.tar.bz2" version('6.1.2', '8ddbb26dc3bd4e2302984debba14...
Gmp
identifier_name
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
args = ['--enable-cxx'] # This flag is necessary for the Intel build to pass `make check` if self.spec.compiler.name == 'intel': args.append('CXXFLAGS=-no-ftz') return args
identifier_body
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
return args
args.append('CXXFLAGS=-no-ftz')
conditional_block
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
# # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the...
# # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999.
random_line_split
rustbenchs.rs
/* * Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU Genera...
{ let mut tester = MyTester {}; run_suite!(tester, bboxlist::run); run_suite!(tester, bdlist::run); run_suite!(tester, bmgate::run); run_suite!(tester, bpipe::run); run_suite!(tester, bregfile::run); run_suite!(tester, bstream::run); run_suite!(tester, bsyscall::run); run_suite!(test...
identifier_body
rustbenchs.rs
/* * Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU Genera...
() -> i32 { let mut tester = MyTester {}; run_suite!(tester, bboxlist::run); run_suite!(tester, bdlist::run); run_suite!(tester, bmgate::run); run_suite!(tester, bpipe::run); run_suite!(tester, bregfile::run); run_suite!(tester, bstream::run); run_suite!(tester, bsyscall::run); run_s...
main
identifier_name
rustbenchs.rs
/* * Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU Genera...
println!("Done\n"); } fn run_test(&mut self, name: &str, f: &Fn()) { println!("-- Running benchmark {} ...", name); let free_mem = m3::heap::free_memory(); f(); assert_eq!(m3::heap::free_memory(), free_mem); println!("-- Done"); } } #[no_mangle] pub fn main(...
impl Tester for MyTester { fn run_suite(&mut self, name: &str, f: &Fn(&mut Tester)) { println!("Running benchmark suite {} ...", name); f(self);
random_line_split
box.js
var $ = function (selector) { return document.querySelector(selector); }; var $all = function (selector) { return document.querySelectorAll(selector); }; var colorScheme = [ '#6BED08', '#A0F261', '#86EF35', '#60DD00', '#4AAA00', '#F8FE09', '#FBFE66', '#F9FE39', '#F2F800', '#BABF00', '#06BEBE',...
(el, x, y, className) { className = className ? className : ''; var d = document.createElement("div"); d.className = "frame"; d.style.left = 50 * x + "%"; d.style.top = 50 * y + "%"; var box = document.createElement("div"); box.classList.add('box'); if (className) box.classList.add(clas...
makeBox
identifier_name
box.js
var $ = function (selector) { return document.querySelector(selector); }; var $all = function (selector) { return document.querySelectorAll(selector); }; var colorScheme = [ '#6BED08', '#A0F261', '#86EF35', '#60DD00', '#4AAA00', '#F8FE09', '#FBFE66', '#F9FE39', '#F2F800', '#BABF00', '#06BEBE',...
el.removeChild(el.childNodes[0]); } var level = 1; divide($("#screen"), false, level); document.onclick = function () { if (level > 9) { $all('.box').forEach(function (box) { box.onclick = function () { divide(this.parentNode); }; }); return; } leve...
{ return; }
conditional_block
box.js
var $ = function (selector) { return document.querySelector(selector); }; var $all = function (selector) { return document.querySelectorAll(selector); }; var colorScheme = [ '#6BED08', '#A0F261', '#86EF35', '#60DD00', '#4AAA00', '#F8FE09', '#FBFE66', '#F9FE39', '#F2F800', '#BABF00', '#06BEBE',...
} el.removeChild(el.childNodes[0]); } var level = 1; divide($("#screen"), false, level); document.onclick = function () { if (level > 9) { $all('.box').forEach(function (box) { box.onclick = function () { divide(this.parentNode); }; }); return; } ...
makeBox(el, 0, 1, 'diagonal'); makeBox(el, 1, 1); if (!remove) { return;
random_line_split
box.js
var $ = function (selector) { return document.querySelector(selector); }; var $all = function (selector) { return document.querySelectorAll(selector); }; var colorScheme = [ '#6BED08', '#A0F261', '#86EF35', '#60DD00', '#4AAA00', '#F8FE09', '#FBFE66', '#F9FE39', '#F2F800', '#BABF00', '#06BEBE',...
var level = 1; divide($("#screen"), false, level); document.onclick = function () { if (level > 9) { $all('.box').forEach(function (box) { box.onclick = function () { divide(this.parentNode); }; }); return; } level++; $all('.box.diagonal').forEach(fun...
{ remove = remove === void 0 ? true : !!remove; makeBox(el, 0, 0); makeBox(el, 1, 0, 'diagonal'); makeBox(el, 0, 1, 'diagonal'); makeBox(el, 1, 1); if (!remove) { return; } el.removeChild(el.childNodes[0]); }
identifier_body
dialog.component.tsx
/** * Copyright (C) 2017 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This pro...
} }; const handleResolve = (...args) => { handleHide(); setIsOpen(false); if (props.config.onConfirm) { handleCallback(props.config.onConfirm.bind(null, ...args)); } }; return ( <DialogBase {...DialogProps} ref={ref} open={isOpen} onClose={handleClose}> <DialogTitle disableTypography>{title}{...
{ handleCallback(props.config.onCancel.bind(null, ...args)); }
conditional_block
dialog.component.tsx
/** * Copyright (C) 2017 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This pro...
/>} <IconButton onClick={handleClose}><CloseIcon htmlColor={COLOR.WHITE} /></IconButton> </TopDialogActions> ); const renderActions = renderWhenTrue(() => ( <DialogActions> <Button onClick={handleClose} variant={props.config.buttonVariant || 'text'} color="secondary"> {props.config.clos...
{search && <SearchButton enabled={props.searchEnabled} onOpen={search.onOpen} onClose={search.onClose}
random_line_split
update-dbus-docs.py
remove_comments=False, strip_cdata=False, resolve_entities=False) def print_method(declarations, elem, *, prefix, file, is_signal=False): name = elem.get('name') klass = 'signal' if is_signal else 'method' declarations[klass]....
for print_boring in [False, True]: for iface in xml.findall('./interface'): print_interface(iface, prefix=' ', file=file, print_boring=print_boring, only_interface=only_interface, declarations=declarations) ...
interfaces = [] print(f'''node {destination} {{''', file=file)
random_line_split
update-dbus-docs.py
remove_comments=False, strip_cdata=False, resolve_entities=False) def print_method(declarations, elem, *, prefix, file, is_signal=False): name = elem.get('name') klass = 'signal' if is_signal else 'method' declarations[klass]....
else: variablelist.attrib['extra-ref'] = declaration prev_element.addnext(variablelist) prev_element.tail = the_tail prev_element = variablelist last_element = etree.Comment("End of Autogenerated section") prev_elemen...
variablelist.attrib['extra-ref'] = declaration + '()'
conditional_block
update-dbus-docs.py
remove_comments=False, strip_cdata=False, resolve_entities=False) def print_method(declarations, elem, *, prefix, file, is_signal=False): name = elem.get('name') klass = 'signal' if is_signal else 'method' declarations[klass]....
(type): if type == 's': return "'...'"; if type[0] == 'a': inner = value_ellipsis(type[1:]) return f"[{inner}{', ...' if inner != '...' else ''}]"; return '...' def print_property(declarations, elem, *, prefix, file): name = elem.get('name') type = elem.get('type') acces...
value_ellipsis
identifier_name
update-dbus-docs.py
remove_comments=False, strip_cdata=False, resolve_entities=False) def print_method(declarations, elem, *, prefix, file, is_signal=False): name = elem.get('name') klass = 'signal' if is_signal else 'method' declarations[klass]....
def check_documented(document, declarations, stats): missing = [] for klass, items in declarations.items(): stats['total'] += len(items) for item in items: if klass == 'method': elem = 'function' item_repr = f'{item}()' elif klass == 'si...
predicate = f".//{elem}" # [text() = 'foo'] doesn't seem supported :( for loc in document.findall(predicate): if loc.text == item_repr: return True return False
identifier_body
fix_ncbi.py
#!/usr/bin/env python import sys import logging
logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) def safe_qualifiers(quals): unsafe_quals = ("ID", "Parent", "Name") new_quals = {} for (key, value) in quals.items(): if key not in unsafe_quals: new_quals[key] = value return new_quals def fix_ncbi(gff3):...
import argparse from gff3 import feature_lambda, feature_test_type from CPT_GFFParser import gffParse, gffWrite
random_line_split
fix_ncbi.py
#!/usr/bin/env python import sys import logging import argparse from gff3 import feature_lambda, feature_test_type from CPT_GFFParser import gffParse, gffWrite logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) def safe_qualifiers(quals): unsafe_quals = ("ID", "Parent", "Name") new_qua...
if __name__ == "__main__": parser = argparse.ArgumentParser(description="correct their terrible GFF data") parser.add_argument("gff3", type=argparse.FileType("r"), help="GFF3 annotations") args = parser.parse_args() fix_ncbi(**vars(args))
for feature in feature_lambda( rec.features, feature_test_type, {"type": "gene"}, subfeatures=True ): CDSs = list( feature_lambda( feature.sub_features, feature_test_type, {"type": "CDS"}, sub...
conditional_block
fix_ncbi.py
#!/usr/bin/env python import sys import logging import argparse from gff3 import feature_lambda, feature_test_type from CPT_GFFParser import gffParse, gffWrite logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) def safe_qualifiers(quals):
def fix_ncbi(gff3): for rec in gffParse(gff3): for feature in feature_lambda( rec.features, feature_test_type, {"type": "gene"}, subfeatures=True ): CDSs = list( feature_lambda( feature.sub_features, feature_test_type...
unsafe_quals = ("ID", "Parent", "Name") new_quals = {} for (key, value) in quals.items(): if key not in unsafe_quals: new_quals[key] = value return new_quals
identifier_body
fix_ncbi.py
#!/usr/bin/env python import sys import logging import argparse from gff3 import feature_lambda, feature_test_type from CPT_GFFParser import gffParse, gffWrite logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) def safe_qualifiers(quals): unsafe_quals = ("ID", "Parent", "Name") new_qua...
(gff3): for rec in gffParse(gff3): for feature in feature_lambda( rec.features, feature_test_type, {"type": "gene"}, subfeatures=True ): CDSs = list( feature_lambda( feature.sub_features, feature_test_type, ...
fix_ncbi
identifier_name
__init__.py
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from . import LayerView, LayerViewProxy from PyQt5.QtQml import qmlRegisterType, qmlRegisterSingletonType from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def
(): return { "plugin": { "name": "Layer View", "author": "Ultimaker", "version": "1.0", "description": catalog.i18nc("Layer View plugin description", "Provides the Layer view."), "api": 2 }, "view": { "name": catalog.i18...
getMetaData
identifier_name
__init__.py
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from . import LayerView, LayerViewProxy from PyQt5.QtQml import qmlRegisterType, qmlRegisterSingletonType from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "plugin": { ...
return LayerViewProxy.LayerViewProxy() def register(app): layer_view = LayerView.LayerView() qmlRegisterSingletonType(LayerViewProxy.LayerViewProxy, "UM", 1, 0, "LayerView", layer_view.getProxy) return { "view": LayerView.LayerView() }
random_line_split
__init__.py
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from . import LayerView, LayerViewProxy from PyQt5.QtQml import qmlRegisterType, qmlRegisterSingletonType from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "plugin": { ...
layer_view = LayerView.LayerView() qmlRegisterSingletonType(LayerViewProxy.LayerViewProxy, "UM", 1, 0, "LayerView", layer_view.getProxy) return { "view": LayerView.LayerView() }
identifier_body
index.d.ts
import { Node, Store, Cache } from "gatsby" /** * @see https://www.gatsbyjs.org/packages/gatsby-source-filesystem/?=files#createfilepath */ export function createFilePath(args: CreateFilePathArgs): string /** * @see https://www.gatsbyjs.org/packages/gatsby-source-filesystem/?=files#createremotefilenode */ export ...
relativeDirectory: string relativePath: string sourceInstanceName: string // parsed path typings base: string dir: string ext: string name: string root: string // stats atime: Date atimeMs: number birthtime: Date birthtimeMs: number ctime: Date ctimeMs: number gid: number mode: num...
prettySize: string
random_line_split
translate.ts
import {NewSignal} from 'vega'; import {selector as parseSelector} from 'vega-event-selector'; import {SelectionComponent} from '.'; import {ScaleChannel, X, Y} from '../../channel'; import {UnitModel} from '../unit'; import {BRUSH as INTERVAL_BRUSH} from './interval'; import {SelectionProjection} from './project'; imp...
return signals; } }; export default translate; function onDelta( model: UnitModel, selCmpt: SelectionComponent, proj: SelectionProjection, size: 'width' | 'height', signals: NewSignal[] ) { const name = selCmpt.name; const anchor = name + ANCHOR; const delta = name + DELTA; const channel = p...
{ onDelta(model, selCmpt, y, 'height', signals); }
conditional_block
translate.ts
import {NewSignal} from 'vega'; import {selector as parseSelector} from 'vega-event-selector'; import {SelectionComponent} from '.'; import {ScaleChannel, X, Y} from '../../channel'; import {UnitModel} from '../unit'; import {BRUSH as INTERVAL_BRUSH} from './interval'; import {SelectionProjection} from './project'; imp...
( model: UnitModel, selCmpt: SelectionComponent, proj: SelectionProjection, size: 'width' | 'height', signals: NewSignal[] ) { const name = selCmpt.name; const anchor = name + ANCHOR; const delta = name + DELTA; const channel = proj.channel as ScaleChannel; const hasScales = scalesCompiler.defined(s...
onDelta
identifier_name
translate.ts
import {NewSignal} from 'vega'; import {selector as parseSelector} from 'vega-event-selector'; import {SelectionComponent} from '.'; import {ScaleChannel, X, Y} from '../../channel'; import {UnitModel} from '../unit'; import {BRUSH as INTERVAL_BRUSH} from './interval'; import {SelectionProjection} from './project'; imp...
: scaleType === 'pow' ? 'panPow' : 'panLinear'; const arg = !hasScales ? '' : scaleType === 'pow' ? `, ${scaleCmpt.get('exponent') ?? 1}` : scaleType === 'symlog' ? `, ${scaleCmpt.get('constant') ?? 1}` : ''; const update = `${panFn}(${extent}, ${offset}${arg})`; signal.on.pus...
{ const name = selCmpt.name; const anchor = name + ANCHOR; const delta = name + DELTA; const channel = proj.channel as ScaleChannel; const hasScales = scalesCompiler.defined(selCmpt); const signal = signals.filter(s => s.name === proj.signals[hasScales ? 'data' : 'visual'])[0]; const sizeSg = model.getSiz...
identifier_body
translate.ts
import {NewSignal} from 'vega'; import {selector as parseSelector} from 'vega-event-selector'; import {SelectionComponent} from '.'; import {ScaleChannel, X, Y} from '../../channel'; import {UnitModel} from '../unit'; import {BRUSH as INTERVAL_BRUSH} from './interval'; import {SelectionProjection} from './project'; imp...
if (!hasScales) { events = events.map(e => ((e.between[0].markname = name + INTERVAL_BRUSH), e)); } signals.push( { name: anchor, value: {}, on: [ { events: events.map(e => e.between[0]), update: '{x: x(unit), y: y(unit)' ...
const {x, y} = selCmpt.project.hasChannel; let events = parseSelector(selCmpt.translate, 'scope');
random_line_split
accounts.rs
#![allow(unused_variables)] use domain::Money; use rocket_contrib::{JSON, UUID}; use uuid::Uuid; #[derive(Debug, Copy, Clone, Deserialize)] pub struct OpenAccountData { pub initial_balance: Money, } #[derive(Debug, Clone, Deserialize)] pub struct DepositMoneyData { pub transfer_id: Uuid, pub amount: Mone...
pub fn close_account(id: UUID) { unimplemented!() }
random_line_split
accounts.rs
#![allow(unused_variables)] use domain::Money; use rocket_contrib::{JSON, UUID}; use uuid::Uuid; #[derive(Debug, Copy, Clone, Deserialize)] pub struct OpenAccountData { pub initial_balance: Money, } #[derive(Debug, Clone, Deserialize)] pub struct DepositMoneyData { pub transfer_id: Uuid, pub amount: Mone...
{ pub transfer_id: Uuid, pub amount: Money, } #[post("/accounts", data = "<data>")] pub fn open_account(data: JSON<OpenAccountData>) { unimplemented!() } #[post("/accounts/<id>/deposit_money", data = "<data>")] pub fn deposit_money(id: UUID, data: JSON<DepositMoneyData>) { unimplemented!() } #[post(...
WithdrawMoneyData
identifier_name
accounts.rs
#![allow(unused_variables)] use domain::Money; use rocket_contrib::{JSON, UUID}; use uuid::Uuid; #[derive(Debug, Copy, Clone, Deserialize)] pub struct OpenAccountData { pub initial_balance: Money, } #[derive(Debug, Clone, Deserialize)] pub struct DepositMoneyData { pub transfer_id: Uuid, pub amount: Mone...
#[post("/accounts/<id>/close_account")] pub fn close_account(id: UUID) { unimplemented!() }
{ unimplemented!() }
identifier_body
comment_controller.js
var models=require('../models/models.js'); // Autoload :id de comentarios exports.load=function (req,res,next,commentId) { models.Comment.find({ where:{ id:Number(commentId) } }).then(function (comment) { if(comment){ req.comment=comment; next(); }else{ next(new Error('No existe commentId=' +comme...
next(error); }); };
random_line_split
comment_controller.js
var models=require('../models/models.js'); // Autoload :id de comentarios exports.load=function (req,res,next,commentId) { models.Comment.find({ where:{ id:Number(commentId) } }).then(function (comment) { if(comment){ req.comment=comment; next(); }else{ next(new Error('No existe commentId=' +comme...
else{ comment //save :guarda en DB campo texto .save() .then(function () { res.redirect('/quizes/'+req.params.quizId); }); } } ).catch(function (error) { next(error); }); }; //GET /quizes/:quizId/comments/:commentId/publish exports.publish=function (req,res) { req.comment.publicado=true; r...
{ res.render('comments/new.ejs', {comment:comment,quizid:req.params.quizId,errors:err.errors}); }
conditional_block
views.py
import markdown from django.shortcuts import render_to_response, get_object_or_404, HttpResponse, HttpResponseRedirect, Http404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.contrib import messages from django.views.decorators.csrf import csrf_exempt ...
@login_required def profile(request): ''' Displays page where user can update their profile. @param request: Django request object. @return: Rendered profile.html. ''' if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): data = form.cleaned_data print data #Update...
if not request.POST: raise Http404() try: data = request.POST['data'] except KeyError: raise Http404() data_formatted = markdown.markdown(data) return render_to_response('core/markdown_preview.html', {'data': data_formatted}, \ context_instance = RequestContext(request))
identifier_body
views.py
import markdown from django.shortcuts import render_to_response, get_object_or_404, HttpResponse, HttpResponseRedirect, Http404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.contrib import messages from django.views.decorators.csrf import csrf_exempt ...
try: data = request.POST['data'] except KeyError: raise Http404() data_formatted = markdown.markdown(data) return render_to_response('core/markdown_preview.html', {'data': data_formatted}, \ context_instance = RequestContext(request)) @login_required def profile(request): ''' Displays pa...
raise Http404()
conditional_block
views.py
import markdown from django.shortcuts import render_to_response, get_object_or_404, HttpResponse, HttpResponseRedirect, Http404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.contrib import messages from django.views.decorators.csrf import csrf_exempt ...
comments = Comment.objects.filter(is_public = True).order_by('-submit_date')[:count] return comments
def get_latest_comments(count = 4): """ Returns the latest comments."""
random_line_split
views.py
import markdown from django.shortcuts import render_to_response, get_object_or_404, HttpResponse, HttpResponseRedirect, Http404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.contrib import messages from django.views.decorators.csrf import csrf_exempt ...
(request): ''' Displays page where user can update their profile. @param request: Django request object. @return: Rendered profile.html. ''' if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): data = form.cleaned_data print data #Update user with form data request....
profile
identifier_name
i18n.py
setting the chosen language in the session or cookie. The url and the language code need to be specified in the request parameters. Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. If called as a GET request, it will redirect to the pa...
if not next: next = '/' response = http.HttpResponseRedirect(next) if request.method == 'POST': lang_code = request.POST.get('language', None) if lang_code and check_for_language(lang_code): if hasattr(request, 'session'): request.session['django_language...
next = request.META.get('HTTP_REFERER', None)
conditional_block
i18n.py
setting the chosen language in the session or cookie. The url and the language code need to be specified in the request parameters. Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. If called as a GET request, it will redirect to the pa...
LibFormatHead = """ /* formatting library */ var formats = new Array(); """ LibFormatFoot = """ function get_format(format_type) { var value = formats[format_type]; if (typeof(value) == 'undefined') { return format_type; } else { return value; } } """ SimplePlural = """ function plurali...
value = ngettext(singular, plural, count); } return value; } """
random_line_split
i18n.py
request.session['django_language'] = lang_code else: response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code) return response def get_formats(): """ Returns all formats strings required for i18n to work """ FORMAT_SETTINGS = ( 'DATE_FORMAT',...
""" Redirect to a given url while setting the chosen language in the session or cookie. The url and the language code need to be specified in the request parameters. Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. If called as a GET re...
identifier_body
i18n.py
setting the chosen language in the session or cookie. The url and the language code need to be specified in the request parameters. Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. If called as a GET request, it will redirect to the pa...
(request, domain=None, packages=None): """ Returns "identity" versions of the JavaScript i18n functions -- i.e., versions that don't actually do anything. """ src = [NullSource, InterPolate, LibFormatHead, get_formats(), LibFormatFoot] return http.HttpResponse(''.join(src), 'text/javascript') d...
null_javascript_catalog
identifier_name
router_spec.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {verifyNoBrowserErrors} from 'e2e_util/e2e_util'; describe('WebWorker Router', () => { beforeEach(() => { ...
(selector: string): void { browser.wait(protractor.until.elementLocated(by.css(selector)), 15000); } function waitForElementText(contentSelector: string, expected: string): void { browser.wait(() => { let deferred = protractor.promise.defer(); var elem = element(by.css(contentSelector)); ...
waitForElement
identifier_name
router_spec.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {verifyNoBrowserErrors} from 'e2e_util/e2e_util'; describe('WebWorker Router', () => { beforeEach(() => { ...
function waitForElement(selector: string): void { browser.wait(protractor.until.elementLocated(by.css(selector)), 15000); } function waitForElementText(contentSelector: string, expected: string): void { browser.wait(() => { let deferred = protractor.promise.defer(); var elem = element(by.css...
random_line_split
router_spec.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {verifyNoBrowserErrors} from 'e2e_util/e2e_util'; describe('WebWorker Router', () => { beforeEach(() => { ...
function waitForUrl(regex: any /** TODO #9100 */): void { browser.wait(() => { let deferred = protractor.promise.defer(); browser.getCurrentUrl().then( (url) => { return deferred.fulfill(url.match(regex) !== null); }); return deferred.promise; }, 5000); } });
{ browser.wait(() => { let deferred = protractor.promise.defer(); var elem = element(by.css(contentSelector)); elem.getText().then((text) => { return deferred.fulfill(text === expected); }); return deferred.promise; }, 5000); }
identifier_body
vselb.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 OpenStack 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/...
(self, ini_path): pool_vseid = self.conf.pool_vseid vip_vseid = self.conf.vip_vseid return (pool_vseid, vip_vseid) def extract_monitorids(self, monitors): monitor_ids = [] for monitor in monitors: monitor_ids.append(monitor['id']) return monitor_ids ...
ini2vseid
identifier_name
vselb.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 OpenStack 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/...
self.vselbapi.get_config()
identifier_body
vselb.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 OpenStack 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/...
def get_stats(pool_id, ini_path, conf_path): # self.vselbapi.get_stats() self.vselbapi.get_config()
self.vselbapi.delete_monitors(monitor_vseids, pool_vseid)
conditional_block
vselb.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 OpenStack 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/...
count = 0 while count < self._max_monitors: monitorMap = "monitorMap_%d" % count OPTS.append(cfg.ListOpt(monitorMap)) count = count + 1 self.conf.register_opts(OPTS) def ini_update(self, ini_path): argv = ["--config-file", ini_path] self....
self._max_monitors = 255
random_line_split
lib.rs
pub fn primefactors(n: isize) -> Vec<isize> { let mut number = n; let mut factors = Vec::new(); if number % 2 == 0 { factors.push(2); number = number / 2; } let mut factor = 3; let upperlimit = (n as f64).sqrt() as isize + 2; while factor <= upperlimit { if number % ...
factors } fn find_root(a: f64, x: f64, epsilon: f64) -> f64 { let nextx = (a/x + x) / 2.0; if (x-nextx).abs() < epsilon*x { nextx } else { find_root(a, nextx, epsilon) } } pub fn sqrt(n: f64) -> f64 { find_root(n, 2.0, 1.0e-40_f64) } #[test] fn test_sqrt() { assert!(s...
} factor += 2; }
random_line_split
lib.rs
pub fn primefactors(n: isize) -> Vec<isize> { let mut number = n; let mut factors = Vec::new(); if number % 2 == 0 { factors.push(2); number = number / 2; } let mut factor = 3; let upperlimit = (n as f64).sqrt() as isize + 2; while factor <= upperlimit { if number % ...
(n: f64) -> f64 { find_root(n, 2.0, 1.0e-40_f64) } #[test] fn test_sqrt() { assert!(sqrt(4.0) == 2.0); } #[test] fn test_primefactors() { assert!(primefactors(10) == [2, 5]); assert!(primefactors(13195) == [5,7,13,29]); }
sqrt
identifier_name
lib.rs
pub fn primefactors(n: isize) -> Vec<isize> { let mut number = n; let mut factors = Vec::new(); if number % 2 == 0 { factors.push(2); number = number / 2; } let mut factor = 3; let upperlimit = (n as f64).sqrt() as isize + 2; while factor <= upperlimit { if number % ...
{ assert!(primefactors(10) == [2, 5]); assert!(primefactors(13195) == [5,7,13,29]); }
identifier_body
lib.rs
pub fn primefactors(n: isize) -> Vec<isize> { let mut number = n; let mut factors = Vec::new(); if number % 2 == 0 { factors.push(2); number = number / 2; } let mut factor = 3; let upperlimit = (n as f64).sqrt() as isize + 2; while factor <= upperlimit { if number % ...
else { find_root(a, nextx, epsilon) } } pub fn sqrt(n: f64) -> f64 { find_root(n, 2.0, 1.0e-40_f64) } #[test] fn test_sqrt() { assert!(sqrt(4.0) == 2.0); } #[test] fn test_primefactors() { assert!(primefactors(10) == [2, 5]); assert!(primefactors(13195) == [5,7,13,29]); }
{ nextx }
conditional_block
dropck_no_diverge_on_nonregular_3.rs
// Issue 22443: Reject code using non-regular types that would // otherwise cause dropck to loop infinitely. // // This version is just checking that we still sanely handle a trivial // wrapper around the non-regular type. (It also demonstrates how the // error messages will report different types depending on which ty...
<T:'static> { Simple, Other(FingerTree<T>), } fn main() { let w = //~ ERROR overflow while adding drop-check rules for Option Some(Wrapper::Simple::<u32>); //~^ ERROR overflow while adding drop-check rules for Option //~| ERROR overflow while adding drop-check rules for Wrapper }
Wrapper
identifier_name
dropck_no_diverge_on_nonregular_3.rs
// Issue 22443: Reject code using non-regular types that would // otherwise cause dropck to loop infinitely. // // This version is just checking that we still sanely handle a trivial // wrapper around the non-regular type. (It also demonstrates how the // error messages will report different types depending on which ty...
use std::marker::PhantomData; struct Digit<T> { elem: T } struct Node<T:'static> { m: PhantomData<&'static T> } enum FingerTree<T:'static> { Single(T), // According to the bug report, Digit before Box would infinite loop. Deep( Digit<T>, Box<FingerTree<Node<T>>>, ) } enum Wra...
random_line_split
pipeline_fragment.py
the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file exc...
v = UserTransformVisitor() self._runner_pipeline.visit(v) return label_to_user_transform def _build_correlation_between_pipelines( self, runner_pcoll_to_id, id_to_target_pcoll, label_to_user_transform): runner_pcolls_to_user_pcolls = {} runner_transforms_to_user_transforms = {} class...
def enter_composite_transform(self, transform_node): self.visit_transform(transform_node) def visit_transform(self, transform_node): if transform_node is not None: label_to_user_transform[transform_node.full_label] = transform_node
identifier_body
pipeline_fragment.py
Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except ...
# No modification to self._user_pipeline is allowed. self._user_pipeline = pcolls[0].pipeline # These are user PCollections. Do not use them to deduce anything that # will be executed by any runner. Instead, use # `self._runner_pcolls_to_user_pcolls.keys()` to get copied PCollections. self._pco...
assert isinstance(pcoll, beam.pvalue.PCollection), ( '{} is not an apache_beam.pvalue.PCollection.'.format(pcoll))
conditional_block
pipeline_fragment.py
the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file exc...
updated_all_inputs.update(side_input_pvalues) # Go to its parent AppliedPTransform. producer = producer.parent return necessary_transforms, all_inputs def _prune_runner_pipeline_to_fragment( self, runner_pipeline, necessary_transforms): class PruneVisitor(PipelineVisitor):...
# Record all necessary input and side input PCollections. updated_all_inputs.update(producer.inputs) # pylint: disable=map-builtin-not-iterating side_input_pvalues = set( map(lambda side_input: side_input.pvalue, producer.side_inputs))
random_line_split
pipeline_fragment.py
Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except ...
(self, transform_node): self.visit_transform(transform_node) def visit_transform(self, transform_node): if transform_node is not None: label_to_user_transform[transform_node.full_label] = transform_node v = UserTransformVisitor() self._runner_pipeline.visit(v) return label_...
enter_composite_transform
identifier_name
htlc.py
import click from bitshares.amount import Amount from .decorators import online, unlock from .main import main, config from .ui import print_tx @main.group() def htlc(): pass @htlc.command() @click.argument("to")
help="Hash algorithm" ) @click.option( "--hash", prompt="Hash (hex string)", hide_input=False, confirmation_prompt=True, help="Hash value as string of hex digits" ) @click.option( "--expiration", default=60 * 60, prompt="Expiration (seconds)", help="Duration of HTLC in seconds" ) @click.option( ...
@click.argument("amount") @click.argument("symbol") @click.option( "--type", type=click.Choice(["ripemd160", "sha1", "sha256", "hash160"]), default="sha256", prompt="Hash algorithm", show_default=True,
random_line_split
htlc.py
import click from bitshares.amount import Amount from .decorators import online, unlock from .main import main, config from .ui import print_tx @main.group() def htlc(): pass @htlc.command() @click.argument("to") @click.argument("amount") @click.argument("symbol") @click.option( "--type", type=click.Choice(...
(ctx, to, amount, symbol, type, secret, expiration, length, account): """Create an HTLC contract from a secret preimage If you are the party choosing the preimage, this version of htlc_create will compute the hash for you from the supplied preimage, and create the HTLC with the r...
create_from_secret
identifier_name
htlc.py
import click from bitshares.amount import Amount from .decorators import online, unlock from .main import main, config from .ui import print_tx @main.group() def htlc():
@htlc.command() @click.argument("to") @click.argument("amount") @click.argument("symbol") @click.option( "--type", type=click.Choice(["ripemd160", "sha1", "sha256", "hash160"]), default="sha256", prompt="Hash algorithm", show_default=True, help="Hash algorithm" ) @click.option( "--hash", prompt="Hash...
pass
identifier_body
htlc.py
import click from bitshares.amount import Amount from .decorators import online, unlock from .main import main, config from .ui import print_tx @main.group() def htlc(): pass @htlc.command() @click.argument("to") @click.argument("amount") @click.argument("symbol") @click.option( "--type", type=click.Choice(...
ctx.blockchain.blocking = True tx = ctx.blockchain.htlc_create( Amount(amount, symbol), to, preimage=secret, preimage_length=length, hash_type=type, expiration=expiration, account=account, ) tx.pop("trx", None) print_tx(tx) results = tx.g...
raise ValueError("Length must be zero or agree with actual preimage length")
conditional_block
inner_orientation.py
import tkinter.filedialog as tkFileDialog import numpy as np from numpy import sin,cos import os def InnerOrientation(mat1,mat2): """ mat1 为像素坐标,4*2,mat2为理论坐标4*2, h0,h1,h2,k0,k1,k2,这六个参数由下列矩阵定义: [x]=[h0]+[h1 h2] [i] [y]=[k0]+[k1 k2] [j] 返回6个定向参数的齐次矩阵,x方向单位权方差,y方向单位权方差 [h1 h2 h0] [k1 k2 ...
itle=u"选择文件",filetypes=[("kb file", "*.kb"), ("all", "*.*")],initialdir=r"D:\学习\摄影测量\摄影测量实验数据-后方交会、前方交会") f=open(fname,mode='r') lines=f.readlines() f.close() mat=[] for line in lines: t=line.split() mat.append([float(t[0]),float(t[1])]) #initialdir=(os.path.expanduser(default_di...
filename(t
identifier_name
inner_orientation.py
import tkinter.filedialog as tkFileDialog import numpy as np from numpy import sin,cos import os def InnerOrientation(mat1,mat2): """ mat1 为像素坐标,4*2,mat2为理论坐标4*2, h0,h1,h2,k0,k1,k2,这六个参数由下列矩阵定义: [x]=[h0]+[h1 h2] [i] [y]=[k0]+[k1 k2] [j] 返回6个定向参数的齐次矩阵,x方向单位权方差,y方向单位权方差 [h1 h2 h0] [k1 k2 ...
# phi,omega,kappa=0,0,0 # R=np.zeros((3,3)) # R[0,0]=cos(phi)*cos(kappa)-sin(phi)*sin(omega)*sin(kappa) # R[0,1]=-cos(phi)*sin(kappa)-sin(phi)*sin(omega)*cos(kappa) # R[0,2]=-sin(phi)*cos(omega) # R[1,0]=cos(omega)*sin(kappa) # R[1,1]=cos(omega)*cos(kappa) # R[1,2]=-sin(omega) # R[2,...
random_line_split
inner_orientation.py
import tkinter.filedialog as tkFileDialog import numpy as np from numpy import sin,cos import os def InnerOrientation(mat1,mat2):
N=np.linalg.inv(x.T @ x) beta=N @ x.T @ y # print(beta) r=(np.size(y)-6) e=y-x@beta ex=e[0::2] ey=e[1::2] sigmax=(np.linalg.norm(ex)/r) sigmay=(np.linalg.norm(ey)/r) # print(sigmax) # print(sigmay) return(np.matrix([[beta[1,0],beta[2,0],beta[0,0]],[beta[4,0],beta[5,0],bet...
""" mat1 为像素坐标,4*2,mat2为理论坐标4*2, h0,h1,h2,k0,k1,k2,这六个参数由下列矩阵定义: [x]=[h0]+[h1 h2] [i] [y]=[k0]+[k1 k2] [j] 返回6个定向参数的齐次矩阵,x方向单位权方差,y方向单位权方差 [h1 h2 h0] [k1 k2 k0] [0 0 1 ] """ # mat1=np.matrix(mat1) # mat2=np.matrix(mat2) y=mat2.ravel() y=y.T xlist=[] for i in...
identifier_body
inner_orientation.py
import tkinter.filedialog as tkFileDialog import numpy as np from numpy import sin,cos import os def InnerOrientation(mat1,mat2): """ mat1 为像素坐标,4*2,mat2为理论坐标4*2, h0,h1,h2,k0,k1,k2,这六个参数由下列矩阵定义: [x]=[h0]+[h1 h2] [i] [y]=[k0]+[k1 k2] [j] 返回6个定向参数的齐次矩阵,x方向单位权方差,y方向单位权方差 [h1 h2 h0] [k1 k2 ...
),np.matrix(mat2)) print(mat,sigmax2,sigmay2) # def transform(mat,coormat): # """ # mat:齐次矩阵,由InnerOrientation获得 # coormat:齐次坐标:即每列第三个元素为1,每个坐标均为列向量。列数不限。 # 返回:转换后的坐标 # """ # return mat@coormat # def openaofile(): # fname = tkFileDialog.askopenfilename(title=u"选择文件",filetypes=[("ao.txt ...
::2] mat,sigmax2,sigmay2=InnerOrientation(np.matrix(mat1
conditional_block
test.py
#!/usr/bin/python import pypm, sys, time DEV_NAME = 'nanoPAD2 MIDI 1' OUT_NAME = 'fs' #OUT_NAME = 'MIDI IN' #OUT_NAME = 'Synth input port (20116:0)' FIRST_NOTE = 24 + 4 # E, not C SECOND_NOTE = FIRST_NOTE + 5 PADS1 = range(51, 35, -2) PADS2 = range(50, 34, -2) shorten_bools = lambda bool_list: ''.join(('0' if b else...
def noteoff(chan, note): midi_out.Write([[[0x80 + chan, note, 0], pypm.Time()]]) def press(chan, base_note, vel): noteon(chan, base_note, vel) noteon(chan, base_note - 7, vel / 3) noteon(chan, base_note + 7, vel / 4) noteon(chan, base_note + 12, vel / 5) def release(chan, base_note): noteoff...
midi_out.Write([[[0x90 + chan, note, vel], pypm.Time()]])
identifier_body
test.py
#!/usr/bin/python import pypm, sys, time DEV_NAME = 'nanoPAD2 MIDI 1' OUT_NAME = 'fs' #OUT_NAME = 'MIDI IN' #OUT_NAME = 'Synth input port (20116:0)' FIRST_NOTE = 24 + 4 # E, not C SECOND_NOTE = FIRST_NOTE + 5 PADS1 = range(51, 35, -2) PADS2 = range(50, 34, -2) shorten_bools = lambda bool_list: ''.join(('0' if b else...
if not pressed: release(1, SECOND_NOTE) continue if b in PADS1: pads1_pressed[PADS1.index(b)] = False if b in PADS2: pads2_pressed[PADS2.index(b)] = False #else: # continue note1 = max([i if p else 0 for i, p in zip(range(1, 8+2-1), pads1_pressed)])...
if b == PADS2[-1]: # noteoff for the second pad row
random_line_split
test.py
#!/usr/bin/python import pypm, sys, time DEV_NAME = 'nanoPAD2 MIDI 1' OUT_NAME = 'fs' #OUT_NAME = 'MIDI IN' #OUT_NAME = 'Synth input port (20116:0)' FIRST_NOTE = 24 + 4 # E, not C SECOND_NOTE = FIRST_NOTE + 5 PADS1 = range(51, 35, -2) PADS2 = range(50, 34, -2) shorten_bools = lambda bool_list: ''.join(('0' if b else...
(chan, note, vel): midi_out.Write([[[0x90 + chan, note, vel], pypm.Time()]]) def noteoff(chan, note): midi_out.Write([[[0x80 + chan, note, 0], pypm.Time()]]) def press(chan, base_note, vel): noteon(chan, base_note, vel) noteon(chan, base_note - 7, vel / 3) noteon(chan, base_note + 7, vel / 4) ...
noteon
identifier_name
test.py
#!/usr/bin/python import pypm, sys, time DEV_NAME = 'nanoPAD2 MIDI 1' OUT_NAME = 'fs' #OUT_NAME = 'MIDI IN' #OUT_NAME = 'Synth input port (20116:0)' FIRST_NOTE = 24 + 4 # E, not C SECOND_NOTE = FIRST_NOTE + 5 PADS1 = range(51, 35, -2) PADS2 = range(50, 34, -2) shorten_bools = lambda bool_list: ''.join(('0' if b else...
elif a == 128: if b == PADS1[-1]: # noteoff for the first pad row if not pressed: release(0, FIRST_NOTE) continue if b == PADS2[-1]: # noteoff for the second pad row if not pressed: release(1, SECOND_NOTE) ...
pads2_pressed[PADS2.index(b)] = True
conditional_block
main.rs
extern crate clap; extern crate rusty_post_lib; use clap::App; use clap::Arg; use rusty_post_lib::request::request::{Request, RequestConfig, HttpMethod}; fn
() { let matches = App::new("rusty-post") .version("0.1.0") .about("Make HTTP requests") .author("Jonathan Rothberg") .arg(Arg::with_name("request") .short("X") .long("request") .default_value("GET") .takes_value(...
main
identifier_name
main.rs
extern crate clap; extern crate rusty_post_lib; use clap::App; use clap::Arg; use rusty_post_lib::request::request::{Request, RequestConfig, HttpMethod}; fn main() { let matches = App::new("rusty-post") .version("0.1.0") .about("Make HTTP requests") .author("Jonathan Rothberg") ...
println!("Headers: {:?}", headers); let config = RequestConfig::new(method, &headers, data); let request = Request::new_with_config(u.into(), &config); let resp = request.request(); println!("{}", resp); }, None => {} } println!("Hello...
Some(m) if m == "" || m == "GET" || m == "get" || m == "Get" => HttpMethod::Get, Some(m) if m == "POST" || m == "post" || m == "Post" => HttpMethod::Post, _ => HttpMethod::Get };
random_line_split
main.rs
extern crate clap; extern crate rusty_post_lib; use clap::App; use clap::Arg; use rusty_post_lib::request::request::{Request, RequestConfig, HttpMethod}; fn main() { let matches = App::new("rusty-post") .version("0.1.0") .about("Make HTTP requests") .author("Jonathan Rothberg") ...
println!("Headers: {:?}", headers); let config = RequestConfig::new(method, &headers, data); let request = Request::new_with_config(u.into(), &config); let resp = request.request(); println!("{}", resp); } , None => {} } println!("Hell...
{ let headers = match matches.values_of("H") { Some(h) => { h.collect() }, None => Vec::new() }; let data = match matches.value_of("data") { Some(d) => { d }, ...
conditional_block
main.rs
extern crate clap; extern crate rusty_post_lib; use clap::App; use clap::Arg; use rusty_post_lib::request::request::{Request, RequestConfig, HttpMethod}; fn main()
.arg(Arg::with_name("data") .short("d") .long("data") .takes_value(true) .default_value("") ).get_matches(); match matches.value_of("url") { Some(u) => { let headers = match matches.values_of("H") { Some(h) ...
{ let matches = App::new("rusty-post") .version("0.1.0") .about("Make HTTP requests") .author("Jonathan Rothberg") .arg(Arg::with_name("request") .short("X") .long("request") .default_value("GET") .takes_value(tru...
identifier_body
selector.js
jui.define("chart.brush.map.selector", [ "util.base" ], function(_) { /** * @class chart.brush.over * @extends chart.brush.core */ var MapSelectorBrush = function(chart, axis, brush) { var g = null, activePath = null; this.drawBefore = function() { g = chart.svg.group(); } this.dra...
return g; } } MapSelectorBrush.setup = function() { return { active: [], activeEvent: null } } return MapSelectorBrush; }, "chart.brush.map.core");
{ activePath = []; axis.map.each(function(i, obj) { if(_.inArray(axis.getValue(obj.data, "id"), brush.active) != -1) { activePath.push(obj.path); obj.path.css({ fill: chart.theme("mapSelectorActiveColor") }); } }); }
conditional_block
selector.js
jui.define("chart.brush.map.selector", [ "util.base" ], function(_) { /** * @class chart.brush.over * @extends chart.brush.core */
var MapSelectorBrush = function(chart, axis, brush) { var g = null, activePath = null; this.drawBefore = function() { g = chart.svg.group(); } this.draw = function() { var originFill = null; this.on("map.mouseover", function(obj, e) { if(activePath == obj.path) return; originFill = obj....
random_line_split
treemap.renderer.google.ts
import { ElementRef } from '@angular/core'; import { GoogleCharts } from 'google-charts'; import { TreemapRenderer } from './treemap.renderer'; import { TreemapOptions } from './treemap.data'; import { TacticsTooltipService } from '../tactics-pane/tactics-tooltip/tactics-tooltip.service'; /** * Google Charts implem...
}); GoogleCharts.api.visualization.events.addListener(this.chart, 'onmouseout', (event) => { window.clearTimeout(this.tooltipDelay); if (this.selected !== null) { eventHandler.onHover({ ...
{ window.clearTimeout(this.tooltipDelay); this.tooltipDelay = window.setTimeout(() => { let index: string = this.table.getValue(event.row, 0); const selected = this.data.filter(row => row[0] === index...
conditional_block
treemap.renderer.google.ts
import { ElementRef } from '@angular/core'; import { GoogleCharts } from 'google-charts'; import { TreemapRenderer } from './treemap.renderer'; import { TreemapOptions } from './treemap.data'; import { TacticsTooltipService } from '../tactics-pane/tactics-tooltip/tactics-tooltip.service'; /** * Google Charts implem...
source: {target: this.view.nativeElement} }); } }); } }, 'treemap'); } /** * @description draws the treemap onto the current viewport */ public redraw() { if (this.c...
random_line_split
treemap.renderer.google.ts
import { ElementRef } from '@angular/core'; import { GoogleCharts } from 'google-charts'; import { TreemapRenderer } from './treemap.renderer'; import { TreemapOptions } from './treemap.data'; import { TacticsTooltipService } from '../tactics-pane/tactics-tooltip/tactics-tooltip.service'; /** * Google Charts implem...
implements TreemapRenderer { private data: Array<any>; private options: TreemapOptions; private view: ElementRef; private table: any; private chart: any; private selected: any[]; private tooltipDelay: number; /** * @description initializes Google's api to draw the map ...
GoogleTreemapRenderer
identifier_name
treemap.renderer.google.ts
import { ElementRef } from '@angular/core'; import { GoogleCharts } from 'google-charts'; import { TreemapRenderer } from './treemap.renderer'; import { TreemapOptions } from './treemap.data'; import { TacticsTooltipService } from '../tactics-pane/tactics-tooltip/tactics-tooltip.service'; /** * Google Charts implem...
} }, 500); } }); GoogleCharts.api.visualization.events.addListener(this.chart, 'onmouseout', (event) => { window.clearTimeout(this.tooltipDelay); ...
{ this.view = treeMapView; GoogleCharts.load(() => { this.table = GoogleCharts.api.visualization.arrayToDataTable(this.data); this.chart = new GoogleCharts.api.visualization.TreeMap(this.view.nativeElement); this.redraw(); if (eventHandler && eventHandler...
identifier_body
ai.rs
use ball::Ball; use player::Player; use settings; pub struct AI { sleep_time: f64, awake_time: f64, } impl AI { pub fn new() -> AI { AI { sleep_time: 0.0, awake_time: settings::AI_AWAKE_TIME, } } pub fn update(&mut self, dt: f64, player: &mut Player, ball:...
} } }
{ self.awake_time = settings::AI_AWAKE_TIME; self.sleep_time = settings::AI_SLEEP_TIME; }
conditional_block
ai.rs
use ball::Ball; use player::Player; use settings; pub struct AI { sleep_time: f64, awake_time: f64, } impl AI { pub fn new() -> AI { AI { sleep_time: 0.0,
} pub fn update(&mut self, dt: f64, player: &mut Player, ball: &mut Ball) { let d = ball.position()[1] - player.position()[1]; let size = ball.aabb().size; if self.awake_time > 0.0 { self.awake_time -= dt; if d < -size[1] / 4.0 { player.start_mo...
awake_time: settings::AI_AWAKE_TIME, }
random_line_split
ai.rs
use ball::Ball; use player::Player; use settings; pub struct AI { sleep_time: f64, awake_time: f64, } impl AI { pub fn
() -> AI { AI { sleep_time: 0.0, awake_time: settings::AI_AWAKE_TIME, } } pub fn update(&mut self, dt: f64, player: &mut Player, ball: &mut Ball) { let d = ball.position()[1] - player.position()[1]; let size = ball.aabb().size; if self.awake_time...
new
identifier_name
complex_inner_join.rs
extern crate rustorm; extern crate uuid; extern crate chrono; extern crate rustc_serialize; use uuid::Uuid; use rustorm::query::Query; use rustorm::query::Equality; use rustorm::dao::{Dao, IsDao}; use rustorm::pool::ManagedPool; #[derive(Debug, Clone)] pub struct Photo { pub photo_id: Uuid, pub url: Option<S...
(dao: &Dao) -> Self { Photo { photo_id: dao.get("photo_id"), url: dao.get_opt("url"), } } fn to_dao(&self) -> Dao { let mut dao = Dao::new(); dao.set("photo_id", &self.photo_id); match self.url { Some(ref _value) => dao.set("url", _val...
from_dao
identifier_name
complex_inner_join.rs
extern crate rustorm; extern crate uuid; extern crate chrono; extern crate rustc_serialize; use uuid::Uuid; use rustorm::query::Query; use rustorm::query::Equality; use rustorm::dao::{Dao, IsDao}; use rustorm::pool::ManagedPool; #[derive(Debug, Clone)] pub struct Photo { pub photo_id: Uuid, pub url: Option<S...
let frag = query.build(db.as_ref()); let expected = " SELECT * FROM bazaar.product INNER JOIN bazaar.product_category\x20 ON product_category.product_id = product.product_id\x20 INNER JOIN bazaar.category\x20 ON category.category_id = product_category.category_id...
.group_by(vec!["category.name"]) .having("count(*)", Equality::GT, &1) .asc("product.name") .desc("product.created");
random_line_split
index.test.ts
import { default as factory, isPostgres, adapters, } from '../readmodel-test-utils' type UnPromise<T> = T extends Promise<T> ? T : never const maybeDescribe = isPostgres() ? describe : describe.skip jest.setTimeout(60000) maybeDescribe('Postgres reconnections with delay', () => { const uniqueName = 'postgres-r...
let flushWorkers: Function let buildOnConnection: Function let performWorkers = true beforeAll(async () => { await factory.create(uniqueName)() adapter = adapters[uniqueName] baseConnection = await adapter.connect(readModelName) flushWorkers = async () => await adapter.subscribe( ...
const currentBuilders = new Set() let adapter: typeof adapters[typeof uniqueName] let baseConnection: UnPromise<ReturnType<typeof adapter['connect']>> const connectionsDelays = new WeakMap<typeof baseConnection, Array<number>>()
random_line_split
index.test.ts
import { default as factory, isPostgres, adapters, } from '../readmodel-test-utils' type UnPromise<T> = T extends Promise<T> ? T : never const maybeDescribe = isPostgres() ? describe : describe.skip jest.setTimeout(60000) maybeDescribe('Postgres reconnections with delay', () => { const uniqueName = 'postgres-r...
} } }) afterAll(async () => { await Promise.all( Array.from(currentConnections).map(async (connection) => { try { await adapter.disconnect(connection, readModelName) } catch (e) {} }) ) currentConnections.clear() await adapter.unsubscribe(baseConnec...
{ currentBuilders.delete(buildPromise) }
conditional_block
lambdaFluc2dCreator.py
import subprocess import sys import os # This code is meant to manage running multiple instances of my KMCLib codes at the same time, # in the name of time efficiency numLambda = 512 numStepsEquilib = 1600000 numStepsAnal = 16000 numStepsSnapshot = 1000 numStepsReq = 16000 sysWidth = 32 sysLength = 32 analInterval = 1...
currentRate = lambdaMin + rateStepSize*rateIndex botConc = 0.99 topConc = 0.01 jobInput = "2dSteadyFlow.py "+str(botConc)+" "+str(topConc)+" "+str(currentRate)+" "+str(sysWidth)+" "+str(sysLength)+" "+str(analInterval)+" "+str(numStepsEquilib)+" "+str(numStepsSnapshot)+" "+str(numStepsAnal)+" "+str(...
conditional_block
lambdaFluc2dCreator.py
import subprocess import sys import os # This code is meant to manage running multiple instances of my KMCLib codes at the same time, # in the name of time efficiency numLambda = 512 numStepsEquilib = 1600000 numStepsAnal = 16000 numStepsSnapshot = 1000 numStepsReq = 16000 sysWidth = 32
analInterval = 1 numPasses = 100 timeInterval = 1.0 dataLocation = "dim2Runs/lambdaScan1/" lambdaMin = 0.05 lambdaMax = 1.25 rateStepSize = (lambdaMax-lambdaMin)/float(numLambda-1) runningJobs = [] for rateIndex in range(0, numLambda): currentRate = lambdaMin + rateStepSize*rateIndex botConc = 0.99 topCon...
sysLength = 32
random_line_split
__init__.py
# Portions 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. # __init__.py - Startup and module loading logic for Mercurial. # # Copyright 2015 Gregory Szorc <gregory.szorc@gmail.com> # # This software ma...
# pyre-fixme[11]: Annotation `hgdemandimport` is not defined as a type. demandimport = hgdemandimport __all__ = [] if getattr(sys, "platform") == "win32": configdir = os.path.join( getattr(os, "environ").get("PROGRAMDATA") or "\ProgramData", "Facebook", "Mercurial", ) else: confi...
# Allow 'from mercurial import demandimport' to keep working. from edenscm import hgdemandimport
random_line_split
__init__.py
# Portions 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. # __init__.py - Startup and module loading logic for Mercurial. # # Copyright 2015 Gregory Szorc <gregory.szorc@gmail.com> # # This software ma...
(name): legacy = getattr(os, "environ").get("HGLEGACY") if legacy is not None: return name in legacy.split() else: return os.path.lexists(os.path.join(configdir, "legacy.%s" % name))
shoulduselegacy
identifier_name
__init__.py
# Portions 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. # __init__.py - Startup and module loading logic for Mercurial. # # Copyright 2015 Gregory Szorc <gregory.szorc@gmail.com> # # This software ma...
else: return os.path.lexists(os.path.join(configdir, "legacy.%s" % name))
return name in legacy.split()
conditional_block
__init__.py
# Portions 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. # __init__.py - Startup and module loading logic for Mercurial. # # Copyright 2015 Gregory Szorc <gregory.szorc@gmail.com> # # This software ma...
legacy = getattr(os, "environ").get("HGLEGACY") if legacy is not None: return name in legacy.split() else: return os.path.lexists(os.path.join(configdir, "legacy.%s" % name))
identifier_body
test_script.py
# -*- coding: utf-8 -*- # Copyright 2017 Chris Meyers <cmeyers@ansible.com> # # This file is part of Ansible # # Ansible 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 # (...
with pytest.raises(AnsibleError) as e: inventory_module.parse(self.inventory, self.loader, '/foo/bar/foobar.py') assert e.value.message == to_native("failed to parse executable inventory script results from " "/foo/bar/foobar.py: obj must be string...
random_line_split
test_script.py
# -*- coding: utf-8 -*- # Copyright 2017 Chris Meyers <cmeyers@ansible.com> # # This file is part of Ansible # # Ansible 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 # (...
self.popen = register_patch('subprocess.Popen') self.popen.return_value = self.popen_result self.BaseInventoryPlugin = register_patch('ansible.plugins.inventory.BaseInventoryPlugin') self.BaseInventoryPlugin.get_cache_prefix.return_value = 'abc123' def test_parse_subprocess_path_...
class Inventory(): cache = dict() class PopenResult(): returncode = 0 stdout = b"" stderr = b"" def communicate(self): return (self.stdout, self.stderr) self.popen_result = PopenResult() self.inventory = Inventory() ...
identifier_body