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
lexer.js
/** Copyright 2013-2020 the original author or authors from the JHipster project. * * This file is part of the JHipster project, see http://www.jhipster.tech/ * for more information. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the Licen...
(config) { const newToken = createTokenFromConfigCreator(config); tokens[config.name] = newToken; return newToken; } // Some categories to make the grammar easier to read const BOOLEAN = createTokenFromConfig({ name: 'BOOLEAN', pattern: Lexer.NA, }); // Category for the Application Configuration k...
createTokenFromConfig
identifier_name
AnalyzeCoreV2.js
* MS_1_HOUR; class AnalyzeCoreV2 { static get GroupBy() { return GROUP_BY; } /** * @param {CachedDataFileReader} fileReader */
(fileReader) { this.exception = Exception.create(); //a filter function be generate from #setFilter rules this.filterFunction = generateFilterFunction({}); //a group by rules object be generate from #setGroupBy this.groupByRules = convertGroupRulesNumberToObject(0); //analyze timestamp range [new Date(xxx...
constructor
identifier_name
AnalyzeCoreV2.js
[new Date(xxxx,xx,xx,0,0,0).getTime(), new Date(xxxx,xx,xx,23,59,59).getTime()] this.analyzeTimestampRange = [0, 0]; //projects this.projects = []; //analyze result object this.resultObject = getBaseResultObject(); this.definedString = DefinedString.create(); this.reader = fileReader; } //#region A...
let version = lines[0].trim(); if (SUPPORT_VERSION.indexOf(version) == -1) throw new Error(`${fileName} with unsupported version: ${lines[0]}`);
random_line_split
AnalyzeCoreV2.js
// get all existed files map const existedFiles = new Set(); /** @type {string[]} */ let projectsArray = []; /** @type {string[][]} */ const lines = []; /** @type {number[]} */ const startTimes = []; /** @type {number[]} */ const howLongs = []; let lineCount = 0; return fs.readdir(this.reader.g...
{ let line = lines[lineNo].trim(); if (line.startsWith('#')) continue; if (line.startsWith('d')) { if (!this.definedString.addDefiningLine(line)) throw new Error(`${fileName}#${String(lineNo+1)} defining line is invalid`); continue; } //If it is a empty line, just ignore if ...
conditional_block
AnalyzeCoreV2.js
V2#analyze /** * @param {Date} start * @param {Date} end * @returns {Promise} */ analyze(start, end) { // set analyzeTimestamp range this.analyzeTimestampRange = [start.getTime(), end.getTime()]; this.resultObject = getBaseResultObject(); // date loop cursor let dateIterator = new Date(start.getTim...
{ const [analyzeFrom, analyzeTo] = this.analyzeTimestampRange; return this.reader.readFile(fileName).then(content => { let lines = content.split(SPLIT_LINE); if (lines.length == 0) throw new Error(`${fileName} is empty!`); let version = lines[0].trim(); if (SUPPORT_VERSION.indexOf(version) == -1) ...
identifier_body
common.ts
import {DebugElement} from '@angular/core'; import {TestBed, ComponentFixture} from '@angular/core/testing'; import {Key} from '../util/key'; export function createGenericTestComponent<T>( html: string, type: {new (...args: any[]): T}, detectChanges = true): ComponentFixture<T> { TestBed.overrideComponent(type...
if (ua.indexOf('Firefox/') > 0) { return 'firefox'; } throw new Error('Browser detection failed for: ' + ua); } export function isBrowser(browsers: Browser | Browser[], ua = window.navigator.userAgent) { let browsersStr = Array.isArray(browsers) ? (browsers as Browser[]).map(x => x.toString()) : [browsers...
return 'safari'; } // Firefox
random_line_split
common.ts
import {DebugElement} from '@angular/core'; import {TestBed, ComponentFixture} from '@angular/core/testing'; import {Key} from '../util/key'; export function createGenericTestComponent<T>( html: string, type: {new (...args: any[]): T}, detectChanges = true): ComponentFixture<T> { TestBed.overrideComponent(type...
return 'chrome'; } // Safari if (ua.indexOf('Safari/') > 0) { return 'safari'; } // Firefox if (ua.indexOf('Firefox/') > 0) { return 'firefox'; } throw new Error('Browser detection failed for: ' + ua); } export function isBrowser(browsers: Browser | Browser[], ua = window.navigator.user...
{ // IE < 11 const msie = ua.indexOf('MSIE '); if (msie > 0) { return 'ie' + parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10); } // IE 11 if (ua.indexOf('Trident/') > 0) { let rv = ua.indexOf('rv:'); return 'ie' + parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10); } // Edg...
identifier_body
common.ts
import {DebugElement} from '@angular/core'; import {TestBed, ComponentFixture} from '@angular/core/testing'; import {Key} from '../util/key'; export function createGenericTestComponent<T>( html: string, type: {new (...args: any[]): T}, detectChanges = true): ComponentFixture<T> { TestBed.overrideComponent(type...
(browsers: Browser | Browser[], ua = window.navigator.userAgent) { let browsersStr = Array.isArray(browsers) ? (browsers as Browser[]).map(x => x.toString()) : [browsers.toString()]; let browser = getBrowser(ua); if (browsersStr.indexOf('ie') > -1 && browser.startsWith('ie')) { return true; } else { re...
isBrowser
identifier_name
common.ts
import {DebugElement} from '@angular/core'; import {TestBed, ComponentFixture} from '@angular/core/testing'; import {Key} from '../util/key'; export function createGenericTestComponent<T>( html: string, type: {new (...args: any[]): T}, detectChanges = true): ComponentFixture<T> { TestBed.overrideComponent(type...
// Edge if (ua.indexOf('Edge/') > 0) { return 'edge'; } // Chrome if (ua.indexOf('Chrome/') > 0) { return 'chrome'; } // Safari if (ua.indexOf('Safari/') > 0) { return 'safari'; } // Firefox if (ua.indexOf('Firefox/') > 0) { return 'firefox'; } throw new Error('Browser de...
{ let rv = ua.indexOf('rv:'); return 'ie' + parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10); }
conditional_block
options.js
var path = require( 'path' ); module.exports = { pkgJSONPath: path.resolve( __dirname, '../package.json' ), configFile: { //defaultName: 'package.json', //pathToLocalConfig: path.resolve( __dirname, '../configs/bundly.json' ), description: 'Path to your `ico-mixins` config. This can be used to specify ...
} ] } };
alias: 't', type: 'String', dependsOn: 'config', description: 'The name of the target to execute from all the posible targets'
random_line_split
book.component.ts
import { Component, OnInit, Input } from '@angular/core'; import { Router, ActivatedRoute, ROUTER_DIRECTIVES } from '@angular/router'; import { AuthenticationService } from '../../../shared/authentication.service'; import { CartService } from '../../../cart/shared/cart.service'; import { Book } from '../../shared/book...
implements OnInit { @Input() book: Book; private categoryId: number; private auth: string; private options: any; private userId: string; constructor( private authenticationService: AuthenticationService, private cartService: CartService, private route: ActivatedRoute, private router: Route...
BookComponent
identifier_name
book.component.ts
import { Component, OnInit, Input } from '@angular/core'; import { Router, ActivatedRoute, ROUTER_DIRECTIVES } from '@angular/router'; import { AuthenticationService } from '../../../shared/authentication.service';
selector: 'bfy-book', templateUrl: 'book.component.html', styleUrls: ['book.component.css'], directives: [ROUTER_DIRECTIVES], providers: [AuthenticationService, CartService] }) export class BookComponent implements OnInit { @Input() book: Book; private categoryId: number; private auth: string; private...
import { CartService } from '../../../cart/shared/cart.service'; import { Book } from '../../shared/book.model'; @Component({ moduleId: module.id,
random_line_split
main.py
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, an open source suite of business apps # This module copyright (C) 2015 bloopark systems (<http://bloopark.de>). # # This program is free software: you can redistribute it and/or modify # it under the terms o...
lang = env['res.lang'].get_code_from_alias(lang) domain = [('url', '=', seo_url), ('lang', '=', lang)] data = env['website.seo.redirect'].search(domain) if data: model, rid = data[0].resource.split(',') resource = env[model].browse(int(rid)) return re...
lang = request.website.default_lang_code
conditional_block
main.py
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, an open source suite of business apps # This module copyright (C) 2015 bloopark systems (<http://bloopark.de>). # # This program is free software: you can redistribute it and/or modify # it under the terms o...
(self, seo_url, **kwargs): """Handle SEO urls for ir.ui.views. ToDo: Add additional check for field seo_url_parent. Otherwise it is possible to use invalid url structures. For example: if you have two pages 'study-1' and 'study-2' with the same seo_url_level and different seo_ur...
path_page
identifier_name
main.py
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, an open source suite of business apps # This module copyright (C) 2015 bloopark systems (<http://bloopark.de>). # # This program is free software: you can redistribute it and/or modify # it under the terms o...
view = request.website.get_template(page) if view.seo_url: return request.redirect(view.get_seo_path()[0], code=301) except: pass return super(Website, self).page(page, **opt) @http.route(['/website/seo_suggest'], type='json', auth='user', website...
@http.route() def page(self, page, **opt): try:
random_line_split
main.py
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, an open source suite of business apps # This module copyright (C) 2015 bloopark systems (<http://bloopark.de>). # # This program is free software: you can redistribute it and/or modify # it under the terms o...
@http.route(['/website/seo_suggest'], type='json', auth='user', website=True) def seo_suggest(self, keywords=None, lang=None): url = "http://google.com/complete/search" try: params = { 'ie': 'utf8', 'oe': 'utf8', 'output': 'toolbar', ...
try: view = request.website.get_template(page) if view.seo_url: return request.redirect(view.get_seo_path()[0], code=301) except: pass return super(Website, self).page(page, **opt)
identifier_body
SearchLayoutButton.js
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { settings } from 'carbon-components'; import ListBullet...
() { const { labelText, iconDescriptionList, iconDescriptionGrid } = this.props; const SearchLayoutButtonIcon = () => { if (this.state.format === 'list') { return ( <ListBulleted16 className={`${prefix}--search-view`} aria-label={iconDescriptionList} /> ...
render
identifier_name
SearchLayoutButton.js
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { settings } from 'carbon-components'; import ListBullet...
} } export default SearchLayoutButton;
<SearchLayoutButtonIcon /> </div> </button> );
random_line_split
SearchLayoutButton.js
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { settings } from 'carbon-components'; import ListBullet...
}); }; render() { const { labelText, iconDescriptionList, iconDescriptionGrid } = this.props; const SearchLayoutButtonIcon = () => { if (this.state.format === 'list') { return ( <ListBulleted16 className={`${prefix}--search-view`} aria-label={iconDescrip...
{ onChangeFormat({ format }); }
conditional_block
SearchLayoutButton.js
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { settings } from 'carbon-components'; import ListBullet...
className={`${prefix}--search-button`} type="button" onClick={this.toggleLayout} aria-label={labelText} title={labelText}> <div className={`${prefix}--search__toggle-layout__container`}> <SearchLayoutButtonIcon /> </div> </button> ); } } ex...
{ const { labelText, iconDescriptionList, iconDescriptionGrid } = this.props; const SearchLayoutButtonIcon = () => { if (this.state.format === 'list') { return ( <ListBulleted16 className={`${prefix}--search-view`} aria-label={iconDescriptionList} /> ...
identifier_body
app.js
// Module dependencies. var express = require('express'); var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var app = module.exports = express(); app.set('port', process.env.PORT ||...
// production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); app.use('/', routes.index); var server = app.listen(app.get('port'), function(){ console.log('Express serv...
{ app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); }
conditional_block
app.js
// Module dependencies. var express = require('express'); var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var app = module.exports = express(); app.set('port', process.env.PORT ||...
// will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, re...
/// error handlers // development error handler
random_line_split
template.py
#!/usr/bin/env python # encoding: utf-8 import mistune from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import html from flask import current_app, render_template from application.models.system import site from application.services.system import has base_env = { ...
def render_theme_template(template, **kwargs): kwargs.update(base_env) return render_template(template, **kwargs) def format_markdown(mdstr): render = HighlightRenderer() markdown = mistune.Markdown(renderer=render) return markdown(mdstr)
def block_code(self, code, lang_desc): if not lang_desc: return '\n<pre><code>%s</code></pre>\n' % \ mistune.escape(code) lang_split = lang_desc.split(":") lang = lang_split[0] lexer = get_lexer_by_name(lang, stripall=True) formatter = html.HtmlFormatt...
identifier_body
template.py
#!/usr/bin/env python # encoding: utf-8 import mistune from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import html from flask import current_app, render_template from application.models.system import site from application.services.system import has base_env = { ...
(mdstr): render = HighlightRenderer() markdown = mistune.Markdown(renderer=render) return markdown(mdstr)
format_markdown
identifier_name
template.py
#!/usr/bin/env python # encoding: utf-8 import mistune from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import html from flask import current_app, render_template from application.models.system import site from application.services.system import has base_env = { ...
}, '_': lambda x: x, 'i18n': lambda x, y, z: y, 'mobile_meta': lambda: '', 'get_resource': lambda x: '', } class HighlightRenderer(mistune.Renderer): def block_code(self, code, lang_desc): if not lang_desc: return '\n<pre><code>%s</code></pre>\n' % \ mistune...
'category': { 'join': lambda x: '',
random_line_split
template.py
#!/usr/bin/env python # encoding: utf-8 import mistune from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import html from flask import current_app, render_template from application.models.system import site from application.services.system import has base_env = { ...
lang_split = lang_desc.split(":") lang = lang_split[0] lexer = get_lexer_by_name(lang, stripall=True) formatter = html.HtmlFormatter( linenos=True, style=current_app.config.get("HIGHLIGHT_STYLE", "default")) return highlight(code, lexer, formatter) def ...
return '\n<pre><code>%s</code></pre>\n' % \ mistune.escape(code)
conditional_block
jquery.effects.drop.min.js
/* * jQuery UI Effects Drop 1.8.12 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Drop * * Depends: * jquery.effects.core.js */
"show"?1:0};i[f]=(e=="show"?b=="pos"?"+=":"-=":b=="pos"?"-=":"+=")+g;a.animate(i,{queue:false,duration:d.duration,easing:d.options.easing,complete:function(){e=="hide"&&a.hide();c.effects.restore(a,h);c.effects.removeWrapper(a);d.callback&&d.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery);
(function(c){c.effects.drop=function(d){return this.queue(function(){var a=c(this),h=["position","top","bottom","left","right","opacity"],e=c.effects.setMode(a,d.options.mode||"hide"),b=d.options.direction||"left";c.effects.save(a,h);a.show();c.effects.createWrapper(a);var f=b=="up"||b=="down"?"top":"left";b=b=="up"||b...
random_line_split
vnode-utils.ts
/* * Copyright (C) 2017 TypeFox and others. * * 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 */ import { VNode } from "snabbdom/vnode"; import { ...
(vnode: VNode) { if (!vnode.data) vnode.data = {}; return vnode.data; } function getClass(vnode: VNode) { const data = getData(vnode); if (!data.class) data.class = {}; return data.class; } function getOn(vnode: VNode) { const data = getData(vnode); if (!data.on) da...
getData
identifier_name
vnode-utils.ts
/* * Copyright (C) 2017 TypeFox and others. * * 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 */ import { VNode } from "snabbdom/vnode"; import { ...
} export function mergeStyle(vnode: VNode, style: any) { getData(vnode).style = {...(getData(vnode).style || {}), ...style}; } export function on(vnode: VNode, event: string, listener: (model: SModelElement, event: Event) => void, element: SModelElement) { const val = getOn(vnode); if (val[event]) { ...
{ const item = classList.item(i); if (item) setClass(target, item, true); }
conditional_block
vnode-utils.ts
/* * Copyright (C) 2017 TypeFox and others. * * 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 */ import { VNode } from "snabbdom/vnode"; import { ...
export function copyClassesFromVNode(source: VNode, target: VNode) { const classList = getClass(source); for (const c in classList) { if (classList.hasOwnProperty(c)) setClass(target, c, true); } } export function copyClassesFromElement(element: HTMLElement, target: VNode) { const...
{ getClass(vnode)[name] = value; }
identifier_body
vnode-utils.ts
/* * Copyright (C) 2017 TypeFox and others. *
import { VNode } from "snabbdom/vnode"; import { SModelElement } from "../model/smodel"; export function setAttr(vnode: VNode, name: string, value: any) { getAttrs(vnode)[name] = value; } export function setClass(vnode: VNode, name: string, value: boolean) { getClass(vnode)[name] = value; } export function c...
* 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 */
random_line_split
day_4.rs
pub use tdd_kata::string_calc_kata::iter_2::day_4::evaluate; pub use expectest::prelude::be_ok; describe! string_calculator { it "should evaluate integer number" { expect!(evaluate("54357632471")).to(be_ok().value(54357632471.0)); } it "shoould evaluate float number" { expect!(evaluate("...
expect!(evaluate("3245+45.55+567.876-658561.54÷154+4325×25+3534")).to(be_ok().value(111241.05236363637)); } }
random_line_split
TestCommon.py
# vim: ts=4:sw=4:expandtab # BleachBit # Copyright (C) 2008-2020 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # ...
(common.BleachbitTestCase): """Test case for Common.""" def test_expandvars(self): """Unit test for expandvars.""" var = os.path.expandvars('$HOME') self.assertIsString(var) def test_environment(self): """Test for important environment variables""" # useful for rese...
CommonTestCase
identifier_name
TestCommon.py
# vim: ts=4:sw=4:expandtab # BleachBit # Copyright (C) 2008-2020 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # ...
def test_environment(self): """Test for important environment variables""" # useful for researching # grep -Poh "([\\$%]\w+)" cleaners/*xml | cut -b2- | sort | uniq -i envs = {'posix': ['XDG_DATA_HOME', 'XDG_CONFIG_HOME', 'XDG_CACHE_HOME', 'HOME'], 'nt': ['AppData',...
"""Unit test for expandvars.""" var = os.path.expandvars('$HOME') self.assertIsString(var)
identifier_body
TestCommon.py
# vim: ts=4:sw=4:expandtab # BleachBit # Copyright (C) 2008-2020 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # ...
def test_expanduser(self): """Unit test for expanduser.""" # Return Unicode when given Unicode. self.assertIsString(os.path.expanduser('~')) # Blank input should give blank output. self.assertEqual(os.path.expanduser(''), '') # An absolute path should not be alter...
e = os.getenv(env) self.assertIsNotNone(e) self.assertGreater(len(e), 4)
conditional_block
TestCommon.py
# vim: ts=4:sw=4:expandtab # BleachBit # Copyright (C) 2008-2020 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # ...
# An absolute path should not be altered. abs_dirs = {'posix': '$HOME', 'nt': '%USERPROFILE%'} abs_dir = os.path.expandvars(abs_dirs[os.name]) self.assertExists(abs_dir) self.assertEqual(os.path.expanduser(abs_dir), abs_dir) # A relative path (without a reference to the ...
random_line_split
ApplicationStore.js
/** * Copyright 2014, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ 'use strict'; var createStore = require('fluxible/addons').createStore; var routesConfig= require('../configs/routes') var ApplicationStore = createStore({ storeName: 'ApplicationSt...
var pageName = route.config.page; var page = this.pages[pageName]; this.currentPageName = pageName; this.currentPage = page; this.currentRoute = route; this.emitChange(); }, updatePageTitle: function (title) { this.pageTitle = title.pageTitle; t...
{ return; }
conditional_block
ApplicationStore.js
/** * Copyright 2014, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ 'use strict'; var createStore = require('fluxible/addons').createStore; var routesConfig= require('../configs/routes') var ApplicationStore = createStore({ storeName: 'ApplicationSt...
getState: function () { return { currentPageName: this.currentPageName, currentPage: this.currentPage, pages: this.pages, route: this.currentRoute, pageTitle: this.pageTitle }; }, dehydrate: function () { return this.getStat...
}, getPageTitle: function () { return this.pageTitle; },
random_line_split
atbash-cipher.rs
extern crate atbash_cipher as cipher; #[test] fn test_encode_yes() { assert_eq!("bvh", cipher::encode("yes")); } #[test] #[ignore] fn test_encode_no() { assert_eq!("ml", cipher::encode("no")); } #[test] #[ignore] fn test_encode_omg() { assert_eq!("lnt", cipher::encode("OMG")); } #[test] #[ignore] fn tes...
#[test] #[ignore] fn test_encode_deep_thought() { assert_eq!("gifgs rhurx grlm", cipher::encode("Truth is fiction.")); } #[test] #[ignore] fn test_encode_all_the_letters() { assert_eq!("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt", cipher::encode("The quick brown fox jumps over the lazy dog.")); } #[t...
{ assert_eq!("gvhgr mt123 gvhgr mt", cipher::encode("Testing,1 2 3, testing.")); }
identifier_body
atbash-cipher.rs
extern crate atbash_cipher as cipher; #[test] fn test_encode_yes() { assert_eq!("bvh", cipher::encode("yes")); } #[test] #[ignore] fn test_encode_no() { assert_eq!("ml", cipher::encode("no")); } #[test] #[ignore] fn test_encode_omg() { assert_eq!("lnt", cipher::encode("OMG")); } #[test] #[ignore] fn tes...
assert_eq!("gifgs rhurx grlm", cipher::encode("Truth is fiction.")); } #[test] #[ignore] fn test_encode_all_the_letters() { assert_eq!("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt", cipher::encode("The quick brown fox jumps over the lazy dog.")); } #[test] #[ignore] fn test_encode_ignores_non_ascii() { ...
#[test] #[ignore] fn test_encode_deep_thought() {
random_line_split
atbash-cipher.rs
extern crate atbash_cipher as cipher; #[test] fn test_encode_yes() { assert_eq!("bvh", cipher::encode("yes")); } #[test] #[ignore] fn test_encode_no() { assert_eq!("ml", cipher::encode("no")); } #[test] #[ignore] fn test_encode_omg() { assert_eq!("lnt", cipher::encode("OMG")); } #[test] #[ignore] fn tes...
() { assert_eq!("nrmwy oldrm tob", cipher::encode("mindblowingly")); } #[test] #[ignore] fn test_encode_numbers() { assert_eq!("gvhgr mt123 gvhgr mt", cipher::encode("Testing,1 2 3, testing.")); } #[test] #[ignore] fn test_encode_deep_thought() { assert_eq!("gifgs rhurx grlm", cipher::encode("Truth is fic...
test_encode_mindblowingly
identifier_name
decorators.py
from functools import wraps from django.utils.translation import ugettext as _ from django.contrib.admin.forms import AdminAuthenticationForm
from django.contrib.auth.views import login from django.contrib.auth import REDIRECT_FIELD_NAME def staff_member_required(backoffice): def decorate(view_func): """ Decorator for views that checks that the user is logged in and is a staff member, displaying the login page if necessary. ...
random_line_split
decorators.py
from functools import wraps from django.utils.translation import ugettext as _ from django.contrib.admin.forms import AdminAuthenticationForm from django.contrib.auth.views import login from django.contrib.auth import REDIRECT_FIELD_NAME def staff_member_required(backoffice): def decorate(view_func):
return _checklogin return decorate
""" Decorator for views that checks that the user is logged in and is a staff member, displaying the login page if necessary. """ @wraps(view_func) def _checklogin(request, *args, **kwargs): if request.user.is_active and request.user.is_staff: # The us...
identifier_body
decorators.py
from functools import wraps from django.utils.translation import ugettext as _ from django.contrib.admin.forms import AdminAuthenticationForm from django.contrib.auth.views import login from django.contrib.auth import REDIRECT_FIELD_NAME def staff_member_required(backoffice): def decorate(view_func): """ ...
assert hasattr(request, 'session'), "Advanced Reports Backoffice requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'." defaults = { 'template_name': backoffice.login_template, ...
return view_func(request, *args, **kwargs)
conditional_block
decorators.py
from functools import wraps from django.utils.translation import ugettext as _ from django.contrib.admin.forms import AdminAuthenticationForm from django.contrib.auth.views import login from django.contrib.auth import REDIRECT_FIELD_NAME def staff_member_required(backoffice): def
(view_func): """ Decorator for views that checks that the user is logged in and is a staff member, displaying the login page if necessary. """ @wraps(view_func) def _checklogin(request, *args, **kwargs): if request.user.is_active and request.user.is_staff: ...
decorate
identifier_name
createTree.ts
export interface Task { id: number name: string parent?: number } export interface TaskNode extends Task { children?: TaskNode[] } type TaskRepository = { [id: string]: TaskNode } const createTreeInternal = (tree: TaskRepository, task: Task) => { const ref = tree[task.id] = { ...tree[task.id], id:...
return tree } const createTree = (tasks: Task[]) => { const result = tasks.reduce(createTreeInternal, {}) return Object.keys(result).map((key) => result[key]).filter((task) => task.parent == null) } export default createTree
{ const parent = tree[task.parent] = tree[task.parent] || { id: task.parent } parent.children = (parent.children || []).concat(ref) }
conditional_block
createTree.ts
export interface Task { id: number name: string parent?: number } export interface TaskNode extends Task { children?: TaskNode[] } type TaskRepository = { [id: string]: TaskNode } const createTreeInternal = (tree: TaskRepository, task: Task) => {
...tree[task.id], id: task.id, name: task.name, parent: task.parent, } if (task.parent != null) { const parent = tree[task.parent] = tree[task.parent] || { id: task.parent } parent.children = (parent.children || []).concat(ref) } return tree } const createTree = (tasks: Task[]) => { c...
const ref = tree[task.id] = {
random_line_split
power.py
""" a custom layer for 'power', maybe we should implement this in standard way. more info can be found here: http://caffe.berkeleyvision.org/tutorial/layers/power.html """ from .register import register def power_shape(input_shape, shape=None):
def power_layer(input, name, power=1.0, scale=1.0, shift=0.0): """ build a layer of type 'Power' using fluid Args: @input (variables): input fluid variable for this layer @name (str): name for this layer @power (float): parameter from caffe's Power layer @scale (float): parameter fr...
""" calculate the output shape of this layer using input shape Args: @input_shape (list of num): a list of number which represents the input shape Returns: @output_shape (list of num): a list of numbers represent the output shape """ return input_shape
identifier_body
power.py
""" a custom layer for 'power', maybe we should implement this in standard way. more info can be found here: http://caffe.berkeleyvision.org/tutorial/layers/power.html """ from .register import register def power_shape(input_shape, shape=None): """ calculate the output shape of this layer using input shape ...
(input, name, power=1.0, scale=1.0, shift=0.0): """ build a layer of type 'Power' using fluid Args: @input (variables): input fluid variable for this layer @name (str): name for this layer @power (float): parameter from caffe's Power layer @scale (float): parameter from caffe's Power l...
power_layer
identifier_name
power.py
""" a custom layer for 'power', maybe we should implement this in standard way. more info can be found here: http://caffe.berkeleyvision.org/tutorial/layers/power.html """ from .register import register def power_shape(input_shape, shape=None): """ calculate the output shape of this layer using input shape ...
def power_layer(input, name, power=1.0, scale=1.0, shift=0.0): """ build a layer of type 'Power' using fluid Args: @input (variables): input fluid variable for this layer @name (str): name for this layer @power (float): parameter from caffe's Power layer @scale (float): parameter fro...
return input_shape
random_line_split
lib.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library 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 ...
#[macro_use] extern crate libimagstore; extern crate libimagerror; extern crate libimagentryedit; module_entry_path_mod!("notes"); pub mod error; pub mod note; pub mod notestore; pub mod notestoreid; pub mod iter;
#[macro_use] extern crate error_chain; extern crate libimagrt;
random_line_split
utils.py
, tb, msg) return bar = iface.messageBar() # If it's not the main window see if we can find a message bar to report the error in if not window.objectName() == "QgisApp": widgets = window.findChildren(QgsMessageBar) if widgets: # Grab the first message bar for now ...
def _unloadPluginModules(packageName): """ unload plugin package with all its modules (files) """ global _plugin_modules mods = _plugin_modules[packageName] for mod in mods: # if it looks like a Qt resource file, try to do a cleanup # otherwise we might experience a segfault next tim...
""" unload and delete plugin! """ global plugins, active_plugins if packageName not in plugins: return False if packageName not in active_plugins: return False try: plugins[packageName].unload() del plugins[packageName] active_plugins.remove(packageName) ...
identifier_body
utils.py
, tb, msg) return bar = iface.messageBar() # If it's not the main window see if we can find a message bar to report the error in if not window.objectName() == "QgisApp": widgets = window.findChildren(QgsMessageBar) if widgets: # Grab the first message bar for now ...
main_error = lst[-1].decode('utf-8', 'replace') if hasattr(lst[-1], 'decode') else lst[-1] version_label = QCoreApplication.translate('Python', 'Python version:') qgis_label = QCoreApplication.translate('Python', 'QGIS version:') pypath_label = QCoreApplication.translate('Python', 'Python Path:') t...
for s in lst: error += s.decode('utf-8', 'replace') if hasattr(s, 'decode') else s error = error.replace('\n', '<br>')
random_line_split
utils.py
, tb, msg) return bar = iface.messageBar() # If it's not the main window see if we can find a message bar to report the error in if not window.objectName() == "QgisApp": widgets = window.findChildren(QgsMessageBar) if widgets: # Grab the first message bar for now ...
if packageName not in active_plugins: return False try: plugins[packageName].unload() del plugins[packageName] active_plugins.remove(packageName) _unloadPluginModules(packageName) return True except Exception as e: msg = QCoreApplication.translate("P...
return False
conditional_block
utils.py
tb, msg) return bar = iface.messageBar() # If it's not the main window see if we can find a message bar to report the error in if not window.objectName() == "QgisApp": widgets = window.findChildren(QgsMessageBar) if widgets: # Grab the first message bar for now ...
(packageName): """ unload and delete plugin! """ global plugins, active_plugins if packageName not in plugins: return False if packageName not in active_plugins: return False try: plugins[packageName].unload() del plugins[packageName] active_plugins.remove(p...
unloadPlugin
identifier_name
parameters.js
// getPostsParameters gives an object containing the appropriate find and options arguments for the subscriptions's Posts.find() getPostsParameters = function (terms) { var maxLimit = 200; // console.log(terms) // note: using jquery's extend() with "deep" parameter set to true instead of shallow _.ext...
getUsersParameters = function(filterBy, sortBy, limit) { var find = {}, sort = {createdAt: -1}; switch(filterBy){ case 'invited': // consider admins as invited find = {$or: [{isInvited: true}, adminMongoQuery]}; break; case 'uninvited': find = {$and: [{isInvited: f...
// console.log(parameters); return parameters; };
random_line_split
app_part_2_AboutMeEditEntryView_1.js
var AboutMeEditEntryView = Backbone.View.extend({ events: { "click #save": "saveEntry", "click #delete": "deleteEntry", "click #close-success": "closeSuccess" }, render: function() {
deleteEntry: function(){ this.model.destroy(); $(this.el).fadeOut(function(){ $(this).remove(); }); }, saveEntry: function(){ var html = $(this.el); var notif = this.notificationSuccess; this.model.save({title: html.find("#title").val(), body: html.find("#...
$(this.el).html(template.preferencesView.aboutMeEditEntry({title: this.model.get("title"), body:this.model.get("body")})); this.notificationSuccess = $(this.el).find("#notif-success"); return this; },
random_line_split
vprEmulatorPatientModel.js
'use strict'; const _ = require('underscore'); const Handlebars = require('handlebars'); const moment = require('moment'); const VPREmulatorModel = require('./vprEmulatorModel'); const toFMDateTime = require('../vdmUtils').toFMDateTime; class VPRPatientEmulator extends VPREmulatorModel { template() { retu...
} module.exports = VPRPatientEmulator;
{ return `2-${ien}`; }
identifier_body
vprEmulatorPatientModel.js
'use strict'; const _ = require('underscore'); const Handlebars = require('handlebars'); const moment = require('moment'); const VPREmulatorModel = require('./vprEmulatorModel'); const toFMDateTime = require('../vdmUtils').toFMDateTime; class VPRPatientEmulator extends VPREmulatorModel { template() { retu...
}; return map[sex]; }); Handlebars.registerHelper('toGivenName', name => name.substring(name.indexOf(',') + 1, name.length)); Handlebars.registerHelper('getInpatient', () => { if (mvdmForm.currentAdmission) { return 'true'; } ...
Handlebars.registerHelper('toGender', (sex) => { const map = { MALE: 'M', FEMALE: 'F',
random_line_split
vprEmulatorPatientModel.js
'use strict'; const _ = require('underscore'); const Handlebars = require('handlebars'); const moment = require('moment'); const VPREmulatorModel = require('./vprEmulatorModel'); const toFMDateTime = require('../vdmUtils').toFMDateTime; class VPRPatientEmulator extends VPREmulatorModel { template() { retu...
return 'false'; }); Handlebars.registerHelper('getLrdfn', () => { if (_.has(mvdmForm, 'laboratoryReference')) { return mvdmForm.laboratoryReference.id.split('-')[1]; } return 0; }); Handlebars.registerHelper('getFacilitie...
{ return 'true'; }
conditional_block
vprEmulatorPatientModel.js
'use strict'; const _ = require('underscore'); const Handlebars = require('handlebars'); const moment = require('moment'); const VPREmulatorModel = require('./vprEmulatorModel'); const toFMDateTime = require('../vdmUtils').toFMDateTime; class VPRPatientEmulator extends VPREmulatorModel { template() { retu...
(ien) { return `2-${ien}`; } } module.exports = VPRPatientEmulator;
transformIEN
identifier_name
views.py
from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.db.models import Q from django.contrib import messages from cc.general.util import render import cc.ripple.api as ripple from cc.profile.models impo...
@login_required @render() def relationship(request, partner_username): partner = get_object_or_404(Profile, user__username=partner_username) if partner == request.profile: raise Http404 # Can't have relationship with yourself. account = request.profile.account(partner) if account: ent...
accounts = ripple.get_user_accounts(request.profile) return locals()
identifier_body
views.py
from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.db.models import Q from django.contrib import messages from cc.general.util import render import cc.ripple.api as ripple from cc.profile.models impo...
return HttpResponseRedirect( endorsement.recipient.get_absolute_url()) form = EndorseForm(request.POST, instance=endorsement, endorser=request.profile, recipient=recipient) if form.is_valid(): is_new = endorsement is None end...
if request.method == 'POST': if 'delete' in request.POST and endorsement: endorsement.delete() messages.info(request, MESSAGES['endorsement_deleted'])
random_line_split
views.py
from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.db.models import Q from django.contrib import messages from cc.general.util import render import cc.ripple.api as ripple from cc.profile.models impo...
can_ripple = max_amount > 0 profile = recipient # For profile_base.html. return locals() def send_acknowledgement_notification(acknowledgement): subject = _("%s has acknowledged you on Villages.cc") % ( acknowledgement.payer) send_notification(subject, acknowledgement.payer, acknowledgeme...
form = AcknowledgementForm(max_ripple=max_amount, initial=request.GET)
conditional_block
views.py
from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.db.models import Q from django.contrib import messages from cc.general.util import render import cc.ripple.api as ripple from cc.profile.models impo...
(acknowledgement): subject = _("%s has acknowledged you on Villages.cc") % ( acknowledgement.payer) send_notification(subject, acknowledgement.payer, acknowledgement.recipient, 'acknowledgement_notification_email.txt', {'acknowledgement': acknowledgement}) @l...
send_acknowledgement_notification
identifier_name
models.py
from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Category(models.Model): """ Django 要求模型必须继承 models.Model 类。 Category 只需要一个简单的分类名 name 就可以了。 CharField 指定了分类名 name 的数据类型,CharField 是字符型, CharField 的 max_length 参数指定其最大长度,超过这个长度的分类名就不能被存入数据库...
identifier_body
models.py
from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Category(models.Model): """ Django 要求模型必须继承 models.Model 类。 Category 只需要一个简单的分类名 name 就可以了。 CharField 指定了分类名 name 的数据类型,CharField 是字符型, CharField 的 max_length 参数指定其最大长度,超过这个长度的分类名就不能被存入数据库...
return reverse('blog:detail',kwargs={'pk':self.pk}) def increase_views(self): self.views += 1 self.save(update_fields=['views']) class Meta: ordering = ['-created_time']
def __str__(self): return self.title def get_absolute_url(self):
random_line_split
models.py
from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Category(models.Model): """ Django 要求模型必须继承 models.Model 类。 Category 只需要一个简单的分类名 name 就可以了。 CharField 指定了分类名 name 的数据类型,CharField 是字符型, CharField 的 max_length 参数指定其最大长度,超过这个长度的分类名就不能被存入数据库...
identifier_name
libpath.py
# coding: utf-8 """Find the path to picasso dynamic library files.""" import os import platform import sys class PicassoLibraryNotFound(Exception): """Error thrown by when picasso is not found""" pass def find_lib_path(): """Find the path to picasso dynamic library files. :return: List of all found ...
""" curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) dll_path = [os.path.join(curr_path, './lib/')] if sys.platform == 'win32': dll_path = [os.path.join(p, 'picasso.dll') for p in dll_path] \ +[os.path.join(p, 'libpicasso.so') for p in dll_path] ...
random_line_split
libpath.py
# coding: utf-8 """Find the path to picasso dynamic library files.""" import os import platform import sys class PicassoLibraryNotFound(Exception): """Error thrown by when picasso is not found""" pass def find_lib_path(): """Find the path to picasso dynamic library files. :return: List of all found ...
return lib_path
raise PicassoLibraryNotFound( 'Cannot find Picasso Library in the candidate path, ' + 'did you install compilers and make the project in root path?\n' 'List of candidates:\n' + ('\n'.join(dll_path)))
conditional_block
libpath.py
# coding: utf-8 """Find the path to picasso dynamic library files.""" import os import platform import sys class PicassoLibraryNotFound(Exception):
def find_lib_path(): """Find the path to picasso dynamic library files. :return: List of all found library path to picasso :rtype: list(string) """ curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) dll_path = [os.path.join(curr_path, './lib/')] if sys.platform ==...
"""Error thrown by when picasso is not found""" pass
identifier_body
libpath.py
# coding: utf-8 """Find the path to picasso dynamic library files.""" import os import platform import sys class PicassoLibraryNotFound(Exception): """Error thrown by when picasso is not found""" pass def
(): """Find the path to picasso dynamic library files. :return: List of all found library path to picasso :rtype: list(string) """ curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) dll_path = [os.path.join(curr_path, './lib/')] if sys.platform == 'win32': d...
find_lib_path
identifier_name
index.ts
import { Chain, chainsType } from './../types' import mainnet from './mainnet.json' import ropsten from './ropsten.json' import rinkeby from './rinkeby.json' import kovan from './kovan.json' import goerli from './goerli.json' /** * @hidden */ export function _getInitializedChains(customChains?: Chain[]) {
'3': 'ropsten', '4': 'rinkeby', '42': 'kovan', '5': 'goerli', } const chains: any = { mainnet, ropsten, rinkeby, kovan, goerli, } if (customChains) { for (const chain of customChains) { const name = chain.name names[chain.chainId.toString()] = name chain...
const names: any = { '1': 'mainnet',
random_line_split
index.ts
import { Chain, chainsType } from './../types' import mainnet from './mainnet.json' import ropsten from './ropsten.json' import rinkeby from './rinkeby.json' import kovan from './kovan.json' import goerli from './goerli.json' /** * @hidden */ export function
(customChains?: Chain[]) { const names: any = { '1': 'mainnet', '3': 'ropsten', '4': 'rinkeby', '42': 'kovan', '5': 'goerli', } const chains: any = { mainnet, ropsten, rinkeby, kovan, goerli, } if (customChains) { for (const chain of customChains) { const name...
_getInitializedChains
identifier_name
index.ts
import { Chain, chainsType } from './../types' import mainnet from './mainnet.json' import ropsten from './ropsten.json' import rinkeby from './rinkeby.json' import kovan from './kovan.json' import goerli from './goerli.json' /** * @hidden */ export function _getInitializedChains(customChains?: Chain[])
} } chains['names'] = names return chains } /** * @deprecated this constant will be internalized (removed) * on next major version update */ export const chains: chainsType = _getInitializedChains()
{ const names: any = { '1': 'mainnet', '3': 'ropsten', '4': 'rinkeby', '42': 'kovan', '5': 'goerli', } const chains: any = { mainnet, ropsten, rinkeby, kovan, goerli, } if (customChains) { for (const chain of customChains) { const name = chain.name names...
identifier_body
index.ts
import { Chain, chainsType } from './../types' import mainnet from './mainnet.json' import ropsten from './ropsten.json' import rinkeby from './rinkeby.json' import kovan from './kovan.json' import goerli from './goerli.json' /** * @hidden */ export function _getInitializedChains(customChains?: Chain[]) { const na...
chains['names'] = names return chains } /** * @deprecated this constant will be internalized (removed) * on next major version update */ export const chains: chainsType = _getInitializedChains()
{ for (const chain of customChains) { const name = chain.name names[chain.chainId.toString()] = name chains[name] = chain } }
conditional_block
barrier.rs
use std::sync::{Mutex,Condvar,Arc}; use std::thread; struct Barrier { threshold: usize, state: Mutex<BarrierState>, open: Condvar, } impl Barrier { fn new(threshold: usize) -> Self { Barrier { threshold: threshold, open: Condvar::new(), state: Mutex::new(Bar...
} struct ThreadArray { data: [u32; ARRAY_SIZE], increment: u32, } impl ThreadArray { fn new(increment: u32) -> Self { let mut array = ThreadArray { data: [0; ARRAY_SIZE], increment: increment, }; for i in 0..array.data.len() { array.data[i] = (...
{ ThreadContext { array: Mutex::new(ThreadArray::new(increment)), barrier: barrier, } }
identifier_body
barrier.rs
use std::sync::{Mutex,Condvar,Arc}; use std::thread; struct Barrier { threshold: usize, state: Mutex<BarrierState>, open: Condvar, } impl Barrier { fn new(threshold: usize) -> Self { Barrier { threshold: threshold, open: Condvar::new(), state: Mutex::new(Bar...
else { while current_cycle == state.cycle { state = self.open.wait(state).unwrap(); } ret = false; } }, } ret } } struct BarrierState { counter: usize, cycle: bool, valid: b...
{ state.cycle = !state.cycle; state.counter = self.threshold; self.open.notify_all(); ret = true; }
conditional_block
barrier.rs
use std::sync::{Mutex,Condvar,Arc}; use std::thread; struct Barrier { threshold: usize, state: Mutex<BarrierState>, open: Condvar, } impl Barrier { fn new(threshold: usize) -> Self { Barrier { threshold: threshold, open: Condvar::new(), state: Mutex::new(Bar...
(counter: usize) -> Self { BarrierState { counter: counter, cycle: true, valid: true, } } } const ARRAY_SIZE: usize = 6; const THREADS: usize = 5; const OUTLOOPS: usize = 10; const INLOOPS: usize = 1000; struct ThreadContext { array: Mutex<ThreadArray>, ...
new
identifier_name
barrier.rs
use std::sync::{Mutex,Condvar,Arc}; use std::thread; struct Barrier { threshold: usize, state: Mutex<BarrierState>, open: Condvar, } impl Barrier { fn new(threshold: usize) -> Self { Barrier { threshold: threshold, open: Condvar::new(), state: Mutex::new(Bar...
impl ThreadArray { fn new(increment: u32) -> Self { let mut array = ThreadArray { data: [0; ARRAY_SIZE], increment: increment, }; for i in 0..array.data.len() { array.data[i] = (i + 1) as u32; } array } } fn main() { let mut han...
}
random_line_split
recordVideo.js
/** * Created by chenjianjun on 16/2/25. */ var env=require("../../config"); var type=env.Thinky.type; /* { "success": true, "message": null, "data": [ { "id": 227, "recordVideoId": 9, "createTime": "2016-01-21 17:31:09", "updateTime": "2016-01-21 17:31:09", "operater": 1, "isU...
RecordVideo.ensureIndex('weight'); module.exports=RecordVideo;
// 权重 weight: type.number() })
random_line_split
test_enqueue_scheduled_jobs.py
from __future__ import absolute_import, print_function from datetime import timedelta from django.utils import timezone from django.core.exceptions import ValidationError from mock import patch import pytest from sentry.models import ScheduledJob from sentry.models.scheduledjob import schedule_jobs from sentry.testu...
) ] schedule_jobs(job) assert set( ScheduledJob.objects.filter( payload={'foo': 'baz'}, ).values_list('name', flat=True) ) == set( ['sentry.tasks.enqueue_scheduled_jobs', 'sentry.tasks.enqueue_scheduled_jobs_followup'] ...
timezone.now() + timedelta(days=1)
random_line_split
test_enqueue_scheduled_jobs.py
from __future__ import absolute_import, print_function from datetime import timedelta from django.utils import timezone from django.core.exceptions import ValidationError from mock import patch import pytest from sentry.models import ScheduledJob from sentry.models.scheduledjob import schedule_jobs from sentry.testu...
enqueue_scheduled_jobs() assert not ScheduledJob.objects.filter( id=sj.id, ).exists() mock_send_task.assert_called_once_with( 'sentry.tasks.enqueue_scheduled_jobs', kwargs={'foo': 'bar'}, ) def test_schedule_job(self): job = [ ...
def test_does_not_schedule_future_job(self): sj = ScheduledJob.objects.create( name='sentry.tasks.enqueue_scheduled_jobs', payload={'foo': 'baz'}, date_scheduled=timezone.now() + timedelta(days=1), ) enqueue_scheduled_jobs() assert ScheduledJob.objec...
identifier_body
test_enqueue_scheduled_jobs.py
from __future__ import absolute_import, print_function from datetime import timedelta from django.utils import timezone from django.core.exceptions import ValidationError from mock import patch import pytest from sentry.models import ScheduledJob from sentry.models.scheduledjob import schedule_jobs from sentry.testu...
(TestCase): def test_does_not_schedule_future_job(self): sj = ScheduledJob.objects.create( name='sentry.tasks.enqueue_scheduled_jobs', payload={'foo': 'baz'}, date_scheduled=timezone.now() + timedelta(days=1), ) enqueue_scheduled_jobs() assert Sc...
EnqueueScheduledJobsTest
identifier_name
wait.rs
use libc::{self, c_int}; use {Errno, Result}; use unistd::Pid; use sys::signal::Signal; libc_bitflags!( pub struct WaitPidFlag: c_int { WNOHANG; WUNTRACED; #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", tar...
WaitStatus::Stopped(pid, stop_signal(status)) } } } decode_stopped(pid, status) } else { assert!(continued(status)); WaitStatus::Continued(pid) } } pub fn waitpid<P: Into<Option<Pid>>>(pid: P, options: Option<WaitPidFlag>) -> Resu...
{ if exited(status) { WaitStatus::Exited(pid, exit_status(status)) } else if signaled(status) { WaitStatus::Signaled(pid, term_signal(status), dumped_core(status)) } else if stopped(status) { cfg_if! { if #[cfg(any(target_os = "linux", target_os = "android"))] { ...
identifier_body
wait.rs
use libc::{self, c_int}; use {Errno, Result}; use unistd::Pid; use sys::signal::Signal; libc_bitflags!( pub struct WaitPidFlag: c_int { WNOHANG; WUNTRACED; #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", tar...
(status: i32) -> bool { unsafe { libc::WCOREDUMP(status) } } fn stopped(status: i32) -> bool { unsafe { libc::WIFSTOPPED(status) } } fn stop_signal(status: i32) -> Signal { Signal::from_c_int(unsafe { libc::WSTOPSIG(status) }).unwrap() } fn syscall_stop(status: i32) -> bool { // From ptrace(2), setti...
dumped_core
identifier_name
wait.rs
use libc::{self, c_int}; use {Errno, Result}; use unistd::Pid; use sys::signal::Signal; libc_bitflags!( pub struct WaitPidFlag: c_int { WNOHANG; WUNTRACED; #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", tar...
waitpid(None, None) }
random_line_split
newtype-struct-drop-run.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let y = &Cell::new(32); { let _x = Foo(y); } assert_eq!(y.get(), 23); }
identifier_body
newtype-struct-drop-run.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[unsafe_destructor] impl<'a> Drop for Foo<'a> { fn drop(&mut self) { let Foo(i) = *self; i.set(23); } } pub fn main() { let y = &Cell::new(32); { let _x = Foo(y); } assert_eq!(y.get(), 23); }
use std::cell::Cell; struct Foo<'a>(&'a Cell<isize>);
random_line_split
newtype-struct-drop-run.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let y = &Cell::new(32); { let _x = Foo(y); } assert_eq!(y.get(), 23); }
main
identifier_name
sticky.js
(function ($, win, Modernizr, nav, doc) { $.fn.headerToFixed = function (options) { var defaults = { speed : 300, windowWidth : $(win).width(), scrollTop : $(win).scrollTop() }, o = $.extend({}, defaults, options), $this = $(this), $clone = $('#logo').clone(), heightHeader = $this.height(); if (o.windowWidt...
} }; if (objNavMenu.fixed) { if (!Modernizr.touch) { $(win).scroll(function () { $('#header').headerToFixed(); }); } } }(jQuery, window, Modernizr, navigator, document));
}
random_line_split
sticky.js
(function ($, win, Modernizr, nav, doc) { $.fn.headerToFixed = function (options) { var defaults = { speed : 300, windowWidth : $(win).width(), scrollTop : $(win).scrollTop() }, o = $.extend({}, defaults, options), $this = $(this), $clone = $('#logo').clone(), heightHeader = $this.height(); if (o.windowWidt...
} }(jQuery, window, Modernizr, navigator, document));
{ $(win).scroll(function () { $('#header').headerToFixed(); }); }
conditional_block
userController.js
var express = require('express'); var userRouter = express.Router(); var passport = require('passport'); var Model = require('../models/user'); var authenticate = require('./auth'); /* GET all the users */ exports.getAll = function(req, res, next) { Model.Users.forge() .fetch({ columns: ['_id', 'username', '...
var token = authenticate.getToken(user); res.status(200).json({ status: 'Login successful', succes: true, token: token }); }); })(req, res, next); }; /* POST Register. */ exports.signUp = function(req, res, next) { var userData = req.body; Model.User.forge({ ...
{ console.log(err); return res.status(500).json({ error: 'Could not log in user' }); }
conditional_block
userController.js
var express = require('express'); var userRouter = express.Router(); var passport = require('passport'); var Model = require('../models/user'); var authenticate = require('./auth'); /* GET all the users */ exports.getAll = function(req, res, next) { Model.Users.forge() .fetch({ columns: ['_id', 'username', '...
}); }); })(req, res, next); }; /* POST Register. */ exports.signUp = function(req, res, next) { var userData = req.body; Model.User.forge({ username: userData.username }).fetch() //see if user already exists .then(function(user) { if (user) { return res.status(400).json({ ...
token: token
random_line_split
lib.js
/* * Copyright (C) 2014 Camptocamp * * This file is part of MapFish Print * * MapFish Print is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any l...
else { return a.title < b.title ? -1 : 1; } }); return filtered; } }); docsApp.filter('sortRecords', function($translate){ return function (items) { items.sort(function(a,b) { return $translate.instant(a.title) < $translate.instant(b.title) ? -1 : 1; }); return items; }...
{ return a.order < b.order ? -1 : 1; }
conditional_block
lib.js
/* * Copyright (C) 2014 Camptocamp * * This file is part of MapFish Print * * MapFish Print is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any l...
var toTranslate = []; angular.forEach($scope.pages, function (p){ toTranslate.push(p.title) }); $translate(toTranslate).then(function (translations) { angular.forEach($scope.pages, function (p){ var titleKey = p.title; p.title = translations[titleKey]; }); }); ...
$scope.renderHtml = function(html){ return $sce.trustAsHtml($translate.instant(html)); }; var translatePages = function() {
random_line_split
headless.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use compositor_task::{CompositorEventListener, CompositorReceiver, Msg}; use windowing::WindowEvent; use geom::sc...
} true } fn repaint_synchronously(&mut self) {} fn shutdown(&mut self) { // Drain compositor port, sometimes messages contain channels that are blocking // another task from finishing (i.e. SetIds) while self.port.try_recv_compositor_msg().is_some() {} sel...
{}
conditional_block
headless.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use compositor_task::{CompositorEventListener, CompositorReceiver, Msg}; use windowing::WindowEvent; use geom::sc...
} // Explicitly list ignored messages so that when we add a new one, // we'll notice and think about whether it needs a response, like // SetFrameTree. Msg::CreateOrUpdateBaseLayer(..) | Msg::CreateOrUpdateDescendantLayer(..) | Msg::S...
{ match self.port.recv_compositor_msg() { Msg::Exit(chan) => { debug!("shutting down the constellation"); let ConstellationChan(ref con_chan) = self.constellation_chan; con_chan.send(ConstellationMsg::Exit).unwrap(); chan.send(()).unwra...
identifier_body
headless.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use compositor_task::{CompositorEventListener, CompositorReceiver, Msg}; use windowing::WindowEvent; use geom::sc...
(&self) -> f32 { 1.0 } fn get_title_for_main_frame(&self) {} }
pinch_zoom_level
identifier_name
headless.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use compositor_task::{CompositorEventListener, CompositorReceiver, Msg}; use windowing::WindowEvent; use geom::sc...
Msg::CreateOrUpdateDescendantLayer(..) | Msg::SetLayerRect(..) | Msg::AssignPaintedBuffers(..) | Msg::ChangeReadyState(..) | Msg::ChangePaintState(..) | Msg::ChangeRunningAnimationsState(..) | Msg::ScrollFragmentPoint(..) | ...
Msg::CreateOrUpdateBaseLayer(..) |
random_line_split