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 |
|---|---|---|---|---|
test_apdetail.py | # -*- coding: utf-8 -*-
"""UnitTests for airwaveapiclient."""
import os
import unittest
from airwaveapiclient import APDetail
from airwaveapiclient.tests import test_utils
class APDetailUnitTests(unittest.TestCase):
"""Class APDetailUnitTests.
Unit test for APDetail.
"""
def setUp(self):
... | if radio['radio_type'] == 'bgn':
self.assertEqual(radio['radio_interface'], '2')
if radio['radio_type'] == 'aN':
self.assertEqual(radio['radio_interface'], '1') | conditional_block | |
test_apdetail.py | # -*- coding: utf-8 -*-
"""UnitTests for airwaveapiclient."""
import os
import unittest
from airwaveapiclient import APDetail
from airwaveapiclient.tests import test_utils
class APDetailUnitTests(unittest.TestCase):
"""Class APDetailUnitTests.
Unit test for APDetail.
"""
def setUp(self):
... |
def tearDown(self):
"""Tear down."""
def test_init(self):
"""Test init."""
self.assertNotEqual(self.obj, None)
def test_radio_type(self):
"""Test radio_type."""
for radio in self.obj['radio']:
if radio['radio_type'] == 'bgn':
self.asser... | """Setup."""
self.ap_detail_file = 'test_apdetail.xml'
self.here = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(self.here, self.ap_detail_file)
self.ap_detail = test_utils.read_file(path)
self.obj = APDetail(self.ap_detail) | identifier_body |
error.rs | fmt::Formatter<'_>) -> fmt::Result {
match self {
ExpectedNumberOfArgs::Single(num) => write!(f, "{}", num),
ExpectedNumberOfArgs::Range(min, max) => write!(f, "{}..{}", min, max),
}
}
}
// TODO: Add backtrace when std::backtrace is stabilized
#[derive(Debug)]
pub struct Er... | url: String,
msg: String,
},
GitLabDiffNotSupported,
BitbucketDiffNotSupported,
AzureDevOpsNotSupported,
NoUserInPath {
path: String,
},
NoRepoInPath {
path: String,
},
UnknownHostingService {
url: String,
},
BrokenUrl {
url: St... | },
CliParseFail(getopts::Fail),
OpenUrlFailure { | random_line_split |
error.rs | fmt::Formatter<'_>) -> fmt::Result {
match self {
ExpectedNumberOfArgs::Single(num) => write!(f, "{}", num),
ExpectedNumberOfArgs::Range(min, max) => write!(f, "{}..{}", min, max),
}
}
}
// TODO: Add backtrace when std::backtrace is stabilized
#[derive(Debug)]
pub struct Er... | <T>(kind: ErrorKind) -> Result<T> {
Err(Error::new(kind))
}
pub fn kind(&self) -> &ErrorKind {
&self.kind
}
pub fn eprintln(&self) {
use std::error::Error;
fn eprint_cause(e: &dyn std::error::Error) {
eprint!(": {}", e);
if let Some(s) = e.source... | err | identifier_name |
tab-bar.ts | /**
* @license
* Copyright 2022 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {BaseElement} from '@material/mwc-base/base-element';
import {observer} from '@material/mwc-base/observer';
import {html} from 'lit';
import {property, query} from 'lit/decorators.js';
import {ClassInfo, classMap} from 'lit/... | (e: KeyboardEvent) {
this.mdcFoundation.handleKeyDown(e);
}
protected override render() {
return html`
<div class="${classMap(this.getRootClasses())}"
role="tablist"
@MD3Tab:interacted="${this._handleTabInteraction}"
@keydown="${this._handleKeydown}">
<md-tab-... | _handleKeydown | identifier_name |
tab-bar.ts | /**
* @license
* Copyright 2022 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {BaseElement} from '@material/mwc-base/base-element';
import {observer} from '@material/mwc-base/observer';
import {html} from 'lit';
import {property, query} from 'lit/decorators.js';
import {ClassInfo, classMap} from 'lit/... | const tab = this._getTab(index);
if (tab !== undefined) {
tab.deactivate();
}
},
focusTabAtIndex: (index: number) => {
const tab = this._getTab(index);
if (tab !== undefined) {
tab.focus();
}
},
// TODO(sorvell): tab may not be ... | {
return {
scrollTo: (scrollX: number) =>
this.scrollerElement.scrollToPosition(scrollX),
incrementScroll: (scrollXIncrement: number) =>
this.scrollerElement.incrementScrollPosition(scrollXIncrement),
getScrollPosition: () => this.scrollerElement.getScrollPosition(),
getS... | identifier_body |
tab-bar.ts | /**
* @license
* Copyright 2022 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {BaseElement} from '@material/mwc-base/base-element';
import {observer} from '@material/mwc-base/observer';
import {html} from 'lit';
import {property, query} from 'lit/decorators.js';
import {ClassInfo, classMap} from 'lit/... | </div>
`;
}
protected getRootClasses(): ClassInfo {
return {
'md3-tab-bar': true,
};
}
protected abstract _getTabs(): MdPrimaryTab[]|MdSecondaryTab[];
protected _getTab(index: number) {
return this._getTabs()[index];
}
protected abstract _getActiveTabIndex(): number;
p... | random_line_split | |
tab-bar.ts | /**
* @license
* Copyright 2022 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {BaseElement} from '@material/mwc-base/base-element';
import {observer} from '@material/mwc-base/observer';
import {html} from 'lit';
import {property, query} from 'lit/decorators.js';
import {ClassInfo, classMap} from 'lit/... |
},
// TODO(sorvell): tab may not be able to synchronously answer
// `computeIndicatorClientRect` if an update is pending or it has not yet
// updated. If this is necessary, LitElement may need a `forceUpdate`
// method.
getTabIndicatorClientRectAtIndex: (index: number) => {
... | {
tab.focus();
} | conditional_block |
check-todos.py | #!/usr/bin/env python3
#
# Copyright © 2019 Endless Mobile, Inc.
#
# SPDX-License-Identifier: LGPL-2.1-or-later
#
# Original author: Philip Withnall
"""
Checks that a merge request doesn’t add any instances of the string ‘todo’
(in uppercase), or similar keywords. It may remove instances of that keyword,
or move them ... | if re.search('(^|\W+){}(\W+|$)'.format(keyword), line):
banned_words_seen.add(keyword)
seen_in_log = True
# Check the diff for banned words.
diff_process = subprocess.run(
['git', 'diff', '-U0', '--no-color', args.commits],
stdout=subprocess.PIPE, std... | arse.ArgumentParser(
description='Check a range of commits to ensure they don’t contain '
'banned keywords.')
parser.add_argument('commits',
help='SHA to diff from, or range of commits to diff')
args = parser.parse_args()
banned_words_seen = set()
see... | identifier_body |
check-todos.py | #!/usr/bin/env python3
#
# Copyright © 2019 Endless Mobile, Inc.
# | # Original author: Philip Withnall
"""
Checks that a merge request doesn’t add any instances of the string ‘todo’
(in uppercase), or similar keywords. It may remove instances of that keyword,
or move them around, according to the logic of `git log -S`.
"""
import argparse
import re
import subprocess
import sys
# We... | # SPDX-License-Identifier: LGPL-2.1-or-later
# | random_line_split |
check-todos.py | #!/usr/bin/env python3
#
# Copyright © 2019 Endless Mobile, Inc.
#
# SPDX-License-Identifier: LGPL-2.1-or-later
#
# Original author: Philip Withnall
"""
Checks that a merge request doesn’t add any instances of the string ‘todo’
(in uppercase), or similar keywords. It may remove instances of that keyword,
or move them ... | r = argparse.ArgumentParser(
description='Check a range of commits to ensure they don’t contain '
'banned keywords.')
parser.add_argument('commits',
help='SHA to diff from, or range of commits to diff')
args = parser.parse_args()
banned_words_seen = set()... | arse | identifier_name |
check-todos.py | #!/usr/bin/env python3
#
# Copyright © 2019 Endless Mobile, Inc.
#
# SPDX-License-Identifier: LGPL-2.1-or-later
#
# Original author: Philip Withnall
"""
Checks that a merge request doesn’t add any instances of the string ‘todo’
(in uppercase), or similar keywords. It may remove instances of that keyword,
or move them ... | een_in_diff:
where = 'commit diff'
print('Saw banned keywords in a {}: {}. '
'This indicates the branch is a work in progress and should not '
'be merged in its current '
'form.'.format(where, ', '.join(banned_words_seen)))
sys.exit(1)
if __name__... | message'
elif s | conditional_block |
dice.js | /**
* # dice plugin
*
* ## Install
* 1. Copy the plugin to the `plugins` directory.
* 2. Start your bot and enable the plugin with `!enable dice`
*
* ## Commands
* * `!dice roll <number>` - Rolls a dice with `<number>` faces.
* + Example: `!dice roll 5` - Rolls a dice with 5 faces
*/
// Discord Bot API
... | (user, userID, channelID, message) {
message = message.split(' ');
if (message.length < 1 || message[0].length < 1 || isNaN(message[0])) {
bot.sendMessage({
to: channelID,
message: 'You have to define the amount of faces.',
});
return false;
}
const fac... | rollCommand | identifier_name |
dice.js | /**
* # dice plugin
*
* ## Install
* 1. Copy the plugin to the `plugins` directory.
* 2. Start your bot and enable the plugin with `!enable dice`
*
* ## Commands
* * `!dice roll <number>` - Rolls a dice with `<number>` faces.
* + Example: `!dice roll 5` - Rolls a dice with 5 faces
*/
// Discord Bot API
... |
const faces = Number(message[0]);
const result = Math.floor(Math.random() * faces) + 1;
bot.sendMessage({
to: channelID,
message: user + ' rolled a ' + result,
});
}
const plugin = {
name: 'dice',
defaultCommandPrefix: 'dice',
commands: {
roll: {
fn: ... | {
bot.sendMessage({
to: channelID,
message: 'You have to define the amount of faces.',
});
return false;
} | conditional_block |
dice.js | /**
* # dice plugin
*
* ## Install
* 1. Copy the plugin to the `plugins` directory.
* 2. Start your bot and enable the plugin with `!enable dice`
*
* ## Commands
* * `!dice roll <number>` - Rolls a dice with `<number>` faces.
* + Example: `!dice roll 5` - Rolls a dice with 5 faces
*/
// Discord Bot API
... |
const plugin = {
name: 'dice',
defaultCommandPrefix: 'dice',
commands: {
roll: {
fn: rollCommand,
description: 'Rolls a dice',
},
},
};
export default plugin;
| {
message = message.split(' ');
if (message.length < 1 || message[0].length < 1 || isNaN(message[0])) {
bot.sendMessage({
to: channelID,
message: 'You have to define the amount of faces.',
});
return false;
}
const faces = Number(message[0]);
const ... | identifier_body |
dice.js | /**
* # dice plugin
*
* ## Install
* 1. Copy the plugin to the `plugins` directory.
* 2. Start your bot and enable the plugin with `!enable dice`
*
* ## Commands
* * `!dice roll <number>` - Rolls a dice with `<number>` faces.
* + Example: `!dice roll 5` - Rolls a dice with 5 faces
*/
// Discord Bot API
... | });
return false;
}
const faces = Number(message[0]);
const result = Math.floor(Math.random() * faces) + 1;
bot.sendMessage({
to: channelID,
message: user + ' rolled a ' + result,
});
}
const plugin = {
name: 'dice',
defaultCommandPrefix: 'dice',
comm... | to: channelID,
message: 'You have to define the amount of faces.', | random_line_split |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations ───────────┐
// Macro Rules Overload ────────────┘
// `test!` will compare `$left` and `$right`
// in different ways depending on how you invoke it:
macro_rules! test {
// Arguments don't need to be separated by... | stringify!($right),
$left && $right)
);
// ^ each arm must end with a semicolon.
($left:expr; or $right:expr) => (
println!("{:?} or {:?} is {:?}",
stringify!($left),
stringify!($right),
$left || $right)
);
}
f... | println!("{:?} and {:?} is {:?}",
stringify!($left), | random_line_split |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations ───────────┐
// Macro Rules Overload ────────────┘
// `test!` will compare `$left` and `$right`
// in different ways depending on how you invoke it:
macro_rules! test {
// Arguments don't need to be separated by... | 2);
test!(true; or false);
}
| 4i3 | identifier_name |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations ───────────┐
// Macro Rules Overload ────────────┘
// `test!` will compare `$left` and `$right`
// in different ways depending on how you invoke it:
macro_rules! test {
// Arguments don't need to be separated by... |
test!(true; or false);
}
| identifier_body | |
rpc.js | if(!dojo._hasResource["tests.rpc"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["tests.rpc"] = true;
dojo.provide("tests.rpc");
dojo.require("dojo.rpc.RpcService");
dojo.require("dojo.rpc.JsonService");
dojo.require("dojo.rpc.JsonpService");
doh.register("te... | ]
);
} | } | random_line_split |
rpc.js | if(!dojo._hasResource["tests.rpc"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["tests.rpc"] = true;
dojo.provide("tests.rpc");
dojo.require("dojo.rpc.RpcService");
dojo.require("dojo.rpc.JsonService");
dojo.require("dojo.rpc.JsonpService");
doh.register("te... |
td.addCallbacks(function(result) {
if(result=="<P>RPC TEST</P>"){
return true;
}else{
return new Error("JsonRpc-EchoTest test failed, resultant content didn't match");
}
}, function(result){
return new Error(result);
});
td.addBoth(d, "callback");
return d;
}
... | {
var err= new Error("This Test requires a webserver and PHP and will fail intentionally if loaded from file://");
d.errback(err);
return d;
} | conditional_block |
views.py | shoppingcart.processors.CyberSource import (
get_signed_purchase_params, get_purchase_endpoint
)
from verify_student.models import SoftwareSecurePhotoVerification
import ssencrypt
log = logging.getLogger(__name__)
class VerifyView(View):
@method_decorator(login_required)
def get(self, request, course_id... | "chosen_price": chosen_price,
"upgrade": upgrade,
}
return render_to_response('verify_student/verified.html', context)
@login_required
def create_order(request):
"""
Submit PhotoVerification and create a new Order for this verified cert
"""
if not SoftwareSecur... | """
Handle the case where we have a get request
"""
upgrade = request.GET.get('upgrade', False)
if CourseEnrollment.enrollment_mode_for_user(request.user, course_id) == 'verified':
return redirect(reverse('dashboard'))
verify_mode = CourseMode.mode_for_course(course_i... | identifier_body |
views.py | shoppingcart.processors.CyberSource import (
get_signed_purchase_params, get_purchase_endpoint
)
from verify_student.models import SoftwareSecurePhotoVerification
import ssencrypt
log = logging.getLogger(__name__)
class VerifyView(View):
@method_decorator(login_required)
def get(self, request, course_id... |
course = course_from_id(course_id)
context = {
"progress_state": progress_state,
"user_full_name": request.user.profile.name,
"course_id": course_id,
"course_name": course.display_name_with_default,
"course_org": course.display_org_with_defau... | chosen_price = verify_mode.min_price | conditional_block |
views.py | shoppingcart.processors.CyberSource import (
get_signed_purchase_params, get_purchase_endpoint
)
from verify_student.models import SoftwareSecurePhotoVerification
import ssencrypt
log = logging.getLogger(__name__)
class VerifyView(View):
@method_decorator(login_required)
def get(self, request, course_id... | error_code = body_dict.get("MessageType", "")
try:
attempt = SoftwareSecurePhotoVerification.objects.get(receipt_id=receipt_id)
except SoftwareSecurePhotoVerification.DoesNotExist:
log.error("Software Secure posted back for receipt_id {}, but not found".format(receipt_id))
return Ht... | reason = body_dict.get("Reason", "") | random_line_split |
views.py | we want to kick them
# from the flow
if not verify_mode:
return redirect(reverse('dashboard'))
if course_id in request.session.get("donation_for_course", {}):
chosen_price = request.session["donation_for_course"][course_id]
else:
chosen_price = verify... | reverification_submission_confirmation | identifier_name | |
addsingletongetter.spec.js | define([
'src/addsingletongetter'
], function (
addSingletonGetter
) {
describe('addSingletonGetter()', function () { | var instance;
function Dummy() {}
it('is a function', function () {
expect(addSingletonGetter).to.be.a('function');
});
it('adds the .getSingleton() static method to the given constructor',
function () {
expect(Dummy).to.not.have.property('getSingleton');
addSingletonG... | random_line_split | |
addsingletongetter.spec.js | define([
'src/addsingletongetter'
], function (
addSingletonGetter
) {
describe('addSingletonGetter()', function () {
var instance;
function Dummy() |
it('is a function', function () {
expect(addSingletonGetter).to.be.a('function');
});
it('adds the .getSingleton() static method to the given constructor',
function () {
expect(Dummy).to.not.have.property('getSingleton');
addSingletonGetter(Dummy);
expect(Dummy).to.hav... | {} | identifier_body |
addsingletongetter.spec.js | define([
'src/addsingletongetter'
], function (
addSingletonGetter
) {
describe('addSingletonGetter()', function () {
var instance;
function | () {}
it('is a function', function () {
expect(addSingletonGetter).to.be.a('function');
});
it('adds the .getSingleton() static method to the given constructor',
function () {
expect(Dummy).to.not.have.property('getSingleton');
addSingletonGetter(Dummy);
expect(Dummy).t... | Dummy | identifier_name |
Shortcuts.ts | /**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Editor from './Editor';
import Env from './Env';
import Tools ... | (e: KeyboardEvent): boolean {
return e.type === 'keydown' && e.keyCode >= 112 && e.keyCode <= 123;
}
private matchShortcut(e: KeyboardEvent, shortcut: Shortcut) {
if (!shortcut) {
return false;
}
if (shortcut.ctrl !== e.ctrlKey || shortcut.meta !== e.metaKey) {
return false;
}
... | isFunctionKey | identifier_name |
Shortcuts.ts | /**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Editor from './Editor';
import Env from './Env';
import Tools ... | if (e.type === 'keydown') {
self.executeShortcutAction(self.pendingPatterns[0]);
}
}
self.pendingPatterns.shift();
}
}
});
}
/**
* Adds a keyboard shortcut for some command or function.
*
* @method add
* @param {String} patte... | {
this.editor = editor;
const self = this;
editor.on('keyup keypress keydown', (e) => {
if ((self.hasModifier(e) || self.isFunctionKey(e)) && !e.isDefaultPrevented()) {
each(self.shortcuts, (shortcut) => {
if (self.matchShortcut(e, shortcut)) {
self.pendingPatterns = sho... | identifier_body |
Shortcuts.ts | /**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Editor from './Editor';
import Env from './Env';
import Tools ... |
}
shortcut.id = id.join(',');
// Handle special access modifier differently depending on Mac/Win
if (shortcut.access) {
shortcut.alt = true;
if (Env.mac) {
shortcut.ctrl = true;
} else {
shortcut.shift = true;
}
}
// Handle special meta modifier differently depending on Mac/W... | {
shortcut[key] = false;
} | conditional_block |
Shortcuts.ts | /**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Editor from './Editor';
import Env from './Env';
import Tools ... | }
}
// Handle special meta modifier differently depending on Mac/Win
if (shortcut.meta) {
if (Env.mac) {
shortcut.meta = true;
} else {
shortcut.ctrl = true;
shortcut.meta = false;
}
}
return shortcut;
};
class Shortcuts {
private readonly editor: Editor;
private reado... | shortcut.shift = true; | random_line_split |
0001_initial.py | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Message'
db.create_table('firstclass_message', (
... |
models = {
'firstclass.message': {
'Meta': {'object_name': 'Message'},
'data': ('django.db.models.fields.TextField', [], {'default': "'{}'"}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '40', 'primary_key': 'True'})
}
}
complete_ap... | db.delete_table('firstclass_message') | identifier_body |
0001_initial.py | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Message'
db.create_table('firstclass_message', (
... |
models = {
'firstclass.message': {
'Meta': {'object_name': 'Message'},
'data': ('django.db.models.fields.TextField', [], {'default': "'{}'"}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '40', 'primary_key': 'True'})
}
}
complete_app... |
def backwards(self, orm):
# Deleting model 'Message'
db.delete_table('firstclass_message') | random_line_split |
0001_initial.py | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Message'
db.create_table('firstclass_message', (
... | (self, orm):
# Deleting model 'Message'
db.delete_table('firstclass_message')
models = {
'firstclass.message': {
'Meta': {'object_name': 'Message'},
'data': ('django.db.models.fields.TextField', [], {'default': "'{}'"}),
'key': ('django.db.models.fields.... | backwards | identifier_name |
Shannon.py | # This script will calculate Shannon entropy from a MSA.
# Dependencies:
# Biopython, Matplotlib, Math
"""
Shannon's entropy equation (latex format):
H=-\sum_{i=1}^{M} P_i\,log_2\,P_i
Entropy is a measure of the uncertainty of a probability distribution (p1, ..... , pM)
https://stepic.org/lesson/Scoring-... |
import argparse
try:
parser = argparse.ArgumentParser(
description='Compute per base/residue Shannon entropy of a Multiple Sequence Alignment.')
parser.add_argument('-a',
'--alignment',
action='store',
... |
def parseArgs():
"""Parse command line arguments""" | random_line_split |
Shannon.py | # This script will calculate Shannon entropy from a MSA.
# Dependencies:
# Biopython, Matplotlib, Math
"""
Shannon's entropy equation (latex format):
H=-\sum_{i=1}^{M} P_i\,log_2\,P_i
Entropy is a measure of the uncertainty of a probability distribution (p1, ..... , pM)
https://stepic.org/lesson/Scoring-... |
def plot(index, sel, verbose):
""""Create a quick plot via matplotlib to visualise the extended spectrum"""
import matplotlib.pyplot as plt
if verbose > 0: print("Plotting data...")
plt.plot(index, sel)
plt.xlabel('MSA Position Index', fontsize=16)
plt.ylabel('Shannon Entropy', fontsize=16)... | """Calculate Shannon Entropy across the whole MSA"""
shannon_entropy_list = []
for col_no in xrange(len(list(alignment[0]))):
list_input = list(alignment[:, col_no])
shannon_entropy_list.append(shannon_entropy(list_input))
return shannon_entropy_list | identifier_body |
Shannon.py | # This script will calculate Shannon entropy from a MSA.
# Dependencies:
# Biopython, Matplotlib, Math
"""
Shannon's entropy equation (latex format):
H=-\sum_{i=1}^{M} P_i\,log_2\,P_i
Entropy is a measure of the uncertainty of a probability distribution (p1, ..... , pM)
https://stepic.org/lesson/Scoring-... |
for c1, c2 in zip(index, sel):
print(str(c1) + '\t' + str(c2))
if __name__ == '__main__':
main()
| print("Index" + '\t' + "Entropy") | conditional_block |
Shannon.py | # This script will calculate Shannon entropy from a MSA.
# Dependencies:
# Biopython, Matplotlib, Math
"""
Shannon's entropy equation (latex format):
H=-\sum_{i=1}^{M} P_i\,log_2\,P_i
Entropy is a measure of the uncertainty of a probability distribution (p1, ..... , pM)
https://stepic.org/lesson/Scoring-... | ():
"""Compute Shannon Entropy from a provided MSA."""
# Parse arguments
args = parseArgs()
# Convert object elements to standard variables for functions
msa = args.alignment
alnformat = args.alnformat
verbose = args.verbose
makeplot = args.makeplot
runningmean = args.runningmean
... | main | identifier_name |
Label.tsx | import * as React from 'react';
import classNames from 'classnames';
interface IProps {
text: string;
link?: string;
type?: 'default' | 'primary' | 'success' | 'warning' | 'alert' | 'highlight' | 'sd-green';
color?: string; // https://ui-framework.superdesk.org/#/components/colors
size?: 'small' | ... | else {
return (
<span className={classes}>
{this.props.text}
</span>
);
}
}
}
| {
return (
<a href={this.props.link} className={classes} onClick={this.props.onClick}>
{this.props.text}
</a>
);
} | conditional_block |
Label.tsx | import * as React from 'react';
import classNames from 'classnames';
interface IProps {
text: string;
link?: string;
type?: 'default' | 'primary' | 'success' | 'warning' | 'alert' | 'highlight' | 'sd-green'; | style?: 'filled' | 'hollow' | 'translucent'; // defaults to 'filled'
}
export class Label extends React.PureComponent<IProps> {
render() {
let classes = classNames('label', {
[`label--${this.props.size}`]: this.props.size !== 'normal' && this.props.size !== undefined,
'label--no-... | color?: string; // https://ui-framework.superdesk.org/#/components/colors
size?: 'small' | 'normal' | 'large'; // defaults to 'normal'
onClick?(): void;
noTransform?: boolean; | random_line_split |
Label.tsx | import * as React from 'react';
import classNames from 'classnames';
interface IProps {
text: string;
link?: string;
type?: 'default' | 'primary' | 'success' | 'warning' | 'alert' | 'highlight' | 'sd-green';
color?: string; // https://ui-framework.superdesk.org/#/components/colors
size?: 'small' | ... | extends React.PureComponent<IProps> {
render() {
let classes = classNames('label', {
[`label--${this.props.size}`]: this.props.size !== 'normal' && this.props.size !== undefined,
'label--no-transform': this.props.noTransform,
[`label--${this.props.type}`]: this.props.typ... | Label | identifier_name |
Label.tsx | import * as React from 'react';
import classNames from 'classnames';
interface IProps {
text: string;
link?: string;
type?: 'default' | 'primary' | 'success' | 'warning' | 'alert' | 'highlight' | 'sd-green';
color?: string; // https://ui-framework.superdesk.org/#/components/colors
size?: 'small' | ... | );
}
}
}
| {
let classes = classNames('label', {
[`label--${this.props.size}`]: this.props.size !== 'normal' && this.props.size !== undefined,
'label--no-transform': this.props.noTransform,
[`label--${this.props.type}`]: this.props.type !== undefined && !this.props.color,
[`... | identifier_body |
한겨레.ts | import * as $ from 'jquery';
import { clearStyles } from '../util';
import { Article } from '..';
export const cleanup = () => {
$('#scrollDiv').remove();
}
export function parse(): Article {
let articleBody = clearStyles($('.article-text')[0].cloneNode(true)); | $subtitle.remove();
$('.relation2-area', articleBody).remove();
const content = articleBody.innerHTML;
return {
title: $('#article_view_headline .title').text().trim(),
content: content,
subtitle: subtitle,
timestamp: (() => {
let $span = $('#article_view_head... | let $subtitle = $('.subtitle', articleBody);
const subtitle = $subtitle.html(); | random_line_split |
한겨레.ts | import * as $ from 'jquery';
import { clearStyles } from '../util';
import { Article } from '..';
export const cleanup = () => {
$('#scrollDiv').remove();
}
export function parse(): Article | reporters: []
};
}
| {
let articleBody = clearStyles($('.article-text')[0].cloneNode(true));
let $subtitle = $('.subtitle', articleBody);
const subtitle = $subtitle.html();
$subtitle.remove();
$('.relation2-area', articleBody).remove();
const content = articleBody.innerHTML;
return {
title: $('#article_v... | identifier_body |
한겨레.ts | import * as $ from 'jquery';
import { clearStyles } from '../util';
import { Article } from '..';
export const cleanup = () => {
$('#scrollDiv').remove();
}
export function | (): Article {
let articleBody = clearStyles($('.article-text')[0].cloneNode(true));
let $subtitle = $('.subtitle', articleBody);
const subtitle = $subtitle.html();
$subtitle.remove();
$('.relation2-area', articleBody).remove();
const content = articleBody.innerHTML;
return {
title: $... | parse | identifier_name |
test_institution_nodes_list.py | from nose.tools import *
from tests.base import ApiTestCase
from tests.factories import InstitutionFactory, AuthUserFactory, NodeFactory
from framework.auth import Auth
from api.base.settings.defaults import API_BASE
class TestInstitutionNodeList(ApiTestCase):
def | (self):
super(TestInstitutionNodeList, self).setUp()
self.institution = InstitutionFactory()
self.node1 = NodeFactory(is_public=True)
self.node1.primary_institution = self.institution
self.node1.save()
self.user1 = AuthUserFactory()
self.user2 = AuthUserFactory()
... | setUp | identifier_name |
test_institution_nodes_list.py | from nose.tools import *
from tests.base import ApiTestCase
from tests.factories import InstitutionFactory, AuthUserFactory, NodeFactory
from framework.auth import Auth
from api.base.settings.defaults import API_BASE
class TestInstitutionNodeList(ApiTestCase):
def setUp(self):
super(TestInstitutionNodeLi... |
def test_return_private_nodes_mixed_auth(self):
res = self.app.get(self.institution_node_url, auth=self.user2.auth)
assert_equal(res.status_code, 200)
ids = [each['id'] for each in res.json['data']]
assert_in(self.node1._id, ids)
assert_in(self.node2._id, ids)
ass... | res = self.app.get(self.institution_node_url, auth=self.user1.auth)
assert_equal(res.status_code, 200)
ids = [each['id'] for each in res.json['data']]
assert_in(self.node1._id, ids)
assert_in(self.node2._id, ids)
assert_not_in(self.node3._id, ids) | identifier_body |
test_institution_nodes_list.py | from nose.tools import *
from tests.base import ApiTestCase
from tests.factories import InstitutionFactory, AuthUserFactory, NodeFactory
from framework.auth import Auth
from api.base.settings.defaults import API_BASE
class TestInstitutionNodeList(ApiTestCase):
def setUp(self):
super(TestInstitutionNodeLi... | self.node2.primary_institution = self.institution
self.node2.add_contributor(self.user2, auth=Auth(self.user1))
self.node2.save()
self.node3 = NodeFactory(creator=self.user2, is_public=False)
self.node3.primary_institution = self.institution
self.node3.save()
sel... | self.node1.primary_institution = self.institution
self.node1.save()
self.user1 = AuthUserFactory()
self.user2 = AuthUserFactory()
self.node2 = NodeFactory(creator=self.user1, is_public=False) | random_line_split |
PostgresNoSQLTable.py | import copy
import json
from psycopg2.extensions import AsIs
from psycopg2.extras import RealDictCursor
from pg4nosql import DEFAULT_JSON_COLUMN_NAME, DEFAULT_ROW_IDENTIFIER
from pg4nosql.PostgresNoSQLQueryStructure import PostgresNoSQLQueryStructure
from pg4nosql.PostgresNoSQLResultItem import PostgresNoSQLResultItem
... |
def query_one(self, query='True', columns='*'):
result = self.query(query, columns)
if not result:
return None
return result[0]
def get_columns(self):
self.cursor.execute(self.__SQL_GET_COLUMNS, (self.name,))
columns = map(lambda m: m['column_name'], self.c... | self.cursor.execute(self.__SQL_QUERY_WITH_JOIN, (AsIs(columns),
AsIs(self.name),
AsIs(table_name),
AsIs(on_statement),
... | identifier_body |
PostgresNoSQLTable.py | import copy
import json
from psycopg2.extensions import AsIs
from psycopg2.extras import RealDictCursor
from pg4nosql import DEFAULT_JSON_COLUMN_NAME, DEFAULT_ROW_IDENTIFIER
from pg4nosql.PostgresNoSQLQueryStructure import PostgresNoSQLQueryStructure
from pg4nosql.PostgresNoSQLResultItem import PostgresNoSQLResultItem
... |
def put(self, json_data, auto_commit=True, **relational_data):
relational_data.update({DEFAULT_JSON_COLUMN_NAME: json_data})
return self.insert(auto_commit=auto_commit, **relational_data)
def save(self, record, auto_commit=True):
data = copy.deepcopy(record.get_record())
objec... | self.commit() | conditional_block |
PostgresNoSQLTable.py | import copy
import json
from psycopg2.extensions import AsIs
from psycopg2.extras import RealDictCursor
from pg4nosql import DEFAULT_JSON_COLUMN_NAME, DEFAULT_ROW_IDENTIFIER
from pg4nosql.PostgresNoSQLQueryStructure import PostgresNoSQLQueryStructure
from pg4nosql.PostgresNoSQLResultItem import PostgresNoSQLResultItem
... | (PostgresNoSQLQueryStructure):
__SQL_INSERT_JSON = "INSERT INTO %s(" + DEFAULT_JSON_COLUMN_NAME + " %s) VALUES(%s %s) RETURNING " + DEFAULT_ROW_IDENTIFIER
__SQL_GET_JSON = 'SELECT * FROM %s WHERE ' + DEFAULT_ROW_IDENTIFIER + '=%s'
__SQL_GET_COLUMNS = 'select column_name from information_schema.columns where... | PostgresNoSQLTable | identifier_name |
PostgresNoSQLTable.py | import copy
import json
from psycopg2.extensions import AsIs
from psycopg2.extras import RealDictCursor
from pg4nosql import DEFAULT_JSON_COLUMN_NAME, DEFAULT_ROW_IDENTIFIER
from pg4nosql.PostgresNoSQLQueryStructure import PostgresNoSQLQueryStructure
from pg4nosql.PostgresNoSQLResultItem import PostgresNoSQLResultItem
... | if record is None:
return record
return PostgresNoSQLResultItem(record, self)
def query_join(self, table_name, on_statement, query='True', columns='*'):
self.cursor.execute(self.__SQL_QUERY_WITH_JOIN, (AsIs(columns),
AsIs... | self.cursor.execute(self.__SQL_GET_JSON, (AsIs(self.name), object_id))
record = self.cursor.fetchone()
| random_line_split |
test_pp_psc_delta_stdp.py | # -*- coding: utf-8 -*-
#
# test_pp_psc_delta_stdp.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the ... |
sg_pre = nest.Create('spike_generator')
nest.SetStatus(sg_pre, {'spike_times': np.arange(Dt, nsteps * Dt, 10. * Dt)})
nest.Connect(sg_pre, nrn_pre)
mm = nest.Create('multimeter')
nest.SetStatus(mm, {'record_from': ['V_m']})
nest.Connect(mm, nrn_post1 + nrn_post2)
sd = nest.Create('spike_detector')
nest.Connect(nrn_p... | conn1 = nest.GetConnections(nrn_pre, nrn_post1)
conn2 = nest.GetConnections(nrn_pre, nrn_post2) | random_line_split |
test_pp_psc_delta_stdp.py | # -*- coding: utf-8 -*-
#
# test_pp_psc_delta_stdp.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the ... | print nest.GetStatus(nrn, keys=['model', 'archiver_length'])[0] | conditional_block | |
lib.rs | impl MouseTranslationData {
fn new<Sz: Into<Size>>(size: Sz) -> Self {
MouseTranslationData {
x_axis_motion_inverted: false,
y_axis_motion_inverted: false,
x_axis_scroll_inverted: false,
y_axis_scroll_inverted: false,
sensitivity: 0.0,
... | {
(a, ButtonTuple(buttons[0], buttons[1], buttons[2]))
} | conditional_block | |
lib.rs | new<Sz: Into<Size>>(size: Sz) -> Self {
MouseTranslationData {
x_axis_motion_inverted: false,
y_axis_motion_inverted: false,
x_axis_scroll_inverted: false,
y_axis_scroll_inverted: false,
sensitivity: 0.0,
viewport_size: size.into()
... | } else {
unreachable!();
} | random_line_split | |
lib.rs | ::fmt::{Debug, Formatter, Result};
use std::hash::{Hash, BuildHasher};
use viewport::Viewport;
use window::Size;
pub use builder::Builder;
/// Represents a logical action to be bound to a particular button press, e.g.
/// jump, attack, or move forward. Needs to be hashable, as it is used as a
/// lookup key when rebi... | (&self) -> usize {
(std::cmp::min(self.i as isize, 3) - 3).abs() as usize
}
}
/// An object which translates piston::input::Input events into input_map::Translated<A> events
#[derive(Clone, Debug, PartialEq)]
pub struct InputTranslator<A: Action, S: BuildHasher = RandomState> {
keymap: HashMap<Button, ... | len | identifier_name |
lib.rs | ::fmt::{Debug, Formatter, Result};
use std::hash::{Hash, BuildHasher};
use viewport::Viewport;
use window::Size;
pub use builder::Builder;
/// Represents a logical action to be bound to a particular button press, e.g.
/// jump, attack, or move forward. Needs to be hashable, as it is used as a
/// lookup key when rebi... |
/// Get the maximum number of buttons which this tuple can contain.
pub fn max_buttons(&self) -> usize {
3
}
/// Returns the number of buttons in the ButtonTuple which are not `None`.
pub fn num_buttons_set(&self) -> usize {
self.iter().map(|b| b.is_some() as usize).fold(0, std::o... | {
let sbtn = Some(button);
match self {
&mut ButtonTuple(None, _, _) => {
self.0 = sbtn;
true
}
&mut ButtonTuple(_, None, _) => {
self.1 = sbtn;
true
}
&mut ButtonTuple(_, _, None)... | identifier_body |
weapon-vendor.ts | import { NPC } from '../../../../../shared/models/npc';
import { VendorResponses } from '../../common-responses';
import { sample } from 'lodash';
export const setup = async (npc: NPC) => {
npc.hostility = 'Never';
npc.affiliation = 'Weapon Vendor'; | 'Antanian Longsword',
'Antanian Greatsword',
'Antanian Staff',
'Antanian Crossbow',
'Antanian Shortbow',
'Antanian Longbow',
'Antanian Wooden Shield',
'Antanian Halberd',
'Antanian Spear',
'Antanian Arrows',
'Smith Hammer'
];
npc.$$room.npcLoader.loadVendorItems(npc, ven... |
const vendorItems = [
'Antanian Dagger',
'Antanian Shortsword', | random_line_split |
_job.py | # -*- coding: ascii -*-
r"""
:Copyright:
Copyright 2014 - 2016
Andr\xe9 Malo or his licensors, as applicable
:License:
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.... | self.locks = _lock.validate(locks)
self.locks_waiting = None
self.importance = importance
self.extra = extra
self.predecessors = set()
self.predecessors_waiting = None
self.attempts = attempts
self.not_before = not_before
for item in predecessors o... | execution attempts (``[ExecutionAttemptInterface, ...]``)
"""
self.id = job_id
self.desc = desc
self.group = group | random_line_split |
_job.py | # -*- coding: ascii -*-
r"""
:Copyright:
Copyright 2014 - 2016
Andr\xe9 Malo or his licensors, as applicable
:License:
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.... |
class Job(object):
"""
Job after is been scheduled.
:See: `JobInterface`
"""
__implements__ = [_interfaces.JobInterface]
def __init__(self, job_id, desc, group, locks, importance, not_before,
extra, predecessors, attempts):
"""
Initialization
:Param... | """
Determine the largest job ID assigned until now
:Return: The ID. It's ``0``, if no job ID was assigned until now (job IDs
start with ``1``)
:Rtype: ``id``
"""
# this inspects the counter iterable by calling pickling methods and
# retrieving the next value from there and then su... | identifier_body |
_job.py | # -*- coding: ascii -*-
r"""
:Copyright:
Copyright 2014 - 2016
Andr\xe9 Malo or his licensors, as applicable
:License:
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.... | (self, job_id):
"""
Add predecessor job ID
Duplicates are silently ignored.
:See: `interfaces.JobInterface.depend_on`
"""
assert self.predecessors_waiting is None
try:
job_id = int(job_id)
except TypeError:
raise ValueError("Inva... | depend_on | identifier_name |
_job.py | # -*- coding: ascii -*-
r"""
:Copyright:
Copyright 2014 - 2016
Andr\xe9 Malo or his licensors, as applicable
:License:
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.... |
if parent is not None:
graph.add(parent, (True, virtual_id))
pre.append(parent)
else:
graph.add((False, None), (True, virtual_id))
except DependencyCycle as e:
# remap to our input (todos and not some weird virtual IDs)
raise ... | pre = []
virtual_id = len(virtuals)
todos[todo_id] = virtual_id, pre, todo
virtuals[virtual_id] = todo_id
for parent_id in todo.predecessors():
graph.add((False, parent_id), (True, virtual_id))
pre.append((False, pa... | conditional_block |
spoke.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
for all "spoke" CASUs, they emit when reading one specific directional
IR sensor.
set the direction that is sensed by the -d flag, from NESW
this is borrowed from `examples/targeted_messaging`, with server setup
that happens behind the scenes (i.e. from RTC files!)
... | self.__casu.set_diagnostic_led_rgb(0, 0, 1, casu.DLED_TOP)
self.old_state = self.state
self.state = 'Blue On'
# West => green
elif self._ctr_dir == 'W' and ((self.__casu.get_range(casu.IR_BR) <
2 or self.... | self.state = 'Red On'
# South => blue
elif self._ctr_dir == 'S' and self.__casu.get_range(casu.IR_B) < 2: | random_line_split |
spoke.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
for all "spoke" CASUs, they emit when reading one specific directional
IR sensor.
set the direction that is sensed by the -d flag, from NESW
this is borrowed from `examples/targeted_messaging`, with server setup
that happens behind the scenes (i.e. from RTC files!)
... |
def stop(self):
self.__casu.stop()
def send_msg(self):
while True:
# North side => yellow
if self._ctr_dir == 'F' and self.__casu.get_range(casu.IR_F) < 2:
self.__casu.set_diagnostic_led_rgb(1, 1, 0, casu.DLED_TOP)
self.old_state = sel... | self.__casu = casu.Casu(rtc_file)
self._ctr_dir = direction
self.old_state = 'Off'
self.state = 'Off'
self.verb = verb | identifier_body |
spoke.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
for all "spoke" CASUs, they emit when reading one specific directional
IR sensor.
set the direction that is sensed by the -d flag, from NESW
this is borrowed from `examples/targeted_messaging`, with server setup
that happens behind the scenes (i.e. from RTC files!)
... | :
def __init__(self, rtc_file, direction, verb=False):
self.__casu = casu.Casu(rtc_file)
self._ctr_dir = direction
self.old_state = 'Off'
self.state = 'Off'
self.verb = verb
def stop(self):
self.__casu.stop()
def send_msg(self):
while True:
... | CasuController | identifier_name |
spoke.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
for all "spoke" CASUs, they emit when reading one specific directional
IR sensor.
set the direction that is sensed by the -d flag, from NESW
this is borrowed from `examples/targeted_messaging`, with server setup
that happens behind the scenes (i.e. from RTC files!)
... |
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--rtc-path', type=str, default='',
help="location of RTC files to configure CASUs",)
parser.add_argument('-n', '--name', type=str, default='casu-ctr',
help="location of RTC files to configure C... | self.send_msg()
time.sleep(0.5) | conditional_block |
mod.rs | // SPDX-License-Identifier: Unlicense
//! Unifies the CPU-architecture specific code for the supported CPU's.
//!
//! All architectures are linked in for unit testing on the host platform.
//! Only the target architecture is linked for release builds (including when
//! used for integration testing).
//!
//! The targe... | // pub use x86_64 as arch; | // #[cfg(all(not(test), target_arch = "x86_64"))] | random_line_split |
scale.js | 'use strict'
let cli = require('heroku-cli-util')
let co = require('co')
let emptyFormationErr = (app) => {
return new Error(`No process types on ${cli.color.app(app)}.
Upload a Procfile to add process types.
https://devcenter.heroku.com/articles/procfile`)
}
function * run (context, heroku) {
const compact = re... |
}
let cmd = {
variableArgs: true,
description: 'scale dyno quantity up or down',
help: `Appending a size (eg. web=2:Standard-2X) allows simultaneous scaling and resizing.
Omitting any arguments will display the app's current dyno formation, in a
format suitable for passing back into ps:scale.
Examples:
$ h... | {
yield cli.action('Scaling dynos', {success: false}, co(function * () {
let formation = yield heroku.request({method: 'PATCH', path: `/apps/${app}/formation`, body: {updates: changes}})
let output = formation.filter((f) => changes.find((c) => c.type === f.type))
.map((d) => `${cli.color.green(d... | conditional_block |
scale.js | 'use strict'
let cli = require('heroku-cli-util')
let co = require('co')
let emptyFormationErr = (app) => {
return new Error(`No process types on ${cli.color.app(app)}.
Upload a Procfile to add process types.
https://devcenter.heroku.com/articles/procfile`)
}
function * run (context, heroku) {
const compact = re... | function parse (args) {
return compact(args.map((arg) => {
let change = arg.match(/^([a-zA-Z0-9_]+)([=+-]\d+)(?::([\w-]+))?$/)
if (!change) return
let quantity = change[2][0] === '=' ? change[2].substr(1) : change[2]
return {type: change[1], quantity, size: change[3]}
}))
}
let ch... | let app = context.app
| random_line_split |
scale.js | 'use strict'
let cli = require('heroku-cli-util')
let co = require('co')
let emptyFormationErr = (app) => {
return new Error(`No process types on ${cli.color.app(app)}.
Upload a Procfile to add process types.
https://devcenter.heroku.com/articles/procfile`)
}
function * run (context, heroku) {
const compact = re... |
let changes = parse(context.args)
if (changes.length === 0) {
let formation = yield heroku.get(`/apps/${app}/formation`)
if (formation.length === 0) throw emptyFormationErr(app)
cli.log(formation.map((d) => `${d.type}=${d.quantity}:${d.size}`).sort().join(' '))
} else {
yield cli.action('Scaling... | {
return compact(args.map((arg) => {
let change = arg.match(/^([a-zA-Z0-9_]+)([=+-]\d+)(?::([\w-]+))?$/)
if (!change) return
let quantity = change[2][0] === '=' ? change[2].substr(1) : change[2]
return {type: change[1], quantity, size: change[3]}
}))
} | identifier_body |
scale.js | 'use strict'
let cli = require('heroku-cli-util')
let co = require('co')
let emptyFormationErr = (app) => {
return new Error(`No process types on ${cli.color.app(app)}.
Upload a Procfile to add process types.
https://devcenter.heroku.com/articles/procfile`)
}
function * run (context, heroku) {
const compact = re... | (args) {
return compact(args.map((arg) => {
let change = arg.match(/^([a-zA-Z0-9_]+)([=+-]\d+)(?::([\w-]+))?$/)
if (!change) return
let quantity = change[2][0] === '=' ? change[2].substr(1) : change[2]
return {type: change[1], quantity, size: change[3]}
}))
}
let changes = parse(co... | parse | identifier_name |
_textfont.py | import _plotly_utils.basevalidators
class TextfontValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="textfont", parent_name="funnelarea", **kwargs):
| system. The Chart Studio Cloud (at
https://chart-studio.plotly.com or on-premise)
generates images on a server, where only a
select number of fonts are installed and
supported. These include "Arial", "Balto",
"Courier New", ... | super(TextfontValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Textfont"),
data_docs=kwargs.pop(
"data_docs",
"""
color
colorsrc
... | identifier_body |
_textfont.py | import _plotly_utils.basevalidators
| plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Textfont"),
data_docs=kwargs.pop(
"data_docs",
"""
color
colorsrc
Sets the source reference on Chart Stu... | class TextfontValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="textfont", parent_name="funnelarea", **kwargs):
super(TextfontValidator, self).__init__( | random_line_split |
_textfont.py | import _plotly_utils.basevalidators
class TextfontValidator(_plotly_utils.basevalidators.CompoundValidator):
def | (self, plotly_name="textfont", parent_name="funnelarea", **kwargs):
super(TextfontValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Textfont"),
data_docs=kwargs.pop(
"data_docs... | __init__ | identifier_name |
strings.js | define({
root: ({
display: {
elevationProfileTitle: "Elevations Profile",
showMe: "show me",
selectLine: "<span style='font-size:medium'><b>Select</b> a feature in the map.</span>",
popupRequirement: "NOTE: the feature must be in a layer with Popups enabled."... | "fr": 1,
"he": 1,
"it": 1,
"ja": 1,
"ko": 1,
"lt": 1,
"lv": 1,
"nl": 1,
"nb": 1,
"pl": 1,
"pt-br": 1,
"pt-pt": 1,
"ro": 1,
"ru": 1,
"sv": 1,
"tr": 1,
"th": 1,
"vi": 1,
"zh-cn": 1
}); | "et": 1,
"fi": 1, | random_line_split |
test-utils.js | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your ... |
export function randomInteger(max = 1000000) {
return Math.floor(Math.random() * max);
}
export async function asyncThrows(fn, ...params) {
let errorThrown = false;
try {
await fn(...params);
} catch (err) {
errorThrown = true;
}
return errorThrown;
}
export async function cleanUp(knex, tableName... |
const id = await knex('fin_entity')
.insert({
disclosure_id: entity.disclosureId,
status: entity.status,
active: entity.active
}, 'id');
return id[0];
}
| identifier_body |
test-utils.js | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your ... |
export function createComment(disclosureId, user) {
return {
disclosureId,
topicSection: DISCLOSURE_STEP.QUESTIONNAIRE,
topicId: 1,
text: 'blah',
userId: hashCode(user),
author: user,
date: new Date(),
piVisible: true,
reviewerVisible: true
};
}
export async function insertComm... | config_id: disclosure.configId,
submitted_by: user_id
}, 'id');
return id[0];
} | random_line_split |
test-utils.js | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your ... | knex, id) {
const comments = await knex('review_comment')
.select(
'id',
'disclosure_id as disclosureId',
'topic_section as topicSection',
'topic_id as topicId',
'text',
'user_id as userId',
'author',
'date',
'pi_visible as piVisible',
'reviewer_visible ... | etComment( | identifier_name |
tree.py | = [['slashdot', 'USA', 'yes', 18, 'None'],
['google', 'France', 'yes', 23, 'Premium'],
['digg', 'USA', 'yes', 24, 'Basic'],
['kiwitobes', 'France', 'yes', 23, 'Basic'],
['google', 'UK', 'no', 21, 'Premium'],
['(direct)', 'New Zealand', 'no', 12, 'None'],
... |
else:
if v == tree.value: branch = tree.tb
else: branch = tree.fb
return mdclassify(obs, branch)
def variance(rows):
if len(rows)==0:
return 0
data = [float | if v>=tree.value: branch = tree.tb
else: branch = tree.fb | conditional_block |
tree.py | [['slashdot', 'USA', 'yes', 18, 'None'],
['google', 'France', 'yes', 23, 'Premium'],
['digg', 'USA', 'yes', 24, 'Basic'],
['kiwitobes', 'France', 'yes', 23, 'Basic'],
['google', 'UK', 'no', 21, 'Premium'],
['(direct)', 'New Zealand', 'no', 12, 'None'],
... |
def drawnode(draw, trees, x, y, widdelta=100, depdelta=100):
if trees.results is None:
wf = getwidth(trees.fb) * widdelta
wt = getwidth(trees.tb) * widdelta
left = x - (wf + wt) / 2
right = x + (wf + wt) / 2
if isinstance(trees.value, int) or isinstance(trees.value, floa... | w = getwidth(trees) * widdelta
h = getdepth(trees) * depdelta + 120
img = Image.new('RGB', (w, h), (255, 255, 255))
draw = ImageDraw.Draw(img)
drawnode(draw, trees, w / 2, 20, widdelta, depdelta)
img.save(jpeg, 'JPEG') | identifier_body |
tree.py | [['slashdot', 'USA', 'yes', 18, 'None'],
['google', 'France', 'yes', 23, 'Premium'],
['digg', 'USA', 'yes', 24, 'Basic'],
['kiwitobes', 'France', 'yes', 23, 'Basic'],
['google', 'UK', 'no', 21, 'Premium'],
['(direct)', 'New Zealand', 'no', 12, 'None'],
... | (object):
"""docstring for decisionnode"""
def __init__(self, col=-1, value=None, results=None, tb=None, fb=None):
self.col = col
self.value = value
self.results = results
self.tb = tb
self.fb = fb
def divideset(rows, column, value):
split_function = None
if i... | decisionnode | identifier_name |
tree.py | [['slashdot', 'USA', 'yes', 18, 'None'],
['google', 'France', 'yes', 23, 'Premium'],
['digg', 'USA', 'yes', 24, 'Basic'],
['kiwitobes', 'France', 'yes', 23, 'Basic'],
['google', 'UK', 'no', 21, 'Premium'],
['(direct)', 'New Zealand', 'no', 12, 'None'],
... |
self.col = col
self.value = value
self.results = results
self.tb = tb
self.fb = fb
def divideset(rows, column, value):
split_function = None
if isinstance(value, int) or isinstance(value, float):
split_function = lambda row: row[column] >= value
else:
... | def __init__(self, col=-1, value=None, results=None, tb=None, fb=None): | random_line_split |
a.rs | extern crate regex;
use std::fs::File;
use std::io::{BufReader, BufRead};
use std::str;
use std::str::FromStr;
use regex::Regex;
fn main() {
let mut summation = 0;
let mut amount_of_correct = 0;
let regex = Regex::new(r"^(.*)-(\d+)\[(.+)\]$").unwrap();
for line_res in BufReader::new(File::open("input"... | (line: &str) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz";
let mut frequency = vec![0isize; 26];
for character in line.chars() {
match alphabet.find(character) {
Some(index) => frequency[index] += 1,
None => (),
}
}
let mut result = String::with_cap... | gen_checksum | identifier_name |
a.rs | extern crate regex;
use std::fs::File;
use std::io::{BufReader, BufRead};
use std::str;
use std::str::FromStr;
use regex::Regex;
fn main() {
let mut summation = 0;
let mut amount_of_correct = 0;
let regex = Regex::new(r"^(.*)-(\d+)\[(.+)\]$").unwrap();
for line_res in BufReader::new(File::open("input"... | {
let alphabet = "abcdefghijklmnopqrstuvwxyz";
let mut frequency = vec![0isize; 26];
for character in line.chars() {
match alphabet.find(character) {
Some(index) => frequency[index] += 1,
None => (),
}
}
let mut result = String::with_capacity(5);
for _ in ... | identifier_body | |
a.rs | extern crate regex; | use std::str;
use std::str::FromStr;
use regex::Regex;
fn main() {
let mut summation = 0;
let mut amount_of_correct = 0;
let regex = Regex::new(r"^(.*)-(\d+)\[(.+)\]$").unwrap();
for line_res in BufReader::new(File::open("input").expect("")).lines() {
let line = line_res.unwrap();
let c... |
use std::fs::File;
use std::io::{BufReader, BufRead}; | random_line_split |
helpers.ts | import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
import { OutputFile } from './interfaces';
const double = /\/\//;
export function toUnix(fileName: string): string {
let res: string = fileName.replace(/\\/g, '/');
while (res.match(double)) {
res = res.replace(do... | (moduleId) {
let fileName = require.resolve(moduleId);
let text = fs.readFileSync(fileName, 'utf8');
return {
fileName: fileName,
text: text
};
}
const TYPESCRIPT_EXTENSION = /\.(d\.)?(t|j)s$/;
export function withoutTypeScriptExtension(fileName: string): string {
return fileName.r... | loadLib | identifier_name |
helpers.ts | import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
import { OutputFile } from './interfaces';
const double = /\/\//;
export function toUnix(fileName: string): string {
let res: string = fileName.replace(/\\/g, '/');
while (res.match(double)) {
res = res.replace(do... |
function isSourceMapEmit(fileName, outputFileName, sourceFileName) {
return sourceFileName === fileName
// typescript now emits .jsx files for .tsx files.
&& (outputFileName.substr(-7) === '.js.map' || outputFileName.substr(-8) === '.jsx.map');
}
function isDeclarationEmit(fileName, outputFileNam... | {
return sourceFileName === fileName
// typescript now emits .jsx files for .tsx files.
&& (outputFileName.substr(-3) === '.js' || outputFileName.substr(-4) === '.jsx');
} | identifier_body |
helpers.ts | import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
import { OutputFile } from './interfaces';
const double = /\/\//;
export function toUnix(fileName: string): string {
let res: string = fileName.replace(/\\/g, '/');
while (res.match(double)) {
res = res.replace(do... |
return {
text: text,
sourceMap: sourceMap,
declaration
};
}
export function codegenErrorReport(errors) {
return errors
.map(function (error) {
return 'console.error(' + JSON.stringify(error) + ');';
})
.join('\n');
}
export function formatError... | {
let o = output.outputFiles[i];
let outputFileName = o.name;
let sourceFileName = withoutExt(o.name);
if (isFileEmit(fileName, outputFileName, sourceFileName)) {
text = o.text;
}
if (isSourceMapEmit(fileName, outputFileName, sourceFileName)) {
sou... | conditional_block |
helpers.ts | import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
import { OutputFile } from './interfaces';
const double = /\/\//;
export function toUnix(fileName: string): string {
let res: string = fileName.replace(/\\/g, '/');
while (res.match(double)) {
res = res.replace(do... |
const TYPESCRIPT_EXTENSION = /\.(d\.)?(t|j)s$/;
export function withoutTypeScriptExtension(fileName: string): string {
return fileName.replace(TYPESCRIPT_EXTENSION, '');
} | return {
fileName: fileName,
text: text
};
} | random_line_split |
mass_spec_reverter.py | # ===============================================================================
# Copyright 2014 Jake Ross
#
# 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... | (self, src, isok):
dbiso = next(
(
i
for i in src.isotopes
if i.molecular_weight.name == isok and i.kind == "signal"
),
None,
)
dbiso_bs = next(
(
i
for i in src.isotop... | _generate_blobs | identifier_name |
mass_spec_reverter.py | # ===============================================================================
# Copyright 2014 Jake Ross
#
# 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... |
def do_reimport(self):
if self._connect_to_source():
if self._connect_to_destination():
self._do_reimport()
def setup_source(self):
src = IsotopeDatabaseManager(connect=False, bind=False)
db = src.db
db.trait_set(
name="pychrondata",
... | self._do_revert() | conditional_block |
mass_spec_reverter.py | # ===============================================================================
# Copyright 2014 Jake Ross
#
# 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... | )
self.source = src
def setup_destination(self):
dest = MassSpecDatabaseAdapter()
dest.trait_set(
name="massspecdata_crow",
kind="mysql",
username="root",
password=os.environ.get("DB_PWD"),
)
self.destination = dest
... | kind="mysql",
host=os.environ.get("HOST"),
username="root",
password=os.environ.get("DB_PWD"), | random_line_split |
mass_spec_reverter.py | # ===============================================================================
# Copyright 2014 Jake Ross
#
# 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... |
def _revert_analyses(self, rid):
"""
rid: str. e.g 12345
revert all analyses with this labnumber
"""
def _revert_analysis(self, rid):
"""
rid: str. e.g 12345-01 or 12345-01A
only revert this specific analysis
"""
# l,a,s = strip_runid(r... | """
rid: str. typical runid e.g 12345, 12345-01, 12345-01A
if rid lacks an aliquot revert all aliquots and steps for
this rid
"""
self.debug("reverting {}".format(rid))
if "-" in rid:
# this is a specific analysis
self._revert_analysis(rid)
... | identifier_body |
snapshotops.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.ap... | src_vhd_path)
export_dir = self._pathutils.get_export_dir(instance_name)
dest_vhd_path = os.path.join(export_dir, os.path.basename(
src_vhd_path))
LOG.debug(_('Copying VHD %(src_vhd_path)s to %(dest_vhd_path)s'),
locals())
... | src_base_disk_path = self._vhdutils.get_vhd_parent_path( | random_line_split |
snapshotops.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.ap... | (self, context, name, image_vhd_path):
(glance_image_service,
image_id) = glance.get_remote_image_service(context, name)
image_metadata = {"is_public": False,
"disk_format": "vhd",
"container_format": "bare",
"propert... | _save_glance_image | identifier_name |
snapshotops.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.ap... |
def _save_glance_image(self, context, name, image_vhd_path):
(glance_image_service,
image_id) = glance.get_remote_image_service(context, name)
image_metadata = {"is_public": False,
"disk_format": "vhd",
"container_format": "bare",
... | self._pathutils = pathutils.PathUtils()
self._vmutils = vmutils.VMUtils()
self._vhdutils = vhdutils.VHDUtils() | identifier_body |
snapshotops.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.ap... |
LOG.debug(_("Updating Glance image %(image_id)s with content from "
"merged disk %(image_vhd_path)s"), locals())
update_task_state(task_state=task_states.IMAGE_UPLOADING,
expected_state=task_states.IMAGE_PENDING_UPLOAD)
self._sa... | basename = os.path.basename(src_base_disk_path)
dest_base_disk_path = os.path.join(export_dir, basename)
LOG.debug(_('Copying base disk %(src_vhd_path)s to '
'%(dest_base_disk_path)s'), locals())
self._pathutils.copyfile(src_base_disk_path,
... | conditional_block |
row-actions.tsx | /*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
* This file is part of Neo4j.
* Neo4j 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 optio... | } | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.