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
lib.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 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 F...
trivial_numeric_casts, unstable_features, unused_allocation, unused_import_braces, unused_imports, unused_must_use, unused_mut, unused_qualifications, while_true, )] extern crate filters; extern crate chrono; extern crate toml; extern crate toml_query; #[macro_use] extern crate lazy...
path_statements,
random_line_split
DefaultConfig.js
module.exports = { autoRoutesEnabled: true, clusteringEnabled: false, compressionEnabled: true, requestLimitKB: 5120, keepAliveTimeoutSeconds: 30, includeErrorStackInResponse: true, viewEngine: 'ejs', controllerPath: './controllers', controllerSuffix: '-controller', controller...
hooks: require('./Hooks'), internalViewPath: 'views' };
} ],
random_line_split
test_iwords.py
""" Test functions in iwords.py. To run with pytest. """ import os from tempfile import NamedTemporaryFile import iwords def test_get_freqs(): with NamedTemporaryFile() as fp: fp.write(b'Hello world!') fp.flush() assert iwords.get_freqs([fp.name]) == {'hello': 0.5, 'world': 0.5} def te...
fp.flush() assert os.system(f'./iwords.py {fp.name}') == 0 assert os.system(f'./iwords.py {fp.name} --show-score') == 0 assert os.system(f'./iwords.py {fp.name} --limit 1') == 0 assert os.system(f'./iwords.py {fp.name} --learn /usr/share/dict/words') == 0
assert os.system('./iwords.py --help') == 0 with NamedTemporaryFile() as fp: fp.write(b'Hello world!')
random_line_split
test_iwords.py
""" Test functions in iwords.py. To run with pytest. """ import os from tempfile import NamedTemporaryFile import iwords def test_get_freqs(): with NamedTemporaryFile() as fp: fp.write(b'Hello world!') fp.flush() assert iwords.get_freqs([fp.name]) == {'hello': 0.5, 'world': 0.5} def te...
def test_run(): assert os.system('./iwords.py --help') == 0 with NamedTemporaryFile() as fp: fp.write(b'Hello world!') fp.flush() assert os.system(f'./iwords.py {fp.name}') == 0 assert os.system(f'./iwords.py {fp.name} --show-score') == 0 assert os.system(f'./iwords.py...
assert iwords.clean('Cómo estás') == 'como estas'
identifier_body
test_iwords.py
""" Test functions in iwords.py. To run with pytest. """ import os from tempfile import NamedTemporaryFile import iwords def
(): with NamedTemporaryFile() as fp: fp.write(b'Hello world!') fp.flush() assert iwords.get_freqs([fp.name]) == {'hello': 0.5, 'world': 0.5} def test_clean(): assert iwords.clean('Cómo estás') == 'como estas' def test_run(): assert os.system('./iwords.py --help') == 0 with N...
test_get_freqs
identifier_name
xml-fyi.py
#!/usr/bin/env python3 import os import unittest import xml.etree.ElementTree as ET from ietf.sql.base import Base from ietf.sql.fyi import Fyi from ietf.xml.fyi import add_all from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker class TestXmlRfc(unittest.TestCase): data_file = os.path.jo...
(self): # RFC 8180 self.std0002 = self.session.query(Fyi).filter(Fyi.id == 2).one() self.assertIsNone(self.std0002.title) if __name__ == '__main__': unittest.main()
test_title
identifier_name
xml-fyi.py
#!/usr/bin/env python3 import os import unittest import xml.etree.ElementTree as ET from ietf.sql.base import Base from ietf.sql.fyi import Fyi from ietf.xml.fyi import add_all from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker class TestXmlRfc(unittest.TestCase): data_file = os.path.jo...
unittest.main()
conditional_block
xml-fyi.py
#!/usr/bin/env python3 import os import unittest import xml.etree.ElementTree as ET from ietf.sql.base import Base from ietf.sql.fyi import Fyi from ietf.xml.fyi import add_all from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker class TestXmlRfc(unittest.TestCase): data_file = os.path.jo...
self.std0002 = self.session.query(Fyi).filter(Fyi.id == 2).one() self.assertIsNone(self.std0002.title) if __name__ == '__main__': unittest.main()
# RFC 8180
random_line_split
xml-fyi.py
#!/usr/bin/env python3 import os import unittest import xml.etree.ElementTree as ET from ietf.sql.base import Base from ietf.sql.fyi import Fyi from ietf.xml.fyi import add_all from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker class TestXmlRfc(unittest.TestCase): data_file = os.path.jo...
def test_title(self): # RFC 8180 self.std0002 = self.session.query(Fyi).filter(Fyi.id == 2).one() self.assertIsNone(self.std0002.title) if __name__ == '__main__': unittest.main()
self.rows = self.session.query(Fyi).order_by(Fyi.id).all() self.assertEqual(1, len(self.rows))
identifier_body
quickOutline.ts
'vs/base/common/strings'; import { TPromise } from 'vs/base/common/winjs.base'; import { IContext, IHighlight, QuickOpenEntryGroup, QuickOpenModel } from 'vs/base/parts/quickopen/browser/quickOpenModel'; import { IAutoFocus, Mode } from 'vs/base/parts/quickopen/common/quickOpen'; import { ICommonCodeEditor } from 'vs/...
private sortScoped(searchValue: string, elementA: SymbolEntry, elementB: SymbolEntry): number { // Remove scope char searchValue = searchValue.substr(SCOPE_PREFIX.length);
{ let elementAName = elementA.getLabel().toLowerCase(); let elementBName = elementB.getLabel().toLowerCase(); // Compare by name let r = elementAName.localeCompare(elementBName); if (r !== 0) { return r; } // If name identical sort by range instead let elementARange = elementA.getRange(); let ele...
identifier_body
quickOutline.ts
'vs/base/common/strings'; import { TPromise } from 'vs/base/common/winjs.base'; import { IContext, IHighlight, QuickOpenEntryGroup, QuickOpenModel } from 'vs/base/parts/quickopen/browser/quickOpenModel'; import { IAutoFocus, Mode } from 'vs/base/parts/quickopen/common/quickOpen'; import { ICommonCodeEditor } from 'vs/...
currentType = result.getType(); currentResult = result; typeCounter = 1; result.setShowBorder(i > 0); } // Existing type, keep counting else { typeCounter++; } } // Update previous result with count if (currentResult) { currentResult.setGroupLabel(this.typeToLa...
{ currentResult.setGroupLabel(this.typeToLabel(currentType, typeCounter)); }
conditional_block
quickOutline.ts
from 'vs/base/common/strings'; import { TPromise } from 'vs/base/common/winjs.base'; import { IContext, IHighlight, QuickOpenEntryGroup, QuickOpenModel } from 'vs/base/parts/quickopen/browser/quickOpenModel'; import { IAutoFocus, Mode } from 'vs/base/parts/quickopen/common/quickOpen'; import { ICommonCodeEditor } from...
() { super(nls.localize('quickOutlineActionInput', "Type the name of an identifier you wish to navigate to"), { id: 'editor.action.quickOutline', label: nls.localize('QuickOutlineAction.label', "Go to Symbol..."), alias: 'Go to Symbol...', precondition: EditorContextKeys.hasDocumentSymbolProvider, kbOp...
constructor
identifier_name
quickOutline.ts
import { IAutoFocus, Mode } from 'vs/base/parts/quickopen/common/quickOpen'; import { ICommonCodeEditor } from 'vs/editor/common/editorCommon'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { SymbolInformation, DocumentSymbolProviderRegistry, symbolKindToCssClass } from 'vs/editor/commo...
if (r !== 0) { return r;
random_line_split
bitporno.py
''' urlresolver XBMC Addon Copyright (C) 2017 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distribu...
@classmethod def _is_enabled(cls): return True
print "print UR BitPorno self, host, media_id", self,host, media_id print "print return", self._default_get_url(host, media_id, template='http://{host}/?v={media_id}') return self._default_get_url(host, media_id, template='http://{host}/?v={media_id}') return "https://www.bitporno.com/?v=FM11XRJ...
identifier_body
bitporno.py
''' urlresolver XBMC Addon Copyright (C) 2017 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distribu...
(GenericResolver): #print "print UR BitPorno" name = 'BitPorno' domains = ['bitporno.com'] pattern = '(?://|\.)(bitporno\.com)/(?:\?v=|embed/)([a-zA-Z0-9]+)' def get_url(self, host, media_id): print "print UR BitPorno self, host, media_id", self,host, media_id print "print return", ...
BitPornoResolver
identifier_name
bitporno.py
''' urlresolver XBMC Addon Copyright (C) 2017 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distribu...
class BitPornoResolver(GenericResolver): #print "print UR BitPorno" name = 'BitPorno' domains = ['bitporno.com'] pattern = '(?://|\.)(bitporno\.com)/(?:\?v=|embed/)([a-zA-Z0-9]+)' def get_url(self, host, media_id): print "print UR BitPorno self, host, media_id", self,host, media_id ...
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' from urlresolver.plugins.__generic_resolver__ import GenericResolver
random_line_split
home_endpoints.py
# Endpoints for user to control the home. from datetime import datetime from flask import Blueprint, jsonify, request from services import elements_services, home_services home_api = Blueprint('/home_api', __name__) elements_services = elements_services.ElementsServices() home_services = home_services.HomeServices()...
home_services.save_time_rules(rules) return 'OK' @home_api.route('/timerules/<string:hid>') def get_timerules(hid): """Gets list of timerules for given hid""" timerules= home_services.read_time_rules(hid) return jsonify(timerules)
rule['id'] = None
conditional_block
home_endpoints.py
# Endpoints for user to control the home. from datetime import datetime from flask import Blueprint, jsonify, request from services import elements_services, home_services home_api = Blueprint('/home_api', __name__) elements_services = elements_services.ElementsServices() home_services = home_services.HomeServices()...
(): """Updates all elements with all new values received from the user application""" received_elements = request.get_json() home_services.update_elements(received_elements) return 'OK' @home_api.route('/elementdelete', methods=['POST']) def delete_element(): """Deletes a single element with given...
update_elements
identifier_name
home_endpoints.py
# Endpoints for user to control the home. from datetime import datetime from flask import Blueprint, jsonify, request from services import elements_services, home_services home_api = Blueprint('/home_api', __name__) elements_services = elements_services.ElementsServices() home_services = home_services.HomeServices()...
if len(rules) == 0: raise Exception("No elements in the list") for rule in rules: if 'id' not in rule: rule['id'] = None home_services.save_time_rules(rules) return 'OK' @home_api.route('/timerules/<string:hid>') def get_timerules(hid): """Gets list of timerules for gi...
"""Adds, Updates or deletes time rule for the given element""" rules = request.get_json()
random_line_split
home_endpoints.py
# Endpoints for user to control the home. from datetime import datetime from flask import Blueprint, jsonify, request from services import elements_services, home_services home_api = Blueprint('/home_api', __name__) elements_services = elements_services.ElementsServices() home_services = home_services.HomeServices()...
@home_api.route('/element', methods=['POST']) def update_element(): """Updates single element with all new values received from the user application""" received_element = request.get_json() home_services.update_element(received_element) return 'OK' @home_api.route('/elements', methods=['POST']) def...
"""Gets all profiles for all elements for user application to display and manipulate elements""" return jsonify(home_services.get_profiles())
identifier_body
rebaseStatusNode.ts
import { Command, MarkdownString, ThemeColor, ThemeIcon, TreeItem, TreeItemCollapsibleState, Uri } from 'vscode'; import type { DiffWithPreviousCommandArgs } from '../../commands'; import { ViewFilesLayout } from '../../configuration'; import { Commands, CoreCommands } from '../../constants'; import { CommitFormatter }...
(): TreeItem { const item = new TreeItem(`Paused at commit ${this.commit.shortSha}`, TreeItemCollapsibleState.Collapsed); // item.contextValue = ContextValues.RebaseCommit; item.description = CommitFormatter.fromTemplate(`\${message}`, this.commit, { messageTruncateAtNewLine: true, }); item.iconPath = ne...
getTreeItem
identifier_name
rebaseStatusNode.ts
import { Command, MarkdownString, ThemeColor, ThemeIcon, TreeItem, TreeItemCollapsibleState, Uri } from 'vscode'; import type { DiffWithPreviousCommandArgs } from '../../commands'; import { ViewFilesLayout } from '../../configuration'; import { Commands, CoreCommands } from '../../constants'; import { CommitFormatter }...
if (remote?.provider != null) { [autolinkedIssuesOrPullRequests, pr] = await Promise.all([ this.view.container.autolinks.getIssueOrPullRequestLinks( this.commit.message ?? this.commit.summary, remote, ), this.view.container.git.getPullRequestForCommit(this.commit.ref, remote.provider), ])...
} let autolinkedIssuesOrPullRequests; let pr;
random_line_split
rebaseStatusNode.ts
import { Command, MarkdownString, ThemeColor, ThemeIcon, TreeItem, TreeItemCollapsibleState, Uri } from 'vscode'; import type { DiffWithPreviousCommandArgs } from '../../commands'; import { ViewFilesLayout } from '../../configuration'; import { Commands, CoreCommands } from '../../constants'; import { CommitFormatter }...
this.rebaseStatus.steps.current.commit.ref, ); if (commit != null) { children.splice(0, 0, new RebaseCommitNode(this.view, this, commit) as any); } return children; } getTreeItem(): TreeItem { const item = new TreeItem( `${this.status?.hasConflicts ? 'Resolve conflicts to continue rebasing' : 'R...
{ let children: FileNode[] = this.status?.conflicts.map(f => new MergeConflictFileNode(this.view, this, this.rebaseStatus, f)) ?? []; if (this.view.config.files.layout !== ViewFilesLayout.List) { const hierarchy = makeHierarchical( children, n => n.uri.relativePath.split('/'), (...parts: string[]...
identifier_body
rebaseStatusNode.ts
import { Command, MarkdownString, ThemeColor, ThemeIcon, TreeItem, TreeItemCollapsibleState, Uri } from 'vscode'; import type { DiffWithPreviousCommandArgs } from '../../commands'; import { ViewFilesLayout } from '../../configuration'; import { Commands, CoreCommands } from '../../constants'; import { CommitFormatter }...
return item; } private async getTooltip() { const remotes = await this.view.container.git.getRemotesWithProviders(this.commit.repoPath); const remote = await this.view.container.git.getRichRemoteProvider(remotes); if (this.commit.message == null) { await this.commit.ensureFullDetails(); } let autol...
{ item.tooltip = await this.getTooltip(); }
conditional_block
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-06 21:26 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import taggit.managers class
(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('taggit', '0002_auto_20150616_2121'), ] operations = [ migrations.CreateModel( name='Reply', fields=[ ('id', models.AutoF...
Migration
identifier_name
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-06 21:26 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): initial = True dependenci...
], options={ 'verbose_name': 'Resposta', 'verbose_name_plural': 'Respostas', 'ordering': ['-correct', 'created_at'], }, ), migrations.CreateModel( name='Topic', fields=[ ('id', mod...
('updated_at', models.DateTimeField(auto_now=True, verbose_name='Modificado em')), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='replies', to=settings.AUTH_USER_MODEL, verbose_name='Autor')),
random_line_split
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-06 21:26 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration):
'verbose_name_plural': 'Respostas', 'ordering': ['-correct', 'created_at'], }, ), migrations.CreateModel( name='Topic', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name=...
initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('taggit', '0002_auto_20150616_2121'), ] operations = [ migrations.CreateModel( name='Reply', fields=[ ('id', models.AutoField(auto_created=True, prima...
identifier_body
WorkingMemory.py
#!/usr/bin/env python """ TURTLE An expert system shell inspired by CLIPS syntax @author Claudio Greco, Daniele Negro, Marco Di Pietro """ from core.exceptions.Exceptions import EvaluateException from core.typesystem.TypeSystem import BaseType, VariableType from core.entities.Fact import Fact from coll...
del self.__facts[fact] del self.__wmes[identifier] return True # Otherwise, if the Working Memory doesn't contain # a fact with the name equal to the one of the specified fact, # then it doesn't remove any fact from the Working Memory # and it returns...
# with the name qual to the one of the specified fact, # then it removes that fact from the Working Memory # and it returns the boolean value True. if identifier in self.__wmes: fact = self.__wmes[identifier].fact
random_line_split
WorkingMemory.py
#!/usr/bin/env python """ TURTLE An expert system shell inspired by CLIPS syntax @author Claudio Greco, Daniele Negro, Marco Di Pietro """ from core.exceptions.Exceptions import EvaluateException from core.typesystem.TypeSystem import BaseType, VariableType from core.entities.Fact import Fact from coll...
# Otherwise, if the Working Memory already contains # a fact with the name equal to the one of the # specified fact, then it doesn't add any fact # to the Working Memory. else: return None def remove_fact(self, identifier): # If the Working Memory doesn'...
wme = WME(self.__counter, fact) self.__facts[fact] = True self.__wmes[self.__counter] = wme self.__counter += 1 return wme
conditional_block
WorkingMemory.py
#!/usr/bin/env python """ TURTLE An expert system shell inspired by CLIPS syntax @author Claudio Greco, Daniele Negro, Marco Di Pietro """ from core.exceptions.Exceptions import EvaluateException from core.typesystem.TypeSystem import BaseType, VariableType from core.entities.Fact import Fact from coll...
class WorkingMemory(object): """ Class for the representation of a Working Memory. """ def __init__(self): self.__wmes = {} self.__facts = defaultdict(lambda: False) self.__counter = long(1) @property def wmes(self): return self.__wmes def add_fact(self, ...
return str(self.__identifier) + ': ' + str(self.__fact)
identifier_body
WorkingMemory.py
#!/usr/bin/env python """ TURTLE An expert system shell inspired by CLIPS syntax @author Claudio Greco, Daniele Negro, Marco Di Pietro """ from core.exceptions.Exceptions import EvaluateException from core.typesystem.TypeSystem import BaseType, VariableType from core.entities.Fact import Fact from coll...
(self): return self.__wmes def add_fact(self, fact): # If the Working Memory doesn't contain a fact with # the name equal to the one of the specified fact, # then it adds that fact to the Working Memory # and it returns the generated WME. fact.values = [x.content if ...
wmes
identifier_name
play2.js
"use strict"; window.mushroom.state.play2 = { preload: function(){ console.log("loading play2 state"); }, create: function(){ console.log("starting play2 state"); this.game.camera.x = 1800; this.redsea = mt.create("redsea"); this.Pathway2 = mt.create("Pathway2"); this.player=mt.create("weirdmushroo...
/*if(this.score_count == 10){ this.switchLevel(); }*/ }, destroyObject: function(player,coin){ this.score_count +=10; this.score.text = this.score_count; coin.destroy(); }, restartGame: function(){ this.game.state.start("play2"); }, switchLevel: function(){ this.game.state.start("play3"); ...
{ this.player.body.velocity.x = 0; }
conditional_block
play2.js
"use strict"; window.mushroom.state.play2 = { preload: function(){ console.log("loading play2 state"); }, create: function(){ console.log("starting play2 state"); this.game.camera.x = 1800; this.redsea = mt.create("redsea"); this.Pathway2 = mt.create("Pathway2"); this.player=mt.create("weirdmushroo...
this.enemy2.body.velocity.y = 0; } if(this.Lkey.isDown){ this.player.body.velocity.x -= 5; } else if(this.Rkey.isDown){ this.player.body.velocity.x += 5; } else if (this.Ukey.isDown && this.player.body.touching.down ){ this.player.body.velocity.y -=400; } else{ this.playe...
random_line_split
app.module.ts
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent} from './app.component'; import { AuthGuard } from './AuthGuard'; import { LoaderStop } from './providers/loaderstop.service'; // import { ROUTER_PRO...
exports: [], bootstrap : [AppComponent], providers : [AuthGuard, LoaderStop] }) export class AppModule{ }
random_line_split
app.module.ts
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent} from './app.component'; import { AuthGuard } from './AuthGuard'; import { LoaderStop } from './providers/loaderstop.service'; // import { ROUTER_PRO...
{ }
AppModule
identifier_name
moment-date.pipe.ts
// ------------------------------------------------------------------------- // @license Copyright Cardinn Inc. All Rights Reserved. // ------------------------------------------------------------------------- import { Pipe, PipeTransform } from '@angular/core'; import * as moment from 'moment'; /** * 基于 moment 日期格式化...
HH:mm'): string { if (value) { if (formatString === 'fn') return moment(value).fromNow(); return moment(value).format(formatString); } else { return ''; } } }
YYY-MM-DD
identifier_name
moment-date.pipe.ts
// ------------------------------------------------------------------------- // @license Copyright Cardinn Inc. All Rights Reserved. // ------------------------------------------------------------------------- import { Pipe, PipeTransform } from '@angular/core'; import * as moment from 'moment'; /** * 基于 moment 日期格式化...
ing === 'fn') return moment(value).fromNow(); return moment(value).format(formatString); } else { return ''; } } }
identifier_body
moment-date.pipe.ts
// ------------------------------------------------------------------------- // @license Copyright Cardinn Inc. All Rights Reserved. // ------------------------------------------------------------------------- import { Pipe, PipeTransform } from '@angular/core'; import * as moment from 'moment'; /** * 基于 moment 日期格式化...
*/ @Pipe({ name: '_date' }) export class MomentDatePipe implements PipeTransform { transform(value: Date, formatString: string = 'YYYY-MM-DD HH:mm'): string { if (value) { if (formatString === 'fn') return moment(value).fromNow(); return moment(value).format(formatSt...
* 2017年09月17 * * {{ data | _date: 'fn' }} * 10 秒前 * ```
random_line_split
math.py
import nltk PLUS = 'plus' MUL = 'multiplied by' DIV = 'divided by' MIN = 'minus' OPENB = 'open bracket' CLOSEB = 'close bracket' with open('../grammars/math.cfg', 'r') as file: grammar_str = file.read() def validate(text): grammar = nltk.CFG.fromstring(grammar_str) parser = nltk.ChartParser(grammar) trees ...
else: text = 'Input text: ' + text + ' --> ' + state + ' Math question ' print(text) lines = [line.rstrip('\n') for line in open('../test/inputs/math')] for line in lines: print('##################################################################\n') invalid_marker = '??????????' try: ...
text = 'Input text: ' + text + ' --> ' + marker + ' ' + state + ' Math question '
conditional_block
math.py
import nltk PLUS = 'plus' MUL = 'multiplied by' DIV = 'divided by' MIN = 'minus' OPENB = 'open bracket' CLOSEB = 'close bracket' with open('../grammars/math.cfg', 'r') as file: grammar_str = file.read() def validate(text):
return (valid, math_form, answer) def print_validity(text, state, marker = None): if marker is not None: text = 'Input text: ' + text + ' --> ' + marker + ' ' + state + ' Math question ' else: text = 'Input text: ' + text + ' --> ' + state + ' Math question ' print(text) lines = [line.r...
grammar = nltk.CFG.fromstring(grammar_str) parser = nltk.ChartParser(grammar) trees = parser.parse(list(text)) valid = False answer = math_form = None for tree in trees: addition = tree[4].leaves() operation_string = '' for i in addition: operation_string = operation_string + i p = ope...
identifier_body
math.py
import nltk PLUS = 'plus' MUL = 'multiplied by' DIV = 'divided by' MIN = 'minus' OPENB = 'open bracket' CLOSEB = 'close bracket' with open('../grammars/math.cfg', 'r') as file: grammar_str = file.read() def validate(text): grammar = nltk.CFG.fromstring(grammar_str) parser = nltk.ChartParser(grammar) trees ...
print(' math form : ' + result[1]) print(' answer : ' + str(result[2])) else: print_validity(line, "Invalid", invalid_marker) except ValueError as ve: print(ve) print_validity(line, "Invalid", invalid_marker) continue
if result[0]: print_validity(line, "Valid")
random_line_split
math.py
import nltk PLUS = 'plus' MUL = 'multiplied by' DIV = 'divided by' MIN = 'minus' OPENB = 'open bracket' CLOSEB = 'close bracket' with open('../grammars/math.cfg', 'r') as file: grammar_str = file.read() def
(text): grammar = nltk.CFG.fromstring(grammar_str) parser = nltk.ChartParser(grammar) trees = parser.parse(list(text)) valid = False answer = math_form = None for tree in trees: addition = tree[4].leaves() operation_string = '' for i in addition: operation_string = operation_string + i ...
validate
identifier_name
cryptocurrency-migration.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...
() -> anyhow::Result<()> { exonum::helpers::init_logger()?; NodeBuilder::new() .with(Spec::new(OldService).with_default_instance()) .with(JustFactory::migrating(CryptocurrencyService)) .run() .await }
main
identifier_name
cryptocurrency-migration.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...
async fn main() -> anyhow::Result<()> { exonum::helpers::init_logger()?; NodeBuilder::new() .with(Spec::new(OldService).with_default_instance()) .with(JustFactory::migrating(CryptocurrencyService)) .run() .await }
use exonum_cryptocurrency_advanced::CryptocurrencyService; use old_cryptocurrency::contracts::CryptocurrencyService as OldService; #[tokio::main]
random_line_split
cryptocurrency-migration.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...
{ exonum::helpers::init_logger()?; NodeBuilder::new() .with(Spec::new(OldService).with_default_instance()) .with(JustFactory::migrating(CryptocurrencyService)) .run() .await }
identifier_body
icheck.js
check|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(options)) { // Normalize method's name options = options.toLowerCase(); // Find checkboxes and radio buttons walker(this); return stack.each(function() { var self = $(this); if (options == 'de...
// Handle states for (var state in active) { if (active[state]) { on(input, state, true); } else { off(input, state, true); }; }; } else if (!direct || method == 'toggle') { // Helper or label was clicked if (!direct) { input[_callb...
{ var node = input[0], state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked, active = method == _update ? { checked: node[_checked], disabled: node[_disabled], indeterminate: input.attr(_indeterminate) == 'true' || input.attr(_determinate) == 'fal...
identifier_body
icheck.js
(this); return stack.each(function() { var self = $(this); // If already customized tidy(self); var node = this, id = node.id, // Layer styles offset = -area + '%', size = 100 + (area * 2) + '%', layer = { position: ...
random_line_split
icheck.js
.each(function() { var self = $(this); // If already customized tidy(self); var node = this, id = node.id, // Layer styles offset = -area + '%', size = 100 + (area * 2) + '%', layer = { position: 'absolute', top...
off
identifier_name
icheck.js
'); } else { operate(self, true, options); }; // Fire method's callback if ($.isFunction(fire)) { fire(); }; }); // Customization } else if (typeof options == 'object' || !options) { // Check if any options were passed var settings...
{ var form = input.closest('form'), inputs = 'input[name="' + node.name + '"]'; inputs = form.length ? form.find(inputs) : $(inputs); inputs.each(function() { if (this !== node && $(this).data(_iCheck)) { off($(this), state); }; }); }
conditional_block
CompositeType-dbg.js
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides the base implementation for all model implementations sap.ui.define(['./FormatException', './ParseException', './SimpleTy...
* * @function * @name sap.ui.model.CompositeType.prototype.formatValue * @param {array} aValues the values to be formatted * @param {string} sInternalType the target type * @return {any} the formatted output value * * @public */ /** * Parse a value of an internal type to the expected set of values...
random_line_split
premium.js
jQuery( document ).ready( function() { jQuery( '#lightslider' ).lightSlider({ item: 1, autoWidth: false,
mode: "slide", useCSS: true, cssEasing: 'ease', //'cubic-bezier(0.25, 0, 0.25, 1)',// easing: 'linear', //'for jquery animation',//// speed: 400, //ms' auto: true, loop: true, slideEndAnimation: true, pause: 5000, keyPress: false, controls: true, prevHtml: '<span class="dashicons dashicons-arr...
slideMove: 1, // slidemove will be 1 if loop is true slideMargin: 10, addClass: '',
random_line_split
__init__.py
# Copyright 2013-2018 Rumma & Ko Ltd # License: BSD (see file COPYING for details) """ Adds a multipurpose concept of "Note". See :doc:`/specs/notes`.
fixtures.std """ from lino import ad from django.utils.translation import ugettext_lazy as _ class Plugin(ad.Plugin): "See :class:`lino.core.Plugin`." verbose_name = _("Notes") # needs_plugins = ['lino.modlib.notify'] needs_plugins = ['lino.modlib.gfks'] def post_site_startup(self, site):...
.. autosummary:: :toctree: fixtures.demo
random_line_split
__init__.py
# Copyright 2013-2018 Rumma & Ko Ltd # License: BSD (see file COPYING for details) """ Adds a multipurpose concept of "Note". See :doc:`/specs/notes`. .. autosummary:: :toctree: fixtures.demo fixtures.std """ from lino import ad from django.utils.translation import ugettext_lazy as _ class Plugin(ad.Pl...
(self, site): super(Plugin, self).post_site_startup(site) site.kernel.memo_parser.register_django_model( 'note', site.models.notes.Note, title=lambda obj: obj.subject) def setup_main_menu(config, site, user_type, m): mg = site.plugins.office m = m.add_men...
post_site_startup
identifier_name
__init__.py
# Copyright 2013-2018 Rumma & Ko Ltd # License: BSD (see file COPYING for details) """ Adds a multipurpose concept of "Note". See :doc:`/specs/notes`. .. autosummary:: :toctree: fixtures.demo fixtures.std """ from lino import ad from django.utils.translation import ugettext_lazy as _ class Plugin(ad.Pl...
def setup_explorer_menu(config, site, user_type, m): mg = site.plugins.office m = m.add_menu(mg.app_label, mg.verbose_name) m.add_action('notes.AllNotes')
mg = site.plugins.office m = m.add_menu(mg.app_label, mg.verbose_name) m.add_action('notes.NoteTypes') m.add_action('notes.EventTypes')
identifier_body
equals.js
/** @license ISC License (c) copyright 2017 original and current authors */ /** @author Ian Hofmann-Hicks (evil) */ const isSameType = require('./isSameType') const isSame = require('./isSame') const hasAlg = require('./hasAlg') const type = require('./type') const comp = (a, b) => a.valueOf() === b.valueOf() cons...
if(hasAlg('equals', a)) { return a.equals(b) } return (strats[type(a)] || comp)(a, b) } module.exports = equals
{ return false }
conditional_block
equals.js
/** @license ISC License (c) copyright 2017 original and current authors */ /** @author Ian Hofmann-Hicks (evil) */ const isSameType = require('./isSameType') const isSame = require('./isSame') const hasAlg = require('./hasAlg') const type = require('./type') const comp = (a, b) => a.valueOf() === b.valueOf() cons...
module.exports = equals
{ if(isSame(a, b)) { return true } if(!isSameType(a, b)) { return false } if(hasAlg('equals', a)) { return a.equals(b) } return (strats[type(a)] || comp)(a, b) }
identifier_body
equals.js
/** @license ISC License (c) copyright 2017 original and current authors */ /** @author Ian Hofmann-Hicks (evil) */ const isSameType = require('./isSameType') const isSame = require('./isSame') const hasAlg = require('./hasAlg') const type = require('./type') const comp = (a, b) => a.valueOf() === b.valueOf() cons...
Object.keys(a).length === Object.keys(b).length && deepEquals(a, b), 'RegExp': (a, b) => a.source === b.source && a.ignoreCase === b.ignoreCase && a.global === b.global && a.multiline === b.multiline && a.unicode === b.unicode } function deepEquals(a, b) { for(const key in a)...
a.name === b.name && a.message === b.message, 'Object': (a, b) =>
random_line_split
equals.js
/** @license ISC License (c) copyright 2017 original and current authors */ /** @author Ian Hofmann-Hicks (evil) */ const isSameType = require('./isSameType') const isSame = require('./isSame') const hasAlg = require('./hasAlg') const type = require('./type') const comp = (a, b) => a.valueOf() === b.valueOf() cons...
(a, b) { for(const key in a) { if(!equals(a[key], b[key])) { return false } } return true } function equals(a, b) { if(isSame(a, b)) { return true } if(!isSameType(a, b)) { return false } if(hasAlg('equals', a)) { return a.equals(b) } return (strats[type(a)] || comp)(a, ...
deepEquals
identifier_name
SSFP.py
from mdt import CompartmentTemplate from mdt.lib.post_processing import DTIMeasures __author__ = 'Robbert Harms' __date__ = '2017-08-03' __maintainer__ = 'Robbert Harms'
parameters = ('d', 'delta', 'G', 'TR', 'flip_angle', 'b1', 'T1', 'T2') dependencies = ('SSFP',) cl_code = ''' return SSFP(d, delta, G, TR, flip_angle, b1, T1, T2); ''' class SSFP_Stick(CompartmentTemplate): parameters = ('g', 'd', 'theta', 'phi', 'delta', 'G', 'TR', 'flip_angle', 'b1', '...
__email__ = 'robbert@xkls.nl' __licence__ = 'LGPL v3' class SSFP_Ball(CompartmentTemplate):
random_line_split
SSFP.py
from mdt import CompartmentTemplate from mdt.lib.post_processing import DTIMeasures __author__ = 'Robbert Harms' __date__ = '2017-08-03' __maintainer__ = 'Robbert Harms' __email__ = 'robbert@xkls.nl' __licence__ = 'LGPL v3' class SSFP_Ball(CompartmentTemplate): parameters = ('d', 'delta', 'G', 'TR', 'flip_angle...
class SSFP_Tensor(CompartmentTemplate): parameters = ('g', 'd', 'dperp0', 'dperp1', 'theta', 'phi', 'psi', 'delta', 'G', 'TR', 'flip_angle', 'b1', 'T1', 'T2') dependencies = ('SSFP', 'TensorApparentDiffusion') cl_code = ''' double adc = TensorApparentDiffusion(theta, phi, psi, ...
parameters = ('g', 'd', 'theta', 'phi', 'delta', 'G', 'TR', 'flip_angle', 'b1', 'T1', 'T2') dependencies = ('SSFP',) cl_code = ''' double adc = d * pown(dot(g, (float4)(cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta), 0.0)), 2); return SSFP(adc, delta, G, TR, flip_angle, b1, T1, T2); ...
identifier_body
SSFP.py
from mdt import CompartmentTemplate from mdt.lib.post_processing import DTIMeasures __author__ = 'Robbert Harms' __date__ = '2017-08-03' __maintainer__ = 'Robbert Harms' __email__ = 'robbert@xkls.nl' __licence__ = 'LGPL v3' class SSFP_Ball(CompartmentTemplate): parameters = ('d', 'delta', 'G', 'TR', 'flip_angle...
(CompartmentTemplate): parameters = ('g', 'd', 'dperp0', 'theta', 'phi', 'delta', 'G', 'TR', 'flip_angle', 'b1', 'T1', 'T2') dependencies = ('SSFP',) cl_code = ''' double adc = dperp0 + ((d - dperp0) * pown(dot(g, (float4)(cos(phi) * sin(theta), ...
SSFP_Zeppelin
identifier_name
typedrw.rs
use std::mem; // use core::raw::Slice as RawSlice; use mmap::MapOption::{MapReadable, MapFd}; use mmap::MemoryMap; use std::os::unix::prelude::AsRawFd; use std::slice; use std::ops; use std::fs::File; use std::marker::PhantomData; pub struct TypedMemoryMap<T:Copy> { map: MemoryMap, // mapped file len: ...
// })} unsafe { slice::from_raw_parts(self.map.data() as *const T, self.len) } } }
random_line_split
typedrw.rs
use std::mem; // use core::raw::Slice as RawSlice; use mmap::MapOption::{MapReadable, MapFd}; use mmap::MemoryMap; use std::os::unix::prelude::AsRawFd; use std::slice; use std::ops; use std::fs::File; use std::marker::PhantomData; pub struct TypedMemoryMap<T:Copy> { map: MemoryMap, // mapped file len: ...
(filename: String) -> TypedMemoryMap<T> { let file = File::open(filename).unwrap(); let size = file.metadata().unwrap().len() as usize; TypedMemoryMap { map: MemoryMap::new(size, &[MapReadable, MapFd(file.as_raw_fd())]).unwrap(), len: size / mem::size_of::<T>(), ...
new
identifier_name
function.rs
use ast::{Node, Loc, IdentifierNode, ExpressionNode}; use ast::{BlockNode, Statement, PatternList, PropertyKey}; pub trait Name<'ast>: Copy { fn empty() -> Self; } #[derive(Debug, PartialEq, Clone, Copy)] pub struct EmptyName; #[derive(Debug, PartialEq, Clone, Copy)] pub struct MandatoryName<'ast>(pub Identifier...
pub type Method<'ast> = Function<'ast, EmptyName>; impl<'ast> Name<'ast> for EmptyName { fn empty() -> Self { EmptyName } } impl<'ast> Name<'ast> for MandatoryName<'ast> { fn empty() -> Self { MandatoryName(Node::new(&Loc { start: 0, end: 0, item: "" ...
#[derive(Debug, PartialEq, Clone, Copy)] pub struct OptionalName<'ast>(pub Option<IdentifierNode<'ast>>);
random_line_split
function.rs
use ast::{Node, Loc, IdentifierNode, ExpressionNode}; use ast::{BlockNode, Statement, PatternList, PropertyKey}; pub trait Name<'ast>: Copy { fn empty() -> Self; } #[derive(Debug, PartialEq, Clone, Copy)] pub struct EmptyName; #[derive(Debug, PartialEq, Clone, Copy)] pub struct MandatoryName<'ast>(pub Identifier...
() -> Self { MandatoryName(Node::new(&Loc { start: 0, end: 0, item: "" })) } } impl<'ast> Name<'ast> for OptionalName<'ast> { fn empty() -> Self { OptionalName(None) } } #[cfg(test)] impl<'ast> From<IdentifierNode<'ast>> for MandatoryName<'ast> {...
empty
identifier_name
gpy_regression.py
.optimize() max_opt_iters : int, optional gp : GPy.model.GPRegression instance, optional **gp_params kernel : GPy.Kern noise_var : float mean_function """ if parameter_names is None: input_dim = 1 elif isinstance(parameter_...
""" # Ensure it's 2d for GPy x = np.asanyarray(x).reshape((-1, self.input_dim)) if self._gp is None: # TODO: return from GP mean function if given return np.zeros((x.shape[0], self.input_dim)), \ np.zeros((x.shape[0], self.input_dim)) # ...
grad_mean : np.array with shape (x.shape[0], input_dim) grad_var : np.array with shape (x.shape[0], input_dim)
random_line_split
gpy_regression.py
() max_opt_iters : int, optional gp : GPy.model.GPRegression instance, optional **gp_params kernel : GPy.Kern noise_var : float mean_function """ if parameter_names is None: input_dim = 1 elif isinstance(parameter_names, (l...
def __repr__(self): """Return GPy's __str__.""" return self.__str__() def predict(self, x, noiseless=False): """Return the GP model mean and variance at x. Parameters ---------- x : np.array numpy compatible (n, input_dim) array of points to evalua...
"""Return GPy's __str__.""" return self._gp.__str__()
identifier_body
gpy_regression.py
() max_opt_iters : int, optional gp : GPy.model.GPRegression instance, optional **gp_params kernel : GPy.Kern noise_var : float mean_function """ if parameter_names is None: input_dim = 1 elif isinstance(parameter_names, (l...
self.input_dim = input_dim self.bounds = bounds self.gp_params = gp_params self.optimizer = optimizer self.max_opt_iters = max_opt_iters self._gp = gp self._rbf_is_cached = False self.is_sampling = False # set to True once in sampling phase def...
raise ValueError("Keyword `bounds` must be a dictionary " "`{'parameter_name': (lower, upper), ... }`")
conditional_block
gpy_regression.py
f_is_cached: self._cache_RBF_kernel() r2 = np.sum(x**2., 1)[:, None] + self._rbf_x2sum - 2. * x.dot(self._gp.X.T) kx = self._rbf_var * np.exp(r2 * self._rbf_factor) + self._rbf_bias mu = kx.dot(self._rbf_woodbury) var = self._rbf_var + self._rbf_bias ...
__copy__
identifier_name
copyTemplatesRecursive.ts
import chalk from "chalk"; import { fs } from "mz"; import * as path from "path"; import { RepositoryCommandArgs } from "./command"; import { Mustache } from "./commands/mustache"; import { Runtime } from "./runtime"; import { globAsync, mkdirpSafe, setupDir } from "./utils"; const nonTextFileExtensions = new Set(["....
args, setupFile.slice(setupDir.length), rootDirectory ); } const outputLocal = `./${setupFile.slice( setupFile.indexOf(directory) + rootDirectory.length + 1 )}`; const outputAbsol...
await Promise.all( files.map(async (setupFile) => { if (fs.statSync(setupFile).isDirectory()) { return await copyTemplatesRecursive( runtime,
random_line_split
copyTemplatesRecursive.ts
import chalk from "chalk"; import { fs } from "mz"; import * as path from "path"; import { RepositoryCommandArgs } from "./command"; import { Mustache } from "./commands/mustache"; import { Runtime } from "./runtime"; import { globAsync, mkdirpSafe, setupDir } from "./utils"; const nonTextFileExtensions = new Set(["....
else { await Mustache(runtime, { ...args, input: setupFile, output: outputAbsolute, }); } }) ); };
{ runtime.logger.log(chalk.grey(`Copying ${outputAbsolute}`)); await mkdirpSafe(path.dirname(outputAbsolute)); await fs.copyFile(setupFile, outputAbsolute); }
conditional_block
test_relu.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
model = _get_model(shape, dtype, a_min, a_max) mod = tei.make_ethosn_partition(model) tei.test_error(mod, {}, err_msg)
conditional_block
test_relu.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
), } outputs = [] for npu in [False, True]: model = _get_model(inputs["a"].shape, dtype, a_min, a_max) mod = tei.make_module(model, {}) outputs.append(tei.build_and_run(mod, inputs, 1, {}, npu=npu)) tei.veri...
trials = [ ((1, 4, 4, 4), 65, 178, "uint8"), ((1, 8, 4, 2), 1, 254, "uint8"), ((1, 16), 12, 76, "uint8"), ((1, 4, 4, 4), 65, 125, "int8"), ((1, 8, 4, 2), -100, 100, "int8"), ((1, 16), -120, -20, "int8"), ] np.random.seed(0) for shape, a_min, a_max, trial_dtyp...
identifier_body
test_relu.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
model = _get_model(shape, dtype, a_min, a_max) mod = tei.make_ethosn_partition(model) tei.test_error(mod, {}, err_msg)
for shape, dtype, a_min, a_max, err_msg in trials:
random_line_split
test_relu.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
(shape, dtype, a_min, a_max): assert a_min >= np.iinfo(dtype).min and a_max <= np.iinfo(dtype).max a = relay.var("a", shape=shape, dtype=dtype) relu = relay.clip(a, a_min=a_min, a_max=a_max) return relu @requires_ethosn @pytest.mark.parametrize("dtype", ["uint8", "int8"]) def test_relu(dtype): tri...
_get_model
identifier_name
task_run.py
# Copyright (C) British Crown (Met Office) & Contributors. # This file is part of Rose, a framework for meteorological suites. # # Rose 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 L...
(): """Launcher for the CLI.""" opt_parser = RoseOptionParser( usage='rose task-run [OPTIONS] [--] [APP-COMMAND ...]', description=''' Provide an environment to run a suite task. Provides environment variables documented in `rose task-env`. It is worth noting that if the environment variables a...
main
identifier_name
task_run.py
# Copyright (C) British Crown (Met Office) & Contributors. # This file is part of Rose, a framework for meteorological suites. # # Rose 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 L...
value = os.pathsep.join(prepend_paths + orig_paths) env_export(key, value, self.event_handler) # Name association with builtin applications builtin_app = None if opts.app_mode is None: builtin_apps_manager = self.app_runner.builtins_manager built...
orig_paths = orig_v.split(os.pathsep)
conditional_block
task_run.py
# Copyright (C) British Crown (Met Office) & Contributors. # This file is part of Rose, a framework for meteorological suites. # # Rose 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 L...
value = os.pathsep.join(prepend_paths + orig_paths) env_export(key, value, self.event_handler) # Name association with builtin applications builtin_app = None if opts.app_mode is None: builtin_apps_manager = self.app_runner.builtins_manager builti...
if orig_v: orig_paths = orig_v.split(os.pathsep)
random_line_split
task_run.py
# Copyright (C) British Crown (Met Office) & Contributors. # This file is part of Rose, a framework for meteorological suites. # # Rose 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 L...
path_globs, full_mode=is_changed, ) for key, prepend_paths in prepend_paths_map.items(): orig_paths = [] orig_v = os.getenv(key, "") if orig_v: orig_paths = orig_v.split(os.pathsep) value = os.pathsep.join(prepend_pa...
"""Run application configuration as a suite task.""" # "rose task-env" t_prop = self.suite_engine_proc.get_task_props( cycle=opts.cycle, cycle_offsets=opts.cycle_offsets, prefix_delim=opts.prefix_delim, suffix_delim=opts.suffix_delim, ) is_...
identifier_body
controllers.js
angular.module('starter.controllers', ['ionic']) .controller('DashCtrl', function($scope) {}) .controller('ListAppDirCtrl', function($scope, $cordovaFile, $ionicPlatform, Scan, $q) { myRes = Scan.all("./"); var helper = Cordohelper.helpers; myRes.then(function (success){ console.log(angular.toJson(...
function getFileDate(fileStr) { return fileStr.split('\n')[2].split("\t")[0].split(" ")[0]; } var helper = Cordohelper.helpers; var array_path = ["./Download", "cordova.file.externalRootDirectory"]; var myRes = helper.cordovaCheckDir(array_path, cordova, $q, $cordovaFile, $ionicPlatform); myRes.the...
{ for (var i = 0; i < objectsList.length; i++) { if (objectsList[i][property] === value) { return i; } } }
identifier_body
controllers.js
angular.module('starter.controllers', ['ionic']) .controller('DashCtrl', function($scope) {}) .controller('ListAppDirCtrl', function($scope, $cordovaFile, $ionicPlatform, Scan, $q) { myRes = Scan.all("./"); var helper = Cordohelper.helpers; myRes.then(function (success){ console.log(angular.toJson(...
var array_path = ["./Download", "cordova.file.externalRootDirectory"]; var myRes = helper.cordovaCheckDir(array_path, cordova, $q, $cordovaFile, $ionicPlatform); myRes.then(function (success){ console.debug(angular.toJson(success, true)); $scope.filesList = success; $scope.filesList = $scope.filesList...
var helper = Cordohelper.helpers;
random_line_split
controllers.js
angular.module('starter.controllers', ['ionic']) .controller('DashCtrl', function($scope) {}) .controller('ListAppDirCtrl', function($scope, $cordovaFile, $ionicPlatform, Scan, $q) { myRes = Scan.all("./"); var helper = Cordohelper.helpers; myRes.then(function (success){ console.log(angular.toJson(...
(objectsList, property, value) { for (var i = 0; i < objectsList.length; i++) { if (objectsList[i][property] === value) { return i; } } } function getFileDate(fileStr) { return fileStr.split('\n')[2].split("\t")[0].split(" ")[0]; } var helper = Cordohelper.h...
findObjectIndex
identifier_name
controllers.js
angular.module('starter.controllers', ['ionic']) .controller('DashCtrl', function($scope) {}) .controller('ListAppDirCtrl', function($scope, $cordovaFile, $ionicPlatform, Scan, $q) { myRes = Scan.all("./"); var helper = Cordohelper.helpers; myRes.then(function (success){ console.log(angular.toJson(...
} } function getFileDate(fileStr) { return fileStr.split('\n')[2].split("\t")[0].split(" ")[0]; } var helper = Cordohelper.helpers; var array_path = ["./Download", "cordova.file.externalRootDirectory"]; var myRes = helper.cordovaCheckDir(array_path, cordova, $q, $cordovaFile, $ionicPlatform);...
{ return i; }
conditional_block
getNameBadIndexed.py
# -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico 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; eith...
print "No error. The change are saved" else: print "There were errors. The changes was not saved"
if not error: DBMgr.getInstance().endRequest()
random_line_split
getNameBadIndexed.py
# -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico 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; eith...
log.writelines("\n".join(lines)) log.close() if not error: DBMgr.getInstance().endRequest() print "No error. The change are saved" else: print "There were errors. The changes was not saved"
if uid in ni._words[word] and word != user.getName(): lines.append(uid + "-" + user.getName() + "-" + word)
conditional_block
main.rs
// Tifflin OS - simple_console // - By John Hodge (thePowersGang) // // Simplistic console, used as a quick test case (fullscreen window) #![feature(const_fn)] #[macro_use] extern crate syscalls; extern crate cmdline_words_parser; use syscalls::Object; use syscalls::gui::Colour; mod terminal_surface; mod terminal;...
term.set_foreground( Colour::def_yellow() ); let _ = write!(&mut term, " {}\n", ::syscalls::get_text_info(::syscalls::TEXTINFO_KERNEL, 1, &mut buf)); // Kernel 1: Build line term.set_foreground( Colour::white() ); let _ = write!(&mut term, "Simple console\n"); } window.show(); // Initial prompt term.write...
{ use syscalls::gui::{Group,Window}; use syscalls::threads::{S_THIS_PROCESS,ThisProcessWaits}; ::syscalls::threads::wait(&mut [S_THIS_PROCESS.get_wait(ThisProcessWaits::new().recv_obj())], !0); ::syscalls::gui::set_group( S_THIS_PROCESS.receive_object::<Group>(0).unwrap() ); // Create maximised window let wind...
identifier_body
main.rs
// Tifflin OS - simple_console // - By John Hodge (thePowersGang) // // Simplistic console, used as a quick test case (fullscreen window) #![feature(const_fn)] #[macro_use] extern crate syscalls; extern crate cmdline_words_parser; use syscalls::Object; use syscalls::gui::Colour; mod terminal_surface; mod terminal;...
fn main() { use syscalls::gui::{Group,Window}; use syscalls::threads::{S_THIS_PROCESS,ThisProcessWaits}; ::syscalls::threads::wait(&mut [S_THIS_PROCESS.get_wait(ThisProcessWaits::new().recv_obj())], !0); ::syscalls::gui::set_group( S_THIS_PROCESS.receive_object::<Group>(0).unwrap() ); // Create maximised window...
use std::fmt::Write;
random_line_split
main.rs
// Tifflin OS - simple_console // - By John Hodge (thePowersGang) // // Simplistic console, used as a quick test case (fullscreen window) #![feature(const_fn)] #[macro_use] extern crate syscalls; extern crate cmdline_words_parser; use syscalls::Object; use syscalls::gui::Colour; mod terminal_surface; mod terminal;...
, }; let mut buf = [0; 256]; loop { let name_bytes = match handle.read_ent(&mut buf) { Ok(v) => v, Err(e) => { print!(term, "Read error: {:?}", e); return ; }, }; if name_bytes == b"" { break ; } let name = ::std::str::from_utf8(name_bytes).expect("Filename not utf-8"); print!(t...
{ print!(term, "Unable to open '{}': {:?}", path, e); return ; }
conditional_block
main.rs
// Tifflin OS - simple_console // - By John Hodge (thePowersGang) // // Simplistic console, used as a quick test case (fullscreen window) #![feature(const_fn)] #[macro_use] extern crate syscalls; extern crate cmdline_words_parser; use syscalls::Object; use syscalls::gui::Colour; mod terminal_surface; mod terminal;...
(&mut self, term: &mut terminal::Terminal, mut cmdline: String) { use cmdline_words_parser::StrExt; let mut args = cmdline.parse_cmdline_words(); match args.next() { None => {}, // 'pwd' - Print working directory Some("pwd") => print!(term, "/{}", self.cwd_rel), // 'cd' - Change directory Some("cd") ...
handle_command
identifier_name
cohort_analysis_function.py
import pandas as pd import numpy as np from dateutil.relativedelta import relativedelta #### Utilities def get_first_visit_date(data_patient): ''' Determines the first visit for a given patient''' #IDEA Could be parallelized in Dask data_patient['first_visit_date'] = min(data_patient.visit_date) retur...
if (data_patient.reasonDescEn.iloc[0] is not np.nan) & (pd.to_datetime(data_patient.discDate.iloc[0]) < reference_date): status = data_patient.reasonDescEn.iloc[0] date_out = pd.to_datetime(data_patient.discDate.iloc[0]) return pd.DataFrame([{'status': status, 'late_ti...
status = 'Followed'
conditional_block
cohort_analysis_function.py
import pandas as pd import numpy as np from dateutil.relativedelta import relativedelta #### Utilities def get_first_visit_date(data_patient): ''' Determines the first visit for a given patient''' #IDEA Could be parallelized in Dask data_patient['first_visit_date'] = min(data_patient.visit_date) retur...
(data_cohort, reference_date, horizon_time): # TODO Make sure dates are dates data_cohort['first_visit_date'] = pd.to_datetime(data_cohort['first_visit_date']) #TODO This conversion should happen earlier data_cohort.loc[:, 'horizon_date'] = data_cohort['first_visit_date'] + np.timedelta64(horizon_time, 'D'...
horizon_outcome
identifier_name
cohort_analysis_function.py
import pandas as pd import numpy as np from dateutil.relativedelta import relativedelta #### Utilities def get_first_visit_date(data_patient): ''' Determines the first visit for a given patient''' #IDEA Could be parallelized in Dask data_patient['first_visit_date'] = min(data_patient.visit_date)
def subset_analysis_data(data, date_analysis): ''' Function that subsets the full dataset to only the data available for a certain analysis date''' if type(data.date_entered.iloc[0]) is str : data.date_entered = pd.to_datetime(data.date_entered) data = data[data.date_entered < date_analysis] ret...
return data_patient
random_line_split
cohort_analysis_function.py
import pandas as pd import numpy as np from dateutil.relativedelta import relativedelta #### Utilities def get_first_visit_date(data_patient): ''' Determines the first visit for a given patient''' #IDEA Could be parallelized in Dask data_patient['first_visit_date'] = min(data_patient.visit_date) retur...
# QUESTION What are the form_types
assert reference_date <= date_analysis, 'You should not analyze a period before you have the data (date of analysis is before reference date)' if type(reference_date) is str : reference_date = pd.to_datetime(reference_date) if type(date_analysis) is str: date_analysis = pd.to_datetime(date_analy...
identifier_body
settings.py
# -*- coding: utf-8 -*- """Application configuration.""" import os class Config(object): """Base configuration.""" ENV = 'dev' # Default ENV SECRET_KEY = os.environ.get('FANSUBS_CMS_SECRET', 'secret-key') APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory PROJECT_ROOT = os.pa...
(Config): """Test configuration.""" TESTING = True DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite://' BCRYPT_LOG_ROUNDS = 4 # For faster tests; needs at least 4 WTF_CSRF_ENABLED = False # Allows form testing PRESERVE_CONTEXT_ON_EXCEPTION = False # Travis CI test fix LANGUAGES = { '...
TestConfig
identifier_name
settings.py
# -*- coding: utf-8 -*- """Application configuration.""" import os class Config(object): """Base configuration.""" ENV = 'dev' # Default ENV SECRET_KEY = os.environ.get('FANSUBS_CMS_SECRET', 'secret-key') APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory PROJECT_ROOT = os.pa...
SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) DEBUG_TB_ENABLED = True ASSETS_DEBUG = True # Don't bundle/minify static assets CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. class TestConfig(Config): """Test configuration.""" TESTING = True DEBUG = True SQLALCH...
ENV = 'dev' DEBUG = True DB_NAME = 'dev.db' # Put the db file in project root DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME)
random_line_split
settings.py
# -*- coding: utf-8 -*- """Application configuration.""" import os class Config(object): """Base configuration.""" ENV = 'dev' # Default ENV SECRET_KEY = os.environ.get('FANSUBS_CMS_SECRET', 'secret-key') APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory PROJECT_ROOT = os.pa...
class DevConfig(Config): """Development configuration.""" ENV = 'dev' DEBUG = True DB_NAME = 'dev.db' # Put the db file in project root DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME) SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH) DEBUG_TB_ENABLED = True ASSETS_DE...
"""Production configuration.""" ENV = 'prod' DEBUG = False SQLALCHEMY_DATABASE_URI = os.environ.get( 'FANSUBS_CMS_DB', 'postgresql://USER:PASS@localhost:5432/DB_NAME' ) DEBUG_TB_ENABLED = False # Disable Debug toolbar FLASK_LOG_LEVEL = 'ERROR' CACHE_TYPE = 'redis' # Can be...
identifier_body
root.js
color11': '#FFCC00', // orange fading (-> receive TVO-ACK) 'color12': '#2EE600', // 'color13': '#2EE600', // 'color14': '#2EE600', // 'color15': '#009DFF', // thin bright blue line (-> selected parent) 'color20': '#536236', // light green -> camera traffic 'color30': '#54E600', // event traffic }; /** ...
stationUpdate(); }; function reporterRemove(data) { var reporter = reporters[data.id]; if (reporter) { reporter.dom.remove(); for (sid in stations) { delete stations[sid].reps[data.id]; delete activeStation.reps[data.id]; } delete activeReporters[data.id]; delete reporters[data.id]; } }; function ...
reporters[data.id].dom.addClass('active'); activeReporters[data.id] = 'active'; }
conditional_block
root.js
color11': '#FFCC00', // orange fading (-> receive TVO-ACK) 'color12': '#2EE600', // 'color13': '#2EE600', // 'color14': '#2EE600', // 'color15': '#009DFF', // thin bright blue line (-> selected parent) 'color20': '#536236', // light green -> camera traffic 'color30': '#54E600', // event traffic }; /** ...
/** * Setup a websocket connection to the anchor for receiving events and register event handlers. */ function initSocket() { socket = io.connect(); socket.on('connect', function() { socket.emit('status', '{online: true}'); isConnected = true; }); socket.on('connect_failed', function() { console.log('Conn...
var out = $("#console-output"); var string = new Date(data.time).toLocaleString() + " [" + data.node + "] " + data.data + "\n"; out.val(out.val() + string); out.scrollTop(out[0].scrollHeight - out.height()); };
identifier_body
root.js
color11': '#FFCC00', // orange fading (-> receive TVO-ACK) 'color12': '#2EE600', // 'color13': '#2EE600', // 'color14': '#2EE600', // 'color15': '#009DFF', // thin bright blue line (-> selected parent) 'color20': '#536236', // light green -> camera traffic 'color30': '#54E600', // event traffic }; /** ...
} /** * @brief Add a new station to the console */ function stationAdd(id, name) { var item = $('<div class="console-station">' + name + '</div>'); item.click(stationSelect); $("#console-stations").append(item); stations[id] = {'name': name, 'dom': item, 'reps': {}}; }; function stationUpdate() { for (rid in r...
stationAdd('all', 'All'); stations['all'].dom.addClass('active'); activeStation = stations.all; stationUpdate();
random_line_split
root.js
11': '#FFCC00', // orange fading (-> receive TVO-ACK) 'color12': '#2EE600', // 'color13': '#2EE600', // 'color14': '#2EE600', // 'color15': '#009DFF', // thin bright blue line (-> selected parent) 'color20': '#536236', // light green -> camera traffic 'color30': '#54E600', // event traffic }; /** * Pr...
data) { var out = $("#console-output"); var string = new Date(data.time).toLocaleString() + " [" + data.node + "] " + data.data + "\n"; out.val(out.val() + string); out.scrollTop(out[0].scrollHeight - out.height()); }; /** * Setup a websocket connection to the anchor for receiving events and register event handle...
onsoleReceive(
identifier_name