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
change_detection_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 {ApplicationRef, ChangeDetectionStrategy, Component, ComponentFactoryResolver, ComponentRef, Directive, Embe...
{ counter = 0; @ViewChild('vc', {read: ViewContainerRef}) vcRef !: ViewContainerRef; constructor(private _cfr: ComponentFactoryResolver) {} createComponentView<T>(cmptType: Type<T>): ComponentRef<T> { const cf = this._cfr.resolveComponentFactory(cmptType); return t...
TestCmpt
identifier_name
search.js
"use strict"; var Search = {}; Search.DoesDeviceMatch = function (device, search) { for (var i = 0; i < search.length; i++) { if (device == search[i])
} Search.ByDevices = function (devices, search) { var total = 0; var found = 0; for (var key in devices) { total += devices[key]; if (Search.DoesDeviceMatch(key, search)) found += devices[key]; } return [found, total]; } Search.DoesTermMatch = function (item, terms) { for (var i = 0; i < ter...
return true; } return false;
random_line_split
recreate_tables.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Tool to recreate all tables/procedures in the database. """ import argparse import copy import re from os import path from src.sqllist import re_sub try: import monetdb.sql as db try: import monetdb.exceptions as me except ImportError: # Ol...
for view in self.VIEWS: try: self.conn.execute("drop view %s;" % view) except error_set: pass print("drop view %s;" % view) drop_tables = copy.copy(self.TABLES) drop_tables.reverse() ...
if self.monet: try: self.conn.execute("drop procedure %s;" % procedure) print("drop procedure %s;" % procedure) except error_set: pass
conditional_block
recreate_tables.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Tool to recreate all tables/procedures in the database. """ import argparse import copy import re from os import path from src.sqllist import re_sub try: import monetdb.sql as db try: import monetdb.exceptions as me except ImportError: # Ol...
if __name__ == '__main__': parser = argparse.ArgumentParser(description=""" ***Database recreator. ***Created by A. Mints (2012). *WARNING!!!* Clears all data from the database.""", formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-D', '--database', type=str, defa...
self.conn.close() return 0
random_line_split
recreate_tables.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Tool to recreate all tables/procedures in the database. """ import argparse import copy import re from os import path from src.sqllist import re_sub try: import monetdb.sql as db try: import monetdb.exceptions as me except ImportError: # Ol...
(self, sql_lines): """ Prepare SQL code for MonetDB/PostgreSQL. Remove all comments, make necessary substitutions. """ sql_lines = re_sub(r'/\*.*?\*/', '', sql_lines, flags=re.DOTALL) sql_lines = re_sub(r'--.*$', '', sql_lines, flags=re.MULTILINE) if not self.mone...
refactor_lines
identifier_name
recreate_tables.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Tool to recreate all tables/procedures in the database. """ import argparse import copy import re from os import path from src.sqllist import re_sub try: import monetdb.sql as db try: import monetdb.exceptions as me except ImportError: # Ol...
def drop_table(self, tab_name): """ Drop table if it exists. """ if self.get_table_exists(tab_name): if self.monet: self.conn.execute("drop table %s;" % tab_name) else: self.conn.execute("drop table %s cascade;" % tab_name) ...
""" Check if the table exists in the database. """ if self.monet: cur = self.conn.cursor() cur.execute( "select count(*) from sys.tables where name = '%s';" % tab_name) else: cur = self.conn cur.execu...
identifier_body
views.py
from django.http import HttpResponse from django.views.generic import TemplateView, DetailView from django.views.generic.edit import FormView from .forms import DonationForm from .models import CardType import json class PagoView(FormView): form_class = DonationForm template_name = 'pago.html' success_url...
return context def form_valid(self, form): instance = super(PagoView, self).form_valid(form) return instance class PagoDone(TemplateView): template_name = 'done.html' class CardTypeView(DetailView): model = CardType slug_field = 'card_type' def get(self, *args, **kwarg...
context['navidad'] = True
conditional_block
views.py
from django.http import HttpResponse from django.views.generic import TemplateView, DetailView from django.views.generic.edit import FormView from .forms import DonationForm from .models import CardType import json class PagoView(FormView): form_class = DonationForm template_name = 'pago.html' success_url...
(TemplateView): template_name = 'done.html' class CardTypeView(DetailView): model = CardType slug_field = 'card_type' def get(self, *args, **kwargs): card_type = CardType.objects.filter(card_type=kwargs.pop('slug')).first() if card_type: response = { 'id': ...
PagoDone
identifier_name
views.py
from django.http import HttpResponse from django.views.generic import TemplateView, DetailView from django.views.generic.edit import FormView from .forms import DonationForm from .models import CardType import json class PagoView(FormView): form_class = DonationForm template_name = 'pago.html' success_url...
class PagoDone(TemplateView): template_name = 'done.html' class CardTypeView(DetailView): model = CardType slug_field = 'card_type' def get(self, *args, **kwargs): card_type = CardType.objects.filter(card_type=kwargs.pop('slug')).first() if card_type: response = { ...
instance = super(PagoView, self).form_valid(form) return instance
identifier_body
views.py
from django.http import HttpResponse from django.views.generic import TemplateView, DetailView from django.views.generic.edit import FormView from .forms import DonationForm
class PagoView(FormView): form_class = DonationForm template_name = 'pago.html' success_url = 'http://funsepa.org/cms/es/gracias/' def get_context_data(self, **kwargs): context = super(PagoView, self).get_context_data(**kwargs) david = self.request.GET.get('david', None) navid...
from .models import CardType import json
random_line_split
window.rs
extern crate ncurses; use self::ncurses::*; // Window are actually implemented has ncurcesw subwin // of the stdscr pub struct Window { start_y: i32, start_x: i32, size_y: i32,
size_x: i32, handle: WINDOW, // ncurses subwin handle } impl Window { pub fn new(start_y: i32, start_x: i32, size_y: i32, size_x: i32) -> Window { unsafe { Window { start_y: start_y, start_x: start_x, size_y: size_y, size_...
random_line_split
window.rs
extern crate ncurses; use self::ncurses::*; // Window are actually implemented has ncurcesw subwin // of the stdscr pub struct
{ start_y: i32, start_x: i32, size_y: i32, size_x: i32, handle: WINDOW, // ncurses subwin handle } impl Window { pub fn new(start_y: i32, start_x: i32, size_y: i32, size_x: i32) -> Window { unsafe { Window { start_y: start_y, start_x: start...
Window
identifier_name
window.rs
extern crate ncurses; use self::ncurses::*; // Window are actually implemented has ncurcesw subwin // of the stdscr pub struct Window { start_y: i32, start_x: i32, size_y: i32, size_x: i32, handle: WINDOW, // ncurses subwin handle } impl Window { pub fn new(start_y: i32, start_x: i32, size_...
pub fn write(&self, text: String) { ncurses::waddstr(self.handle, text.as_ref()); } pub fn mvaddch(&self, y: i32, x: i32, ch: u64) { ncurses::mvwaddch(self.handle, y, x, ch); } pub fn refresh(&self) { ncurses::wrefresh(self.handle); } pub fn delwin(&self) { ...
{ unsafe { self.handle = ncurses::subwin(stdscr, self.size_y, self.size_x, self.start_y, self.start_x); } ncurses::box_(self.handle, 0, 0); }
identifier_body
cell.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/. */ //! A shareable mutable container for the DOM. use dom::bindings::trace::JSTraceable; use js::jsapi::{JSTracer}; ...
(&self, trc: *mut JSTracer) { unsafe { (*self).borrow_for_gc_trace().trace(trc) } } } // Functionality duplicated with `core::cell::RefCell` // =================================================== impl<T> DOMRefCell<T> { /// Create a new `DOMRefCell` containing `value`. pub fn ne...
trace
identifier_name
cell.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/. */ //! A shareable mutable container for the DOM. use dom::bindings::trace::JSTraceable; use js::jsapi::{JSTracer}; ...
_ => Some(self.value.borrow()), } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// Returns `None` if the value is currently borrowed. /// ...
BorrowState::Writing => None,
random_line_split
cell.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/. */ //! A shareable mutable container for the DOM. use dom::bindings::trace::JSTraceable; use js::jsapi::{JSTracer}; ...
}
{ self.try_borrow_mut().expect("DOMRefCell<T> already borrowed") }
identifier_body
omni-output-pane-view.ts
import {Disposable} from "rx"; var Convert = require('ansi-to-html'); import _ = require('lodash') import Omni = require('../../omni-sharp-server/omni') import React = require('react'); import {ReactClientComponent} from "./react-client-component"; import {server} from '../features/server-information'; interface IOutp...
private scrollToBottom() { var item = <any> React.findDOMNode(this).lastElementChild.lastElementChild; if (item) item.scrollIntoViewIfNeeded(); } private createItem(item: OmniSharp.OutputMessage, index: number) { return React.DOM.pre({ key: `output-${index}`, ...
{ super.componentDidMount(); this.disposable.add(server.observe.output .subscribe(z => this.setState({ output: z }, () => this.scrollToBottom()))); _.defer(_.bind(this.scrollToBottom, this)); }
identifier_body
omni-output-pane-view.ts
import {Disposable} from "rx"; var Convert = require('ansi-to-html'); import _ = require('lodash') import Omni = require('../../omni-sharp-server/omni') import React = require('react'); import {ReactClientComponent} from "./react-client-component"; import {server} from '../features/server-information'; interface IOutp...
() { return React.DOM.div({ className: 'omni-output-pane-view native-key-bindings ' + (this.props['className'] || ''), tabIndex: -1 }, React.DOM.div({ className: 'messages-container' }, _.map(this.state.output, (item, index) => this.createI...
render
identifier_name
omni-output-pane-view.ts
import {Disposable} from "rx"; var Convert = require('ansi-to-html'); import _ = require('lodash') import Omni = require('../../omni-sharp-server/omni') import React = require('react'); import {ReactClientComponent} from "./react-client-component"; import {server} from '../features/server-information'; interface IOutp...
.subscribe(z => this.setState({ output: z }, () => this.scrollToBottom()))); _.defer(_.bind(this.scrollToBottom, this)); } private scrollToBottom() { var item = <any> React.findDOMNode(this).lastElementChild.lastElementChild; if (item) item.scrollIntoViewIfNeeded(); } ...
public componentDidMount() { super.componentDidMount(); this.disposable.add(server.observe.output
random_line_split
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-13 18:08 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='ProxyGrantingTicket', fields=[ ('id', models.AutoField(auto_created=True, primary_k...
Migration
identifier_name
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-13 18:08 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migration...
('date', models.DateTimeField(auto_now_add=True)), ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='SessionTicket', ...
('pgt', models.CharField(blank=True, max_length=255, null=True)),
random_line_split
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-13 18:08 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('session_key', models.CharField(max_length=255)), ('ticket', models.CharField(max_length=255)), ], ), migrations.AlterUniqu...
initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='ProxyGrantingTicket', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, ver...
identifier_body
macro_crate_test.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(register: |Name, SyntaxExtension|) { register(token::intern("make_a_1"), NormalTT(~BasicMacroExpander { expander: expand_make_a_1, span: None, }, None)); register(token::intern("into_foo"), ItemModifier(expand_into_foo)); } fn expand_make_a_1(cx: &mut ExtCtxt, s...
macro_registrar
identifier_name
macro_crate_test.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
MacExpr::new(quote_expr!(cx, 1i)) } fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: @MetaItem, it: @Item) -> @Item { @Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone() } } pub fn foo() {}
{ cx.span_fatal(sp, "make_a_1 takes no arguments"); }
conditional_block
macro_crate_test.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
use syntax::parse::token; #[macro_export] macro_rules! exported_macro (() => (2)) macro_rules! unexported_macro (() => (3)) #[macro_registrar] pub fn macro_registrar(register: |Name, SyntaxExtension|) { register(token::intern("make_a_1"), NormalTT(~BasicMacroExpander { expander: expand_make_a...
use syntax::ast::{Name, TokenTree, Item, MetaItem}; use syntax::codemap::Span; use syntax::ext::base::*;
random_line_split
macro_crate_test.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{}
identifier_body
autocollect.ts
import { get, ajax } from './core'; import { DEFAULT_OPTION } from './option'; import { UTIL, support } from './lib/UTIL'; import { setTemplateElement } from './template'; /** * Template auto collect */ export const autocollect = () => { if (!DEFAULT_OPTION.autocollect) return;
Array.prototype.forEach.call(document.querySelectorAll('SCRIPT[id]'), resolveElement); }; const resolveElement = async (element: Element) => { // auto replace if (!element.getAttribute('data-ajst')) return UTIL.removeElement(element); const ajaxURL = element.getAttribute('data-ajst-ajax'); ...
Array.prototype.forEach.call(document.querySelectorAll('SCRIPT[id]'), setTemplateElement);
random_line_split
ui.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
//! Computed values for UI properties use crate::values::computed::color::Color; use crate::values::computed::url::ComputedImageUrl; use crate::values::computed::Number; use crate::values::generics::ui as generics; pub use crate::values::specified::ui::CursorKind; pub use crate::values::specified::ui::{MozForceBroken...
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
random_line_split
query-editor.js
var $ = require('jquery'); var keymaster = require('keymaster'); var ChartEditor = require('./component-chart-editor.js'); var DbInfo = require('./component-db-info.js'); var AceSqlEditor = require('./component-ace-sql-editor.js'); var DataGrid = require('./component-data-grid.js'); var QueryEditor = function () { ...
() { $('#server-run-time').html(''); $('#rowcount').html(''); dataGrid.emptyDataGrid(); var data = { queryText: aceSqlEditor.getSelectedOrAllText(), connectionId: $('#connection').val(), cacheKey: $('#cache-key').val(), queryName: getQuery...
runQuery
identifier_name
query-editor.js
var $ = require('jquery'); var keymaster = require('keymaster'); var ChartEditor = require('./component-chart-editor.js'); var DbInfo = require('./component-db-info.js'); var AceSqlEditor = require('./component-ace-sql-editor.js'); var DataGrid = require('./component-data-grid.js'); var QueryEditor = function () { ...
function saveQuery () { var $queryId = $('#query-id'); var query = { name: getQueryName(), queryText: aceSqlEditor.getEditorText(), tags: getQueryTags(), connectionId: dbInfo.getConnectionId(), chartConfiguration: chartEditor.getChart...
{ return $.map($('#tags').val().split(','), $.trim); }
identifier_body
query-editor.js
var $ = require('jquery'); var keymaster = require('keymaster'); var ChartEditor = require('./component-chart-editor.js'); var DbInfo = require('./component-db-info.js'); var AceSqlEditor = require('./component-ace-sql-editor.js'); var DataGrid = require('./component-data-grid.js'); var QueryEditor = function () { ...
} else { $('#btn-save-result').removeClass('label-info').addClass('label-danger').text('Failed'); } }).fail(function () { alert('ajax fail'); }); } $('#btn-save').click(function (event) { event.preventDefault(); event.stopP...
}, 1000);
random_line_split
query-editor.js
var $ = require('jquery'); var keymaster = require('keymaster'); var ChartEditor = require('./component-chart-editor.js'); var DbInfo = require('./component-db-info.js'); var AceSqlEditor = require('./component-ace-sql-editor.js'); var DataGrid = require('./component-data-grid.js'); var QueryEditor = function () { ...
else { $('#btn-save-result').removeClass('label-info').addClass('label-danger').text('Failed'); } }).fail(function () { alert('ajax fail'); }); } $('#btn-save').click(function (event) { event.preventDefault(); event.stopPropagation();...
{ window.history.replaceState({}, "query " + data.query._id, "/queries/" + data.query._id); $queryId.val(data.query._id); $('#btn-save-result').removeClass('label-info').addClass('label-success').text('Success'); setTimeout(function () { ...
conditional_block
display.rs
use sdl2::video::Window; use sdl2::render::Renderer; use sdl2::pixels::Color::RGB; use sdl2::rect::{Point, Rect}; use sdl2::sdl::Sdl; use gpu::Color; pub struct Display { renderer: Renderer<'static>, /// Upscaling factor, log2. upscale: u8, } impl Display { pub fn new(sdl2: &Sdl, upscale: u8) -> Dis...
(&mut self, x: u32, y: u32, color: Color) { let color = match color { Color::Black => RGB(0x00, 0x00, 0x00), Color::DarkGrey => RGB(0x55, 0x55, 0x55), Color::LightGrey => RGB(0xab, 0xab, 0xab), Color::White => RGB(0xff, 0xff, 0xff), }; le...
set_pixel
identifier_name
display.rs
use sdl2::video::Window; use sdl2::render::Renderer; use sdl2::pixels::Color::RGB; use sdl2::rect::{Point, Rect}; use sdl2::sdl::Sdl; use gpu::Color; pub struct Display { renderer: Renderer<'static>, /// Upscaling factor, log2. upscale: u8, } impl Display { pub fn new(sdl2: &Sdl, upscale: u8) -> Dis...
}; Display { renderer: renderer, upscale: upscale } } } impl ::ui::Display for Display { fn clear(&mut self) { let mut drawer = self.renderer.drawer(); let _ = drawer.set_draw_color(RGB(0xff, 0x00, 0x00)); let _ = drawer.clear(); } fn set_pixel(&mut self, x: ...
{ let up = 1 << (upscale as usize); let xres = 160 * up; let yres = 144 * up; let window = match Window::new(sdl2, "gb-rs", ::sdl2::video::WindowPos::PosCentered, ::sdl2::video::WindowPos::PosCentered, ...
identifier_body
display.rs
use sdl2::video::Window; use sdl2::render::Renderer; use sdl2::pixels::Color::RGB; use sdl2::rect::{Point, Rect}; use sdl2::sdl::Sdl; use gpu::Color; pub struct Display { renderer: Renderer<'static>, /// Upscaling factor, log2. upscale: u8, } impl Display { pub fn new(sdl2: &Sdl, upscale: u8) -> Dis...
Display { renderer: renderer, upscale: upscale } } } impl ::ui::Display for Display { fn clear(&mut self) { let mut drawer = self.renderer.drawer(); let _ = drawer.set_draw_color(RGB(0xff, 0x00, 0x00)); let _ = drawer.clear(); } fn set_pixel(&mut self, x: u32, y: u32, ...
};
random_line_split
linesLayout.js
define(function (require) { return function (ecModel) { ecModel.eachSeriesByType('lines', function (seriesModel) { var coordSys = seriesModel.coordinateSystem; var lineData = seriesModel.getData(); // FIXME Use data dimensions ? lineData.each(function (idx) ...
} var pts = []; if (seriesModel.get('polyline')) { for (var i = 0; i < coords.length; i++) { pts.push(coordSys.dataToPoint(coords[i])); } } else { pts[0] =...
if (__DEV__) { if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) { throw new Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.'); }
random_line_split
linesLayout.js
define(function (require) { return function (ecModel) { ecModel.eachSeriesByType('lines', function (seriesModel) { var coordSys = seriesModel.coordinateSystem; var lineData = seriesModel.getData(); // FIXME Use data dimensions ? lineData.each(function (idx) ...
} var pts = []; if (seriesModel.get('polyline')) { for (var i = 0; i < coords.length; i++) { pts.push(coordSys.dataToPoint(coords[i])); } } else { pts[0] ...
{ throw new Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.'); }
conditional_block
S15.10.2.15_A1_T23.js
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.10.2.15_A1_T23; * @section: 15.10.2.15;
* following: * If A does not contain exactly one character or B does not contain exactly one character then throw * a SyntaxError exception; * @description: Checking if execution of "/[b-G\d]/.exec("a")" leads to throwing the correct exception; */ //CHECK#1 try { $ERROR('#1.1: /[b-G\\d]/.exec("a") throw Sy...
* @assertion: The internal helper function CharacterRange takes two CharSet parameters A and B and performs the
random_line_split
S15.10.2.15_A1_T23.js
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.10.2.15_A1_T23; * @section: 15.10.2.15; * @assertion: The internal helper function CharacterRange takes two CharSet parameters A and B and performs the * followin...
}
{ $ERROR('#1.2: /[b-G\\d]/.exec("a") throw SyntaxError. Actual: ' + (e)); }
conditional_block
ProofreadModal.js
import React, { PureComponent } from 'react'; import { Modal } from 'antd'; import { inject, observer } from 'mobx-react'; import PropTypes from 'prop-types'; import ProofreadAuditorForm from './ProofreadAuditorForm'; import ProofreadTypeForm from './ProofreadTypeForm'; import ProofreadReturnForm from './ProofreadRetur...
export default ProofreadModal;
random_line_split
ProofreadModal.js
import React, { PureComponent } from 'react'; import { Modal } from 'antd'; import { inject, observer } from 'mobx-react'; import PropTypes from 'prop-types'; import ProofreadAuditorForm from './ProofreadAuditorForm'; import ProofreadTypeForm from './ProofreadTypeForm'; import ProofreadReturnForm from './ProofreadRetur...
() { const {proofreadStore, handleModalOk, handleModalChange} = this.props; const form = (function() { switch (proofreadStore.modal.type) { case 'auditor': return <ProofreadAuditorForm handleModalChange={handleModalChange}/>; case 'type': return <ProofreadTypeForm handl...
render
identifier_name
de.js
Bild oder Dimensionsfeld.', requiredProperty: 'Die :property wird benötigt und muss einen Wert besitzen.', onlyNumbers: 'Der :property Wert kann nur Nummern beinhalten.', exceedsMax: 'Der :property Wert übersteigt das Maximum von :max.', belowMin: 'Der :property Wert liegt unter dem Minimum von :min.', outOf...
contentTypeUseButtonLabel: 'Benutzen', contentTypeUpdateButtonLabel: 'Aktualisieren', contentTypeUpdatingButtonLabel: 'Aktualisiere', contentTypeGetButtonLabel: '\u00dcbernehmen', contentTypeBackButtonLabel: 'Zurück', contentTypeIconAltText: 'Symbolbild', contentTypeInstallSuccess: ':contentType erfolgrei...
contentTypeInstallingButtonLabel: 'Installiere',
random_line_split
hover.js
import { dispatch as d3_dispatch } from 'd3-dispatch'; import { event as d3_event, select as d3_select } from 'd3-selection'; import { d3keybinding as d3_keybinding } from '../lib/d3.keybinding.js'; import { osmEntity } from '../osm/index'; import { utilRebind } from '../util/rebind'; /* The hover behavi...
() { buttonDown = false; d3_select(window) .on('mouseup.hover', null, true); } function enter(d) { if (d === target) return; target = d; _selection.selectAll('.hover') .classed('hover', false); _se...
mouseup
identifier_name
hover.js
import { dispatch as d3_dispatch } from 'd3-dispatch'; import { event as d3_event, select as d3_select } from 'd3-selection'; import { d3keybinding as d3_keybinding } from '../lib/d3.keybinding.js'; import { osmEntity } from '../osm/index'; import { utilRebind } from '../util/rebind'; /* The hover behavi...
function keyup() { if (altDisables && d3_event.keyCode === d3_keybinding.modifierCodes.alt) { _selection.selectAll('.hover-suppressed') .classed('hover-suppressed', false) .classed('hover', true); _selection .classed('hover-disabled...
{ if (altDisables && d3_event.keyCode === d3_keybinding.modifierCodes.alt) { _selection.selectAll('.hover') .classed('hover-suppressed', true) .classed('hover', false); _selection .classed('hover-disabled', true); dispatch.cal...
identifier_body
hover.js
import { dispatch as d3_dispatch } from 'd3-dispatch'; import { event as d3_event, select as d3_select } from 'd3-selection'; import { d3keybinding as d3_keybinding } from '../lib/d3.keybinding.js'; import { osmEntity } from '../osm/index'; import { utilRebind } from '../util/rebind'; /* The hover behavi...
.classed('hover-suppressed', false); selection .classed('hover-disabled', false); selection .on('mouseover.hover', null) .on('mouseout.hover', null) .on('mousedown.hover', null); d3_select(window) .on('keydown.hover', nul...
selection.selectAll('.hover') .classed('hover', false); selection.selectAll('.hover-suppressed')
random_line_split
query.rs
use async_trait::async_trait; use super::ElasticsearchStorage; use crate::domain::ports::secondary::get::{Error as GetError, Get, Parameters as GetParameters}; use crate::domain::ports::secondary::search::{ Error as SearchError, Parameters as SearchParameters, Search, }; #[async_trait] impl Search for Elasticsear...
( &self, parameters: SearchParameters, ) -> Result<Vec<Self::Doc>, SearchError> { self.search_documents( parameters.es_indices_to_search_in, parameters.query, parameters.result_limit, parameters.timeout, ) .await .map_er...
search_documents
identifier_name
query.rs
use async_trait::async_trait; use super::ElasticsearchStorage; use crate::domain::ports::secondary::get::{Error as GetError, Get, Parameters as GetParameters}; use crate::domain::ports::secondary::search::{ Error as SearchError, Parameters as SearchParameters, Search, }; #[async_trait] impl Search for Elasticsear...
} #[async_trait] impl Get for ElasticsearchStorage { type Doc = serde_json::Value; async fn get_documents_by_id( &self, parameters: GetParameters, ) -> Result<Vec<Self::Doc>, GetError> { self.get_documents_by_id(parameters.query, parameters.timeout) .await ...
{ self.search_documents( parameters.es_indices_to_search_in, parameters.query, parameters.result_limit, parameters.timeout, ) .await .map_err(|err| SearchError::DocumentRetrievalError { source: err.into() }) }
identifier_body
query.rs
use async_trait::async_trait; use super::ElasticsearchStorage; use crate::domain::ports::secondary::get::{Error as GetError, Get, Parameters as GetParameters}; use crate::domain::ports::secondary::search::{ Error as SearchError, Parameters as SearchParameters, Search, };
type Doc = serde_json::Value; async fn search_documents( &self, parameters: SearchParameters, ) -> Result<Vec<Self::Doc>, SearchError> { self.search_documents( parameters.es_indices_to_search_in, parameters.query, parameters.result_limit, ...
#[async_trait] impl Search for ElasticsearchStorage {
random_line_split
main.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
} Ok(()) } } impl Service for MarkerService {} // Several helpers for testkit. /// Time oracle instance ID. const TIME_SERVICE_ID: InstanceId = 112; /// Time oracle instance name. const TIME_SERVICE_NAME: &str = "time-oracle"; /// Marker service ID. const SERVICE_ID: InstanceId = 128; /// Marker...
{}
conditional_block
main.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
runtime::{ExecutionContext, ExecutionError, InstanceId, SnapshotExt}, }; use exonum_derive::{ exonum_interface, BinaryValue, FromAccess, ObjectHash, RequireArtifact, ServiceDispatcher, ServiceFactory, }; use exonum_rust_runtime::Service; use exonum_testkit::{Spec, TestKitBuilder}; use serde_derive::{Deseria...
access::{Access, FromAccess}, ProofMapIndex, },
random_line_split
main.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
<T: Access> { pub marks: ProofMapIndex<T::Base, PublicKey, i32>, } impl<T: Access> MarkerSchema<T> { fn new(access: T) -> Self { Self::from_root(access).unwrap() } } impl MarkerTransactions<ExecutionContext<'_>> for MarkerService { type Output = Result<(), ExecutionError>; fn mark(&self, ...
MarkerSchema
identifier_name
summary_test_internal.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def get_one(db, q, *p): return db.execute(q, p).fetchone()[0] def get_all(db, q, *p): return unroll(db.execute(q, p).fetchall()) def unroll(list_of_tuples): return sum(list_of_tuples, ())
"""Helper for summary database testing.""" def setUp(self): super(SummaryDbTest, self).setUp() self.db_path = os.path.join(self.get_temp_dir(), 'DbTest.sqlite') if os.path.exists(self.db_path): os.unlink(self.db_path) self.db = sqlite3.connect(self.db_path) self.create_summary_db_writer = f...
identifier_body
summary_test_internal.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
(db, q, *p): return unroll(db.execute(q, p).fetchall()) def unroll(list_of_tuples): return sum(list_of_tuples, ())
get_all
identifier_name
summary_test_internal.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
self.db = sqlite3.connect(self.db_path) self.create_summary_db_writer = functools.partial( summary_ops.create_summary_db_writer, db_uri=self.db_path, experiment_name='experiment', run_name='run', user_name='user') def tearDown(self): self.db.close() super(Summa...
def setUp(self): super(SummaryDbTest, self).setUp() self.db_path = os.path.join(self.get_temp_dir(), 'DbTest.sqlite') if os.path.exists(self.db_path): os.unlink(self.db_path)
random_line_split
summary_test_internal.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
self.db = sqlite3.connect(self.db_path) self.create_summary_db_writer = functools.partial( summary_ops.create_summary_db_writer, db_uri=self.db_path, experiment_name='experiment', run_name='run', user_name='user') def tearDown(self): self.db.close() super(Summ...
os.unlink(self.db_path)
conditional_block
version.rs
MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use chrono::{DateTime, Utc}; use exempi::Xmp; use std::path::Path; use crate::audit::{ audit_get_array_value, audit_get_bool_value, audit_get_date_value, audit_get_dict_value, audit_get_int_value, audit_get_str_val...
{ uuid: Option<String>, model_id: Option<i64>, /// The associated `Master`. master_uuid: Option<String>, /// uuid of the `Folder` project this reside in. pub project_uuid: Option<String>, /// uuid of the raw `Master`. pub raw_master_uuid: Option<String>, /// uuid of the non raw `Ma...
Version
identifier_name
version.rs
MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use chrono::{DateTime, Utc}; use exempi::Xmp; use std::path::Path; use crate::audit::{ audit_get_array_value, audit_get_bool_value, audit_get_date_value, audit_get_dict_value, audit_get_int_value, audit_get_str_val...
auditor.skip("thumbnailGroup", SkipReason::Ignore); auditor.skip("faceDetectionIsFromPreview", SkipReason::Ignore); auditor.skip("processedHeight", SkipReason::Ignore); auditor.skip("processedWidth", SkipReason::Ignore); ...
auditor.skip("statistics", SkipReason::Ignore);
random_line_split
version.rs
MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use chrono::{DateTime, Utc}; use exempi::Xmp; use std::path::Path; use crate::audit::{ audit_get_array_value, audit_get_bool_value, audit_get_date_value, audit_get_dict_value, audit_get_int_value, audit_get_str_val...
} result } _ => None, } } } impl AplibObject for Version { fn obj_type(&self) -> AplibType { AplibType::Version } fn uuid(&self) -> &Option<String> { &self.uuid } fn parent(&self) -> &Option<String> { &self...
{ auditor.skip("statistics", SkipReason::Ignore); auditor.skip("thumbnailGroup", SkipReason::Ignore); auditor.skip("faceDetectionIsFromPreview", SkipReason::Ignore); auditor.skip("processedHeight", SkipReason::Ignore); a...
conditional_block
version.rs
was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use chrono::{DateTime, Utc}; use exempi::Xmp; use std::path::Path; use crate::audit::{ audit_get_array_value, audit_get_bool_value, audit_get_date_value, audit_get_dict_value, audit_get_int_value, audit_get_str_value, ...
} impl ToXmp for Version { fn to_xmp(&self, xmp: &mut Xmp) -> bool { // Here we make sure the Exif data are // processed before Iptc. if let Some(ref exif) = self.exif { exif.to_xmp(xmp); } if let Some(ref iptc) = self.iptc { iptc.to_xmp(xmp); ...
{ store::Wrapper::Version(Box::new(obj)) }
identifier_body
readme_example.rs
// This file is released into Public Domain. use crate::common::*; use gnuplot::*; mod common; fn example(c: Common) { let mut fg = Figure::new(); fg.axes2d() .set_title("A plot", &[]) .set_legend(Graph(0.5), Graph(0.9), &[], &[]) .set_x_label("x", &[]) .set_y_label("y^2", &[]) .lines( &[-3., -2., -1...
} fn main() { Common::new().map(|c| example(c)); }
{ fg.set_terminal("pngcairo", "readme_example.png"); fg.show().unwrap(); }
conditional_block
readme_example.rs
// This file is released into Public Domain. use crate::common::*; use gnuplot::*; mod common; fn example(c: Common) { let mut fg = Figure::new(); fg.axes2d() .set_title("A plot", &[]) .set_legend(Graph(0.5), Graph(0.9), &[], &[]) .set_x_label("x", &[]) .set_y_label("y^2", &[]) .lines( &[-3., -2., -1...
() { Common::new().map(|c| example(c)); }
main
identifier_name
readme_example.rs
// This file is released into Public Domain. use crate::common::*; use gnuplot::*; mod common; fn example(c: Common) { let mut fg = Figure::new(); fg.axes2d() .set_title("A plot", &[]) .set_legend(Graph(0.5), Graph(0.9), &[], &[]) .set_x_label("x", &[]) .set_y_label("y^2", &[]) .lines( &[-3., -2., -1...
{ Common::new().map(|c| example(c)); }
identifier_body
readme_example.rs
// This file is released into Public Domain. use crate::common::*; use gnuplot::*; mod common; fn example(c: Common) { let mut fg = Figure::new(); fg.axes2d() .set_title("A plot", &[]) .set_legend(Graph(0.5), Graph(0.9), &[], &[]) .set_x_label("x", &[]) .set_y_label("y^2", &[]) .lines( &[-3., -2., -1...
}
random_line_split
lib.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 https://mozilla.org/MPL/2.0/. */ #![deny(unsafe_code)] #![crate_name = "servo_url"] #![crate_type = "rlib"] #[macro_use] extern crate malloc_size...
// Step 6 } else { self.scheme() == "file" } } } impl fmt::Display for ServoUrl { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(formatter) } } impl fmt::Debug for ServoUrl { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::R...
{ host == "localhost" || host.ends_with(".localhost") }
conditional_block
lib.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 https://mozilla.org/MPL/2.0/. */ #![deny(unsafe_code)] #![crate_name = "servo_url"] #![crate_type = "rlib"] #[macro_use] extern crate malloc_size...
return false; } // Step 3 if self.scheme() == "https" || self.scheme() == "wss" { true // Steps 4-5 } else if self.host().is_some() { let host = self.host_str().unwrap(); // Step 4 if let Ok(ip_addr) = host.parse::<IpAd...
random_line_split
lib.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 https://mozilla.org/MPL/2.0/. */ #![deny(unsafe_code)] #![crate_name = "servo_url"] #![crate_type = "rlib"] #[macro_use] extern crate malloc_size...
pub fn username(&self) -> &str { self.0.username() } pub fn password(&self) -> Option<&str> { self.0.password() } pub fn to_file_path(&self) -> Result<::std::path::PathBuf, ()> { self.0.to_file_path() } pub fn host(&self) -> Option<url::Host<&str>> { self...
{ self.as_mut_url().set_fragment(fragment) }
identifier_body
lib.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 https://mozilla.org/MPL/2.0/. */ #![deny(unsafe_code)] #![crate_name = "servo_url"] #![crate_type = "rlib"] #[macro_use] extern crate malloc_size...
(&mut self) -> &mut Url { Arc::make_mut(&mut self.0) } pub fn set_username(&mut self, user: &str) -> Result<(), ()> { self.as_mut_url().set_username(user) } pub fn set_ip_host(&mut self, addr: IpAddr) -> Result<(), ()> { self.as_mut_url().set_ip_host(addr) } pub fn set...
as_mut_url
identifier_name
ttt.py
# old single process tictactoe game to be rewritten....
import numpy import os class TicTacToePlayer: def __init__(self, playerType, playerName, ttt_game_settings): if playerType not in ['AI', 'Terminal']: raise(ValueError()) self.type=playerType self.name=playerName self.board_size = ttt_game_settings['board_size'] self.nr_of_positions = ttt_game_settings['...
random_line_split
ttt.py
# old single process tictactoe game to be rewritten.... import numpy import os class TicTacToePlayer: def __init__(self, playerType, playerName, ttt_game_settings): if playerType not in ['AI', 'Terminal']: raise(ValueError()) self.type=playerType self.name=playerName self.board_size = ttt_game_settings['...
else: return self.checkStreak(next_pos,direction) + 1 def checkGameEnded(self): gameHasEnded, endMessage = self.checkWinner() if not gameHasEnded: if len(self.game) == self.board_size[0]*self.board_size[1]: gameHasEnded = True endMessage = "Its a tie!" return gameHasEnded, endMessage if ...
return 0
conditional_block
ttt.py
# old single process tictactoe game to be rewritten.... import numpy import os class TicTacToePlayer: def __init__(self, playerType, playerName, ttt_game_settings): if playerType not in ['AI', 'Terminal']: raise(ValueError()) self.type=playerType self.name=playerName self.board_size = ttt_game_settings['...
(self, board): if self.type == 'AI': return numpy.random.randint(1,self.nr_of_positions+1) elif self.type == 'Terminal': return self.playFromTerminal(board) def playFromTerminal(self,board): os.system('cls' if os.name == 'nt' else 'clear') print(board) while True: try: moveAttempt = input("%s! ...
playMove
identifier_name
ttt.py
# old single process tictactoe game to be rewritten.... import numpy import os class TicTacToePlayer: def __init__(self, playerType, playerName, ttt_game_settings): if playerType not in ['AI', 'Terminal']: raise(ValueError()) self.type=playerType self.name=playerName self.board_size = ttt_game_settings['...
def getGame(self): return self.game def initializa_game(self,settings): board_size_in = settings['board_size'] win_length = settings['win_length'] board_size = numpy.asarray(board_size_in,dtype='int') if len(board_size) != 2: raise(ValueError('Not a good size!')) if win_length > min(board_size) or not ...
self.game, self.board_size, self.win_length = self.initializa_game(settings) self.player1 = TicTacToePlayer(\ playerType=player1Type,\ playerName=player1Name,\ ttt_game_settings=settings) self.playerMinus1 = TicTacToePlayer(\ playerType=playerMinus1Type,\ playerName=playerMinus1Name,\ ttt_game_set...
identifier_body
index.js
var express = require('express'); var Route = express.Router();
var fs = require('fs'); var userController = require(config.root + '/controllers/users'); var trickController = require(config.root + '/controllers/tricks'); var API = {} API.tricks = require(config.root + '/controllers/API/tricks'); API.Uploader = require(config.root + '/controllers/API/uploader'); API.Users = requi...
var config = require('../config/config'); var passport = require('passport'); var lodash = require('lodash') var Auth = require(config.root + '/middleware/authorization');
random_line_split
slice.js
var B = require('../').Buffer var test = require('tape') if (process.env.OBJECT_IMPL) B.TYPED_ARRAY_SUPPORT = false test('modifying buffer created by .slice() modifies original memory', function (t) { if (!B._useTypedArrays) return t.end() var buf1 = new B(26) for (var i = 0 ; i < 26 ; i++) { buf1[i] = i +...
var buf2 = buf1.slice(0, 3) t.equal(buf2.toString('ascii', 0, buf2.length), 'abc') buf1[0] = '!'.charCodeAt(0) t.equal(buf2.toString('ascii', 0, buf2.length), '!bc') t.end() })
{ buf1[i] = i + 97 // 97 is ASCII a }
conditional_block
slice.js
var B = require('../').Buffer var test = require('tape') if (process.env.OBJECT_IMPL) B.TYPED_ARRAY_SUPPORT = false test('modifying buffer created by .slice() modifies original memory', function (t) { if (!B._useTypedArrays) return t.end() var buf1 = new B(26) for (var i = 0 ; i < 26 ; i++) { buf1[i] = i +...
buf2[0] = '!'.charCodeAt(0) t.equal(buf1.toString('ascii', 0, buf2.length), '!bc') t.end() }) test('modifying parent buffer modifies .slice() buffer\'s memory', function (t) { if (!B._useTypedArrays) return t.end() var buf1 = new B(26) for (var i = 0 ; i < 26 ; i++) { buf1[i] = i + 97 // 97 is ASCII ...
var buf2 = buf1.slice(0, 3) t.equal(buf2.toString('ascii', 0, buf2.length), 'abc')
random_line_split
response.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import json import datetime import mimetypes import os import frappe from frappe import _ import frappe.model.document import frappe.utils import frappe.sessions import werkzeug.u...
def download_backup(path): try: frappe.only_for(("System Manager", "Administrator")) except frappe.PermissionError: raise Forbidden(_("You need to be logged in and have System Manager Role to be able to access backups.")) return send_private_file(path) def send_private_file(path): path = os.path.join(frappe...
return werkzeug.utils.redirect(frappe.response.location)
identifier_body
response.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import json import datetime import mimetypes import os import frappe from frappe import _ import frappe.model.document import frappe.utils import frappe.sessions import werkzeug.u...
(): response = Response("""<html> <body style="background-color: #EEE;"> <h3 style="width: 900px; background-color: #FFF; border: 2px solid #AAA; padding: 20px; font-family: Arial; margin: 20px auto"> Updating. We will be back in a few moments... </h3> </body> ...
handle_session_stopped
identifier_name
response.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import json import datetime import mimetypes import os import frappe from frappe import _ import frappe.model.document import frappe.utils import frappe.sessions import werkzeug.u...
response.data = json.dumps(frappe.local.response, default=json_handler, separators=(',',':')) return response def make_logs(response = None): """make strings for msgprint and errprint""" if not response: response = frappe.local.response if frappe.error_log: # frappe.response['exc'] = json.dumps("\n".join([cs...
del frappe.local.response['http_status_code'] response.headers[b"Content-Type"] = b"application/json; charset: utf-8"
random_line_split
response.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import json import datetime import mimetypes import os import frappe from frappe import _ import frappe.model.document import frappe.utils import frappe.sessions import werkzeug.u...
elif isinstance(obj, frappe.model.document.BaseDocument): doc = obj.as_dict(no_nulls=True) return doc else: raise TypeError, """Object of type %s with value of %s is not JSON serializable""" % \ (type(obj), repr(obj)) def as_page(): """print web page""" from frappe.website.render import render return r...
return unicode(obj)
conditional_block
gutters.tsx
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ // Manage codemirror gutters that highlight latex typesetting issues. // // NOTE: If there are multiple errors/warnings/etc., on the SAME line, only the last // one gets a gutt...
ts: { log: IProcessedLatexLog; set_gutter: Function; }): void { for (const group of ["typesetting", "warnings", "errors"]) { // errors last so always shown if multiple issues on a single line! let item: Error; for (item of opts.log[group]) { if (!item.file) continue; if (item.line == null)...
ate_gutters(op
identifier_name
gutters.tsx
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ // Manage codemirror gutters that highlight latex typesetting issues. // // NOTE: If there are multiple errors/warnings/etc., on the SAME line, only the last // one gets a gutt...
// NOTE/BUG: despite allow_touch true below, this still does NOT work on my iPad -- we see the icon, but nothing // happens when clicking on it; this may be a codemirror issue. return ( <Tip title={message} tip={content} placement={"right"} icon={spec.icon} stable={true} popo...
content = message; message = capitalize(level); }
conditional_block
gutters.tsx
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ // Manage codemirror gutters that highlight latex typesetting issues. // // NOTE: If there are multiple errors/warnings/etc., on the SAME line, only the last // one gets a gutt...
); }
allow_touch={true} > <Icon name={spec.icon} style={{ color: spec.color, cursor: "pointer" }} /> </Tip>
random_line_split
gutters.tsx
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ // Manage codemirror gutters that highlight latex typesetting issues. // // NOTE: If there are multiple errors/warnings/etc., on the SAME line, only the last // one gets a gutt...
unction component( level: string, message: string, content: string | undefined ) { const spec: SpecItem = SPEC[level]; if (content === undefined) { content = message; message = capitalize(level); } // NOTE/BUG: despite allow_touch true below, this still does NOT work on my iPad -- we see the icon,...
for (const group of ["typesetting", "warnings", "errors"]) { // errors last so always shown if multiple issues on a single line! let item: Error; for (item of opts.log[group]) { if (!item.file) continue; if (item.line == null) { /* no gutter mark in a line if there is no line number, e....
identifier_body
__init__.py
# coding=utf-8 # Copyright 2020 Google LLC.. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing p...
# 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 #
random_line_split
last_modified.rs
use header::HttpDate; header! { #[doc="`Last-Modified` header, defined in [RFC7232](http://tools.ietf.org/html/rfc7232#section-2.2)"] #[doc=""] #[doc="The `Last-Modified` header field in a response provides a timestamp"] #[doc="indicating the date and time at which the origin server believes the"] ...
bench_header!(imf_fixdate, LastModified, { vec![b"Sun, 07 Nov 1994 08:48:37 GMT".to_vec()] }); bench_header!(rfc_850, LastModified, { vec![b"Sunday, 06-Nov-94 08:49:37 GMT".to_vec()] }); bench_header!(asctime, LastModified, { vec![b"Sun Nov 6 08:49:37 1994".to_vec()] });
#[doc="```"] (LastModified, "Last-Modified") => [HttpDate] }
random_line_split
p12_integer_to_roman.py
# author: Fei Gao # # Integer To Roman # # Given an integer, convert it to a roman numeral. # Input is guaranteed to be within the range from 1 to 3999. class
: # @return a string def intToRoman(self, n): roman_numeral_map = ( ('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX',...
Solution
identifier_name
p12_integer_to_roman.py
# author: Fei Gao # # Integer To Roman #
# @return a string def intToRoman(self, n): roman_numeral_map = ( ('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9...
# Given an integer, convert it to a roman numeral. # Input is guaranteed to be within the range from 1 to 3999. class Solution:
random_line_split
p12_integer_to_roman.py
# author: Fei Gao # # Integer To Roman # # Given an integer, convert it to a roman numeral. # Input is guaranteed to be within the range from 1 to 3999. class Solution: # @return a string def intToRoman(self, n): roman_numeral_map = ( ('M', 1000), ('CM', 900), ('D'...
if __name__ == '__main__': main() pass
solver = Solution() tests = [] for test in tests: print(test) print(' ->') result = solver.intToRoman(test) print(result) print('~'*10) pass
identifier_body
p12_integer_to_roman.py
# author: Fei Gao # # Integer To Roman # # Given an integer, convert it to a roman numeral. # Input is guaranteed to be within the range from 1 to 3999. class Solution: # @return a string def intToRoman(self, n): roman_numeral_map = ( ('M', 1000), ('CM', 900), ('D'...
return result def main(): solver = Solution() tests = [] for test in tests: print(test) print(' ->') result = solver.intToRoman(test) print(result) print('~'*10) pass if __name__ == '__main__': main() pass
result += numeral n -= integer
conditional_block
_placelist.py
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2007-2008 Brian G. Matherly # Copyright (C) 2008 Gary Burton # # 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 v...
""" :param label: A label to be applied to this option. Example: "Places" :type label: string :param value: A set of GIDs as initial values for this option. Example: "111 222 333 444" :type value: string :return: nothing """ Option.__init__...
identifier_body
_placelist.py
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2007-2008 Brian G. Matherly
# # 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 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # ...
# Copyright (C) 2008 Gary Burton
random_line_split
_placelist.py
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2007-2008 Brian G. Matherly # Copyright (C) 2008 Gary Burton # # 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 v...
(Option): """ This class describes a widget that allows multiple places from the database to be selected. """ def __init__(self, label): """ :param label: A label to be applied to this option. Example: "Places" :type label: string :param value: A set of G...
PlaceListOption
identifier_name
IPipelineStep.ts
/** * Interface for pipeline steps. */ import { IFileSystem } from "unitejs-framework/dist/interfaces/IFileSystem"; import { ILogger } from "unitejs-framework/dist/interfaces/ILogger"; import { UniteConfiguration } from "../configuration/models/unite/uniteConfiguration"; import { EngineVariables } from "../engine/eng...
engineVariables: EngineVariables, mainCondition: boolean): Promise<number>; }
fileSystem: IFileSystem, uniteConfiguration: UniteConfiguration,
random_line_split
shBrushCSharp.js
;(function() { // CommonJS SyntaxHighlighter = SyntaxHighlighter || (typeof require !== 'undefined'? require('shCore').SyntaxHighlighter : null); function Brush() { var keywords = 'abstract as base bool break byte case catch char checked class const ' + 'continue decimal default delegate do double else enu...
this.regexList = [ { regex: SyntaxHighlighter.regexLib.singleLineCComments, func : fixComments }, // one line comments { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments { regex: /@"(?:[^"]|"")*"/g, css: 'string' }, // @-quoted strings { regex: ...
{ var css = (match[0].indexOf("///") == 0) ? 'color1' : 'comments' ; return [new SyntaxHighlighter.Match(match[0], match.index, css)]; }
identifier_body
shBrushCSharp.js
;(function() { // CommonJS SyntaxHighlighter = SyntaxHighlighter || (typeof require !== 'undefined'? require('shCore').SyntaxHighlighter : null); function Brush() { var keywords = 'abstract as base bool break byte case catch char checked class const ' + 'continue decimal default delegate do double else enu...
(match, regexInfo) { var css = (match[0].indexOf("///") == 0) ? 'color1' : 'comments' ; return [new SyntaxHighlighter.Match(match[0], match.index, css)]; } this.regexList = [ { regex: SyntaxHighlighter.regexLib.singleLineCComments, func : fixComments }, // one line comments { regex: ...
fixComments
identifier_name
shBrushCSharp.js
;(function() { // CommonJS
function Brush() { var keywords = 'abstract as base bool break byte case catch char checked class const ' + 'continue decimal default delegate do double else enum event explicit volatile ' + 'extern false finally fixed float for foreach get goto if implicit in int ' + 'interface internal is lock ...
SyntaxHighlighter = SyntaxHighlighter || (typeof require !== 'undefined'? require('shCore').SyntaxHighlighter : null);
random_line_split
_tensorflow.py
""" Module containing functions to differentiate functions using tensorflow. """ try: import tensorflow as tf from tensorflow.python.ops.gradients import _hessian_vector_product except ImportError: tf = None from ._backend import Backend, assert_backend_available class TensorflowBackend(Backend): def...
return hess
feed_dict = {i: d for i, d in zip(argument+argA, x+a)} return self._session.run(tfhess, feed_dict)
identifier_body
_tensorflow.py
""" Module containing functions to differentiate functions using tensorflow. """ try: import tensorflow as tf from tensorflow.python.ops.gradients import _hessian_vector_product except ImportError: tf = None from ._backend import Backend, assert_backend_available class TensorflowBackend(Backend): def...
for arg in argument])): raise ValueError( "Tensorflow backend requires an argument (or sequence of " "arguments) with respect to which compilation is to be " "carried out") return True return False ...
def is_compatible(self, objective, argument): if isinstance(objective, tf.Tensor): if (argument is None or not isinstance(argument, tf.Variable) and not all([isinstance(arg, tf.Variable)
random_line_split
_tensorflow.py
""" Module containing functions to differentiate functions using tensorflow. """ try: import tensorflow as tf from tensorflow.python.ops.gradients import _hessian_vector_product except ImportError: tf = None from ._backend import Backend, assert_backend_available class TensorflowBackend(Backend): def...
(x, a): feed_dict = {argument: x, argA: a} return self._session.run(tfhess[0], feed_dict) else: argA = [tf.Variable(tf.zeros(tf.shape(arg))) for arg in argument] tfhess = _hessian_vector_product(objective, argument, argA) ...
hess
identifier_name
_tensorflow.py
""" Module containing functions to differentiate functions using tensorflow. """ try: import tensorflow as tf from tensorflow.python.ops.gradients import _hessian_vector_product except ImportError: tf = None from ._backend import Backend, assert_backend_available class TensorflowBackend(Backend): def...
return True return False @assert_backend_available def compile_function(self, objective, argument): if not isinstance(argument, list): def func(x): feed_dict = {argument: x} return self._session.run(objective, feed_dict) else: ...
raise ValueError( "Tensorflow backend requires an argument (or sequence of " "arguments) with respect to which compilation is to be " "carried out")
conditional_block
secrets.ts
import * as _ from 'lodash'; import * as AWS from 'aws-sdk'; import * as config from './config'; export interface Secrets { REDDIT_CLIENT_ID: string; REDDIT_CLIENT_TOKEN: string; REDDIT_USERNAME: string; REDDIT_PASSWORD: string; STEAM_API_KEY: string; } export async function resolve(): Promise<Secrets> { ...
const kms = new AWS.KMS({ region: 'us-west-2', }); console.log('Resolving secrets.'); const secrets = await kms.decrypt({ CiphertextBlob: Buffer.from(process.env.SECRETS, 'base64'), }).promise(); return JSON.parse(secrets.Plaintext.toString()); }
{ console.info('Getting secrets from ENV instead of encrypted bundle.'); return _.pick(process.env, [ 'REDDIT_CLIENT_ID', 'REDDIT_CLIENT_TOKEN', 'REDDIT_PASSWORD', 'STEAM_API_KEY', ]) as any; }
conditional_block