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 |
|---|---|---|---|---|
FFTSceneManager.py | import numpy as np
from PyQt5.QtGui import QPainterPath, QPen
from PyQt5.QtWidgets import QGraphicsPathItem
from urh import settings
from urh.cythonext import path_creator
from urh.ui.painting.GridScene import GridScene
from urh.ui.painting.SceneManager import SceneManager
class FFTSceneManager(SceneManager):
de... | (self):
super().eliminate()
self.peak = None
self.peak_item = None
| eliminate | identifier_name |
FFTSceneManager.py | import numpy as np
from PyQt5.QtGui import QPainterPath, QPen
from PyQt5.QtWidgets import QGraphicsPathItem
from urh import settings
from urh.cythonext import path_creator
from urh.ui.painting.GridScene import GridScene
from urh.ui.painting.SceneManager import SceneManager
class FFTSceneManager(SceneManager):
de... | self.peak_item.setPath(peak_path)
except RuntimeWarning:
pass
def init_scene(self, draw_grid=True):
self.scene.draw_grid = draw_grid
self.peak = self.plot_data if len(self.peak) < self.num_samples else np.maximum(self.peak, self.plot_data)
self.scene.set... | random_line_split | |
FFTSceneManager.py | import numpy as np
from PyQt5.QtGui import QPainterPath, QPen
from PyQt5.QtWidgets import QGraphicsPathItem
from urh import settings
from urh.cythonext import path_creator
from urh.ui.painting.GridScene import GridScene
from urh.ui.painting.SceneManager import SceneManager
class FFTSceneManager(SceneManager):
| pass
def init_scene(self, draw_grid=True):
self.scene.draw_grid = draw_grid
self.peak = self.plot_data if len(self.peak) < self.num_samples else np.maximum(self.peak, self.plot_data)
self.scene.setSceneRect(0, -5, self.num_samples, 10)
def clear_path(self):
for ite... | def __init__(self, parent, graphic_view=None):
self.peak = []
super().__init__(parent)
self.scene = GridScene(parent=graphic_view)
self.scene.setBackgroundBrush(settings.BGCOLOR)
self.peak_item = self.scene.addPath(QPainterPath(), QPen(settings.PEAK_COLOR, 0)) # type: QGraphic... | identifier_body |
paymill_token.js | // CreateToken call below
var PAYMILL_PUBLIC_KEY = paymill_token.public_key;
jQuery(document).ready(function($) {
var is_error = false;
$(document).ready(function () {
function PaymillResponseHandler(error, result) {
if (error) {
if(error.apierror == 'f... | else if(error.apierror == 'field_invalid_card_holder'){
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_cardholder);
}else{
jQuery("#paymill_checkout_errors").text(error.apierror);
}
} else {
jQuery("... | {
jQuery("#paymill_checkout_errors").text(paymill_token.expired_card);
} | conditional_block |
paymill_token.js | // CreateToken call below
var PAYMILL_PUBLIC_KEY = paymill_token.public_key;
jQuery(document).ready(function($) {
var is_error = false;
$(document).ready(function () {
function | (error, result) {
if (error) {
if(error.apierror == 'field_invalid_card_cvc'){
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_cvc);
}else if(error.apierror == 'field_invalid_card_exp'){
jQuery("#paymill_checkout_er... | PaymillResponseHandler | identifier_name |
paymill_token.js | // CreateToken call below
var PAYMILL_PUBLIC_KEY = paymill_token.public_key;
jQuery(document).ready(function($) {
var is_error = false;
$(document).ready(function () {
function PaymillResponseHandler(error, result) {
if (error) {
if(error.apierror == 'f... | return true;
}
}
//clear errors
jQuery("#paymill_checkout_errors").empty();
if (is_error) return false;
// disable the submit button to prevent repeated clicks
jQuery('#mp_payment_confirm').attr("disabled", "disabled").hide();
... | // IF the length is zero then Paymill or some other payment gateway is the only one defined.
if ( jQuery('input.mp_choose_gateway').length ) {
// If the payment option selected is not Paymill then return and bypass input validations
if ( jQuery('input.mp_choose_gateway:c... | random_line_split |
paymill_token.js | // CreateToken call below
var PAYMILL_PUBLIC_KEY = paymill_token.public_key;
jQuery(document).ready(function($) {
var is_error = false;
$(document).ready(function () {
function PaymillResponseHandler(error, result) | }
jQuery('#mp_payment_confirm').show();
jQuery("#mp_payment_confirm").removeAttr("disabled");
jQuery('#paymill_processing').hide();
}
jQuery("#mp_payment_form").submit(function (event) {
jQuery('#paymill_processing').show... | {
if (error) {
if(error.apierror == 'field_invalid_card_cvc'){
jQuery("#paymill_checkout_errors").text(paymill_token.invalid_cvc);
}else if(error.apierror == 'field_invalid_card_exp'){
jQuery("#paymill_checkout_errors").text(paym... | identifier_body |
defaults-nl_NL.min.js | /*!
* Bootstrap-select v1.7.3 (http://silviomoreto.github.io/bootstrap-select)
*
* Copyright 2013-2015 bootstrap-select
* Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE) | */
!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(a){return b(a)}):"object"==typeof exports?module.exports=b(require("jquery")):b(jQuery)}(this,function(){!function(a){a.fn.selectpicker.defaults={noneSelectedText:"Niets geselecteerd",noneResultsText:"Geen resultaten gevonden voor {0}",... | random_line_split | |
const.py | """Constants for the pi_hole intergration."""
from datetime import timedelta
DOMAIN = "pi_hole"
CONF_LOCATION = "location"
CONF_SLUG = "slug"
DEFAULT_LOCATION = "admin"
DEFAULT_METHOD = "GET"
DEFAULT_NAME = "Pi-Hole"
DEFAULT_SSL = False
DEFAULT_VERIFY_SSL = True
SERVICE_DISABLE = "disable"
SERVICE_DISABLE_ATTR_DURA... | SENSOR_DICT = {
"ads_blocked_today": ["Ads Blocked Today", "ads", "mdi:close-octagon-outline"],
"ads_percentage_today": [
"Ads Percentage Blocked Today",
"%",
"mdi:close-octagon-outline",
],
"clients_ever_seen": ["Seen Clients", "clients", "mdi:account-outline"],
"dns_queries... | random_line_split | |
variables_11.js | var searchData=
[ | ['remoteaddress',['remoteAddress',['../d4/d33/classSocket.html#aea5a56e9aa58cd921df2d28693aa52c7',1,'Socket']]],
['remoteport',['remotePort',['../d4/d33/classSocket.html#a4ad81f48d21bceda7bc1c27389685c6f',1,'Socket']]],
['response',['response',['../d6/d28/classMessage.html#a78167fa1a78f782d15ea7122333eb53d',1,'Me... | random_line_split | |
button07.js |
/*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] in the
hope that it will be useful, but WITHOUT ANY WARRANT... |
var success;
if(checkInitialization(builder, "button07") != null) return;
var nodeList;
var testNode;
var vtype;
var doc;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
doc = load(docRef, "doc", "button");
nodeLis... | on07() { | identifier_name |
button07.js |
/*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] in the
hope that it will be useful, but WITHOUT ANY WARRANT... | button07();
}
| identifier_body | |
button07.js | /*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] in the
hope that it will be useful, but WITHOUT ANY WARRANTY... | if (docsLoaded == 1) {
setUpPageStatus = 'complete';
}
} catch(ex) {
catchInitializationError(builder, ex);
setUpPageStatus = 'complete';
}
}
//
// This method is called on the completion of
// each asychronous load started in setUpTests.
//
// When every synchr... | random_line_split | |
models.py | """
Generic relations
Generic relations let an object have a foreign key to any object through a
content-type/object-id field. A ``GenericForeignKey`` field can point to any
object, be it animal, vegetable, or mineral.
The canonical example is tags (although this example implementation is *far*
from complete).
"""
f... |
@python_2_unicode_compatible
class Vegetable(models.Model):
name = models.CharField(max_length=150)
is_yucky = models.BooleanField(default=True)
tags = GenericRelation(TaggedItem)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Mineral(models.Model):
name = model... | content_type_field="content_type1")
def __str__(self):
return self.common_name | random_line_split |
models.py | """
Generic relations
Generic relations let an object have a foreign key to any object through a
content-type/object-id field. A ``GenericForeignKey`` field can point to any
object, be it animal, vegetable, or mineral.
The canonical example is tags (although this example implementation is *far*
from complete).
"""
f... | (self):
return self.name
class GeckoManager(models.Manager):
def get_queryset(self):
return super(GeckoManager, self).get_queryset().filter(has_tail=True)
class Gecko(models.Model):
has_tail = models.BooleanField(default=False)
objects = GeckoManager()
# To test fix for #11263
class Ro... | __str__ | identifier_name |
models.py | """
Generic relations
Generic relations let an object have a foreign key to any object through a
content-type/object-id field. A ``GenericForeignKey`` field can point to any
object, be it animal, vegetable, or mineral.
The canonical example is tags (although this example implementation is *far*
from complete).
"""
f... |
class ValuableTaggedItem(TaggedItem):
value = models.PositiveIntegerField()
class AbstractComparison(models.Model):
comparative = models.CharField(max_length=50)
content_type1 = models.ForeignKey(ContentType, models.CASCADE, related_name="comparative1_set")
object_id1 = models.PositiveIntegerField... | """A tag on an item."""
tag = models.SlugField()
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
class Meta:
ordering = ["tag", "content_type__model"]
def __str__(self):
return self.ta... | identifier_body |
update.js | /**
* Copyright (c) 2017, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or
* https://opensource.org/licenses/BSD-3-Clause
*/
/**
* tests/db/model/profile/update.js
*/
'use strict';
const expect = require('ch... | })
.catch(done);
});
it('fail, profile aspectAccess bad', (done) => {
Profile.findOne({ where: { name: pname } })
.then((o) => o.update({ aspectAccess: true }))
.catch((err) => {
expect(err.name).to.equal(tu.dbErrorName);
done();
})
.catch(done);
});
it('fail, admin pro... | expect(err.name).to.equal(tu.dbErrorName);
done(); | random_line_split |
string_list.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_u... |
//cef_string_list
#[no_mangle]
pub extern "C" fn cef_string_list_alloc() -> *mut cef_string_list_t {
unsafe {
let lt: Box<Vec<*mut cef_string_t>> = box vec!();
mem::transmute(lt)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_size(lt: *mut cef_string_list_t) -> c_int {
unsafe {
... | {
lt as *mut Vec<*mut cef_string_t>
} | identifier_body |
string_list.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_u... | (lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
if (*v).len() == 0 { return; }
let mut cs;
while (*v).len() != 0 {
cs = (*v).pop();
cef_string_userfree_utf8_free(cs.unwrap());
... | cef_string_list_clear | identifier_name |
string_list.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_u... | use types::{cef_string_list_t,cef_string_t};
fn string_map_to_vec(lt: *mut cef_string_list_t) -> *mut Vec<*mut cef_string_t> {
lt as *mut Vec<*mut cef_string_t>
}
//cef_string_list
#[no_mangle]
pub extern "C" fn cef_string_list_alloc() -> *mut cef_string_list_t {
unsafe {
let lt: Box<Vec<*mut cef_s... | random_line_split | |
string_list.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_u... |
let v = string_map_to_vec(lt);
let cs = cef_string_userfree_utf8_alloc();
cef_string_utf8_set(mem::transmute((*value).str), (*value).length, cs, 1);
(*v).push(cs);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_value(lt: *mut cef_string_list_t, index: c_int, value: *mut cef_str... | { return; } | conditional_block |
all_e.js | ['vrefsh_103',['VREFSH',['../namespace_a_d_c__settings.html#a8c2a64f3fca3ac6b82e8df8cf44f6ca2ad1809a5c0e700d83d66cd3c96f5b414f',1,'ADC_settings']]]
]; | var searchData=
[
['very_5fhigh_5fspeed_101',['VERY_HIGH_SPEED',['../namespace_a_d_c__settings.html#af0d80a1aae7288f77b13f0e01d9da0d3a605020f3fad4a24098fbbb0fa4a293f1',1,'ADC_settings']]],
['very_5flow_5fspeed_102',['VERY_LOW_SPEED',['../namespace_a_d_c__settings.html#af0d80a1aae7288f77b13f0e01d9da0d3a5afd4ce3e5123... | random_line_split | |
response.rs | <bool>,
/// `None` can be considered a StatusCode of `0`.
#[ignore_heap_size_of = "Defined in hyper"]
status: DOMRefCell<Option<StatusCode>>,
raw_status: DOMRefCell<Option<(u16, Vec<u8>)>>,
response_type: DOMRefCell<DOMResponseType>,
url: DOMRefCell<Option<ServoUrl>>,
url_list: DOMRefCell<Ve... | format!("init's status member should be in the range 200 to 599, inclusive, but is {}"
, init.status)));
}
// Step 2
if !is_valid_status_text(&init.statusText) {
return Err(Error::Type("init's statusText member does not match the reason-phrase... | random_line_split | |
response.rs | >,
/// `None` can be considered a StatusCode of `0`.
#[ignore_heap_size_of = "Defined in hyper"]
status: DOMRefCell<Option<StatusCode>>,
raw_status: DOMRefCell<Option<(u16, Vec<u8>)>>,
response_type: DOMRefCell<DOMResponseType>,
url: DOMRefCell<Option<ServoUrl>>,
url_list: DOMRefCell<Vec<Ser... |
// https://fetch.spec.whatwg.org/#dom-response
pub fn new(global: &GlobalScope) -> Root<Response> {
reflect_dom_object(box Response::new_inherited(), global, ResponseBinding::Wrap)
}
pub fn Constructor(global: &GlobalScope, body: Option<BodyInit>, init: &ResponseBinding::ResponseInit)
... | {
Response {
reflector_: Reflector::new(),
headers_reflector: Default::default(),
mime_type: DOMRefCell::new("".to_string().into_bytes()),
body_used: Cell::new(false),
status: DOMRefCell::new(Some(StatusCode::Ok)),
raw_status: DOMRefCell::n... | identifier_body |
response.rs | >,
/// `None` can be considered a StatusCode of `0`.
#[ignore_heap_size_of = "Defined in hyper"]
status: DOMRefCell<Option<StatusCode>>,
raw_status: DOMRefCell<Option<(u16, Vec<u8>)>>,
response_type: DOMRefCell<DOMResponseType>,
url: DOMRefCell<Option<ServoUrl>>,
url_list: DOMRefCell<Vec<Ser... | (&self) -> Ref<Vec<u8>> {
self.mime_type.borrow()
}
}
// https://fetch.spec.whatwg.org/#redirect-status
fn is_redirect_status(status: u16) -> bool {
status == 301 || status == 302 || status == 303 || status == 307 || status == 308
}
// https://tools.ietf.org/html/rfc7230#section-3.1.2
fn is_valid_stat... | get_mime_type | identifier_name |
dsntool.py | import collections
import re
import urlparse
class DSN(collections.MutableMapping):
''' Hold the results of a parsed dsn.
This is very similar to urlparse.ParseResult tuple.
http://docs.python.org/2/library/urlparse.html#results-of-urlparse-and-urlsplit
It exposes the following attributes:
... |
def __setitem__(self, field, value):
setattr(self, field, value)
def __delitem__(self, field):
delattr(self, field)
@property
def schemes(self):
'''the scheme, split by plus signs'''
return self.scheme.split('+')
@property
def netloc(self):
'''return ... | return getattr(self, field, None) | identifier_body |
dsntool.py | import collections
import re
import urlparse
class DSN(collections.MutableMapping):
''' Hold the results of a parsed dsn.
This is very similar to urlparse.ParseResult tuple.
http://docs.python.org/2/library/urlparse.html#results-of-urlparse-and-urlsplit
It exposes the following attributes:
... | (self, field, value):
setattr(self, field, value)
def __delitem__(self, field):
delattr(self, field)
@property
def schemes(self):
'''the scheme, split by plus signs'''
return self.scheme.split('+')
@property
def netloc(self):
'''return username:password@hos... | __setitem__ | identifier_name |
dsntool.py | import collections
import re
import urlparse
class DSN(collections.MutableMapping):
''' Hold the results of a parsed dsn.
This is very similar to urlparse.ParseResult tuple.
http://docs.python.org/2/library/urlparse.html#results-of-urlparse-and-urlsplit
It exposes the following attributes:
... |
return hostloc
def set_default(self, key, value):
''' Set a default value for key.
This is different than dict's setdefault because it will set default either
if the key doesn't exist, or if the value at the key evaluates to False, so
an empty string or a None will value ... | hostloc = '{}:{}'.format(hostloc, self.port) | conditional_block |
dsntool.py | import collections
import re
import urlparse
class DSN(collections.MutableMapping):
''' Hold the results of a parsed dsn.
This is very similar to urlparse.ParseResult tuple.
http://docs.python.org/2/library/urlparse.html#results-of-urlparse-and-urlsplit
It exposes the following attributes:
... | return DSN(self.get_url())
def __str__(self):
return self.get_url() |
def copy(self): | random_line_split |
app.module.ts | import { BrowserModule } from '@angular/platform-browser'
import { NgModule } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { HttpModule } from '@angular/http'
import { RouterModule } from '@angular/router'
import { StoreModule } from '@ngrx/store'
import { StoreDevtoolsM... | { }
| AppModule | identifier_name |
app.module.ts | import { BrowserModule } from '@angular/platform-browser'
import { NgModule } from '@angular/core'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { HttpModule } from '@angular/http'
import { RouterModule } from '@angular/router'
import { StoreModule } from '@ngrx/store'
import { StoreDevtoolsM... | ],
imports: [
RouterModule.forRoot(routes),
StoreModule.provideStore({
page: coursesReducer,
user: userReducer
}),
StoreDevtoolsModule.instrumentOnlyWithExtension({
maxAge: 5
}),
BrowserModule,
FormsModule,
HttpM... | NotFoundComponent | random_line_split |
app.py | import os
import subprocess
from pymongo import MongoClient
from flask import Flask, redirect, url_for, request, flash
from flask_bootstrap import Bootstrap
from flask_mongoengine import MongoEngine
from flask_modular_auth import AuthManager, current_authenticated_entity, SessionBasedAuthProvider, KeyBasedAuthProvider... |
def unauthorized_callback():
if current_authenticated_entity.is_authenticated:
flash('You are not authorized to access this resource!', 'warning')
return redirect(url_for('mass_flask_webui.index'))
else:
return redirect(url_for('mass_flask_webui.login', next=request.url))
auth_manage... | app.key_based_provider = KeyBasedAuthProvider(key_loader)
auth_manager.register_auth_provider(app.key_based_provider) | identifier_body |
app.py | import os
import subprocess
from pymongo import MongoClient
from flask import Flask, redirect, url_for, request, flash
from flask_bootstrap import Bootstrap
from flask_mongoengine import MongoEngine
from flask_modular_auth import AuthManager, current_authenticated_entity, SessionBasedAuthProvider, KeyBasedAuthProvider... | (user_loader):
app.session_provider = SessionBasedAuthProvider(user_loader)
auth_manager.register_auth_provider(app.session_provider)
def setup_key_based_auth(key_loader):
app.key_based_provider = KeyBasedAuthProvider(key_loader)
auth_manager.register_auth_provider(app.key_based_provider)
def unauth... | setup_session_auth | identifier_name |
app.py | import os
import subprocess
from pymongo import MongoClient
from flask import Flask, redirect, url_for, request, flash
from flask_bootstrap import Bootstrap
from flask_mongoengine import MongoEngine
from flask_modular_auth import AuthManager, current_authenticated_entity, SessionBasedAuthProvider, KeyBasedAuthProvider... |
auth_manager = AuthManager(app, unauthorized_callback=unauthorized_callback)
# Set the version number. For the future we should probably read it from a file.
app.version = '1.0-alpha1'
| return redirect(url_for('mass_flask_webui.login', next=request.url)) | conditional_block |
app.py | import os
import subprocess
from pymongo import MongoClient
from flask import Flask, redirect, url_for, request, flash
from flask_bootstrap import Bootstrap
from flask_mongoengine import MongoEngine
from flask_modular_auth import AuthManager, current_authenticated_entity, SessionBasedAuthProvider, KeyBasedAuthProvider... |
# Load config
config_path = os.getenv('CONFIG_PATH', 'mass_flask_config.config_development.DevelopmentConfig')
app.config.from_object(config_path)
# Init db
db = MongoEngine(app)
# Init flask-bootstrap
Bootstrap(app)
# Init auth system
def setup_session_auth(user_loader):
app.session_provider = SessionBasedAut... | secret.close()
except IOError:
Exception('Please create a %s file with random characters \
to generate your secret key!' % SECRET_FILE) | random_line_split |
option.js | function Option ( name, options ) | };
this.unlisten = function() {
context.element.removeEventListener('change', this.callback);
};
}
var cafe = (function ( game ) {
game.bean = new Option ( 'bean', ['gourmet', 'hipster', 'good', 'cheap', 'actual']);
game.price = new Option ('price', ['well below', 'below', 'at', 'above', ... | {
var context = this;
this.options = options;
this.element = document.querySelector('#' + name);
this.set = function ( string ) {
if(this.options.indexOf( string ) >= 0 && this.element.value !== string) {
this.element.value = string;
}
};
this.get = function () {
... | identifier_body |
option.js | function Option ( name, options ) {
var context = this;
this.options = options;
this.element = document.querySelector('#' + name);
this.set = function ( string ) {
if(this.options.indexOf( string ) >= 0 && this.element.value !== string) |
};
this.get = function () {
return this.element.value;
};
this.callback = function ( event ) {
context.set(event.target.value);
event.stopPropagation();
};
this.listen = function() {
context.element.addEventListener('change', this.callback);
};
this.unlis... | {
this.element.value = string;
} | conditional_block |
option.js | function | ( name, options ) {
var context = this;
this.options = options;
this.element = document.querySelector('#' + name);
this.set = function ( string ) {
if(this.options.indexOf( string ) >= 0 && this.element.value !== string) {
this.element.value = string;
}
};
this.get... | Option | identifier_name |
option.js | function Option ( name, options ) {
var context = this;
this.options = options;
this.element = document.querySelector('#' + name);
this.set = function ( string ) {
if(this.options.indexOf( string ) >= 0 && this.element.value !== string) {
this.element.value = string;
}
... |
var cafe = (function ( game ) {
game.bean = new Option ( 'bean', ['gourmet', 'hipster', 'good', 'cheap', 'actual']);
game.price = new Option ('price', ['well below', 'below', 'at', 'above', 'well above']);
return game;
} ( cafe || {})); | } | random_line_split |
classify.py | metavar = 'CSV',
type = lambda f: set(e for e in DictReader(opener(f), fieldnames ='tax_id')),
default = {},
help = 'column: tax_id')
parser.add_argument('--group-def',
metavar = 'INT',
action = 'append',
default = [],
h... | target_rank = ranks[ranks.index(target_rank) + 1]
# recurse down the tax tree
condensed = []
for _,g in groups:
c = condense(g, floor_rank, max_size, ranks, rank_thresholds, target_rank)
condensed.extend(c)
return condensed
def action(args):
### format format blast data and a... | target_rank = target_rank or ranks[0]
groups = list(groupbyl(queries, key = itemgetter(target_rank)))
num_groups = len(groups)
if rank_thresholds.get(target_rank, max_size) < num_groups:
return queries
# assign where available target_rank_ids
# groups without 'i' values remain assigned a... | identifier_body |
classify.py | metavar = 'CSV',
type = lambda f: set(e for e in DictReader(opener(f), fieldnames ='tax_id')),
default = {},
help = 'column: tax_id')
parser.add_argument('--group-def',
metavar = 'INT',
action = 'append',
default = [],
h... | (b):
return dict(seq_info[b['sseqid']], **b) if b['sseqid'] else b
blast_results = (info(b) for b in blast_results)
# tax info
def tax_info(b):
return dict(args.taxonomy[b['tax_id']], **b) if b['sseqid'] else b
blast_results = (tax_info(b) for b in blast_results)
### output file ... | info | identifier_name |
classify.py | metavar = 'CSV',
type = lambda f: set(e for e in DictReader(opener(f), fieldnames ='tax_id')),
default = {},
help = 'column: tax_id')
parser.add_argument('--group-def',
metavar = 'INT',
action = 'append',
default = [],
h... | groups = [
('> {}%'.format(args.max_identity),
lambda h: blast_hit(h, args) and h['pident'] > args.max_identity),
(None,
lambda h: blast_hit(h, args) and args.max_identity >= h['pident'] > args.min_identity),
('<= {}%'.format(args.min_identity),
lambda h: ... | # groups have list position prioritization | random_line_split |
classify.py | _results)
# coverage
def cov(b):
if b['sseqid'] and b['qcovs']:
b['coverage'] = float(b['qcovs'])
return b
elif b['sseqid']:
c = coverage(b['qstart'], b['qend'], b['qlen'])
return dict(b, coverage = c)
else:
return b
blast... | args.out_detail.writerow(dict(
specimen = specimen,
assignment = assignment,
assignment_id = assignment_id,
hi = args.max_identity,
low = args.min_identity,
target_rank = args.... | conditional_block | |
HomeController.ts | 'use strict';
// Import certain style elements here so that webpack picks them up
import '@fortawesome/fontawesome-free/js/all';
import { StateOrName, StateParams, StateService } from '@uirouter/core';
import angular, { IController, IRootScopeService } from 'angular';
import '../../../../public/sass/theme.scss';
impor... |
}
}
angular.module('core').controller('HomeController', HomeController);
| {
const prevState = sessionStorage.prevState as StateOrName;
const prevParams = JSON.parse(sessionStorage.prevParams) as StateParams;
delete sessionStorage.prevState;
delete sessionStorage.prevParams;
this.$state.go(prevState, prevParams);
} | conditional_block |
HomeController.ts | 'use strict';
// Import certain style elements here so that webpack picks them up
import '@fortawesome/fontawesome-free/js/all';
import { StateOrName, StateParams, StateService } from '@uirouter/core';
import angular, { IController, IRootScopeService } from 'angular';
import '../../../../public/sass/theme.scss';
impor... | const prevState = sessionStorage.prevState as StateOrName;
const prevParams = JSON.parse(sessionStorage.prevParams) as StateParams;
delete sessionStorage.prevState;
delete sessionStorage.prevParams;
this.$state.go(prevState, prevParams);
}
}
}
angular.module('core').controller('HomeController', HomeC... | constructor(private AuthenticationService: IAuthenticationService, private $state: StateService, private $rootScope: IRootScopeService) {
this.isUser = !!this.AuthenticationService.user;
if (sessionStorage.prevState) { | random_line_split |
HomeController.ts | 'use strict';
// Import certain style elements here so that webpack picks them up
import '@fortawesome/fontawesome-free/js/all';
import { StateOrName, StateParams, StateService } from '@uirouter/core';
import angular, { IController, IRootScopeService } from 'angular';
import '../../../../public/sass/theme.scss';
impor... | (private AuthenticationService: IAuthenticationService, private $state: StateService, private $rootScope: IRootScopeService) {
this.isUser = !!this.AuthenticationService.user;
if (sessionStorage.prevState) {
const prevState = sessionStorage.prevState as StateOrName;
const prevParams = JSON.parse(sessionStora... | constructor | identifier_name |
null_engine.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... | () {
let s = r#"{
"params": {
"blockReward": "0x0d"
}
}"#;
let deserialized: NullEngine = serde_json::from_str(s).unwrap();
assert_eq!(deserialized.params.block_reward, Some(Uint(U256::from(0x0d))));
}
}
| null_engine_deserialization | identifier_name |
null_engine.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... |
let deserialized: NullEngine = serde_json::from_str(s).unwrap();
assert_eq!(deserialized.params.block_reward, Some(Uint(U256::from(0x0d))));
}
} | "params": {
"blockReward": "0x0d"
}
}"#; | random_line_split |
sk.js | OC.L10N.register(
"workflowengine",
{
"Successfully saved" : "Úspešne uložené",
"Saving failed:" : "Ukladanie neúspešné:",
"File mime type" : "Mime typ súboru",
"is" : "je",
"is not" : "nie je",
"matches" : "súhlasí",
"does not match" : "nesúhlasí",
"Example: {placeholder}" : "Na... | "Request URL" : "Vyžiadať URL",
"Files WebDAV" : "WebDAV súbory",
"Sync clients" : "Synchronizovať klientov",
"Android client" : "Android klient",
"iOS client" : "iOS klient",
"Desktop client" : "Desktopový klient",
"is member of" : "Je členom",
"is not member of" : "Nie je členom",
... | "End" : "Koniec", | random_line_split |
coluslife.js | 'use strict';
/**
* Created by zhaoxueyong on 2017/1/14.
*/
angular.module('browserApp').
controller('ColuslifeCtrl', function ($scope, $http) {
$scope.countryName = "China";
var mapObj = null;
$scope.init_map = function(){
console.log("init map now");
mapObj = new AMap.Map("mapbody", {
... | $http({
method: 'GET',
url: 'http://127.0.0.1:8000/coluslife/locations',
timeout: 5
}).then(
function successCallback(response){
console.log(response.data);
locations = response.data;
for (var i = 0; i < locations.length; i++){
... | if (null === locations){ | random_line_split |
coluslife.js | 'use strict';
/**
* Created by zhaoxueyong on 2017/1/14.
*/
angular.module('browserApp').
controller('ColuslifeCtrl', function ($scope, $http) {
$scope.countryName = "China";
var mapObj = null;
$scope.init_map = function(){
console.log("init map now");
mapObj = new AMap.Map("mapbody", {
... |
});
var placeMarker = function(location){
var marker = new AMap.Marker({
position: new AMap.LngLat(location.fields.gislng, location.fields.gislat),
title: location.fields.name
});
marker.setMap(mapObj);
}
});
| {
$http({
method: 'GET',
url: 'http://127.0.0.1:8000/coluslife/locations',
timeout: 5
}).then(
function successCallback(response){
console.log(response.data);
locations = response.data;
for (var i = 0; i < locations.length; i++)... | conditional_block |
dropdown-toggle.directive.ts | import {
Directive, ElementRef, Host, OnInit, Input, HostBinding, HostListener
} from 'angular2/core';
import {Dropdown} from './dropdown.directive';
@Directive({selector: '[dropdownToggle]'})
export class DropdownToggle implements OnInit {
@HostBinding('class.disabled')
@Input() public disabled:boolean = false;... | this.dropdown = dropdown;
this.el = el;
}
public ngOnInit():void {
this.dropdown.dropDownToggle = this;
}
@HostBinding('attr.aria-expanded')
public get isOpen():boolean {
return this.dropdown.isOpen;
}
@HostListener('click', ['$event'])
public toggleDropdown(event:MouseEvent):boolean ... |
public dropdown:Dropdown;
public el:ElementRef;
public constructor(@Host() dropdown:Dropdown, el:ElementRef) { | random_line_split |
dropdown-toggle.directive.ts | import {
Directive, ElementRef, Host, OnInit, Input, HostBinding, HostListener
} from 'angular2/core';
import {Dropdown} from './dropdown.directive';
@Directive({selector: '[dropdownToggle]'})
export class DropdownToggle implements OnInit {
@HostBinding('class.disabled')
@Input() public disabled:boolean = false;... |
return false;
}
}
| {
this.dropdown.toggle();
} | conditional_block |
dropdown-toggle.directive.ts | import {
Directive, ElementRef, Host, OnInit, Input, HostBinding, HostListener
} from 'angular2/core';
import {Dropdown} from './dropdown.directive';
@Directive({selector: '[dropdownToggle]'})
export class | implements OnInit {
@HostBinding('class.disabled')
@Input() public disabled:boolean = false;
@HostBinding('class.dropdown-toggle')
@HostBinding('attr.aria-haspopup')
public addClass:boolean = true;
public dropdown:Dropdown;
public el:ElementRef;
public constructor(@Host() dropdown:Dropdown, el:Elemen... | DropdownToggle | identifier_name |
dropdown-toggle.directive.ts | import {
Directive, ElementRef, Host, OnInit, Input, HostBinding, HostListener
} from 'angular2/core';
import {Dropdown} from './dropdown.directive';
@Directive({selector: '[dropdownToggle]'})
export class DropdownToggle implements OnInit {
@HostBinding('class.disabled')
@Input() public disabled:boolean = false;... |
@HostBinding('attr.aria-expanded')
public get isOpen():boolean {
return this.dropdown.isOpen;
}
@HostListener('click', ['$event'])
public toggleDropdown(event:MouseEvent):boolean {
event.stopPropagation();
if (!this.disabled) {
this.dropdown.toggle();
}
return false;
}
}
| {
this.dropdown.dropDownToggle = this;
} | identifier_body |
UserInfoObjectFactory.ts | // Copyright 2018 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... | (): boolean {
return this._isAdmin;
}
isTopicManager(): boolean {
return this._isTopicManager;
}
isSuperAdmin(): boolean {
return this._isSuperAdmin;
}
canCreateCollections(): boolean {
return this._canCreateCollections;
}
getPreferredSiteLanguageCode(): string {
return this._pre... | isAdmin | identifier_name |
UserInfoObjectFactory.ts | // Copyright 2018 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... | return this._canCreateCollections;
}
getPreferredSiteLanguageCode(): string {
return this._preferredSiteLanguageCode;
}
getUsername(): string {
return this._username;
}
getEmail(): string {
return this._email;
}
isLoggedIn(): boolean {
return this._isLoggedIn;
}
}
@Injectable(... | return this._isSuperAdmin;
}
canCreateCollections(): boolean { | random_line_split |
UserInfoObjectFactory.ts | // Copyright 2018 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... |
isAdmin(): boolean {
return this._isAdmin;
}
isTopicManager(): boolean {
return this._isTopicManager;
}
isSuperAdmin(): boolean {
return this._isSuperAdmin;
}
canCreateCollections(): boolean {
return this._canCreateCollections;
}
getPreferredSiteLanguageCode(): string {
retur... | {
return this._isModerator;
} | identifier_body |
position-animation.ts | /**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | element: HTMLElement,
largerRect: ClientRect,
smallerRect: ClientRect,
largerDimensions: Size,
smallerDimensions: Size,
largerObjectPosition: string,
smallerObjectPosition: string,
curve: Curve,
styles: Object,
keyframesPrefix: string,
toLarger: boolean,
}): string {
const curveString = curveToS... | styles,
keyframesPrefix,
toLarger,
} : { | random_line_split |
position-animation.ts | /**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | ({
element,
largerRect,
smallerRect,
largerDimensions,
smallerDimensions,
largerObjectPosition,
smallerObjectPosition,
curve,
styles,
keyframesPrefix,
toLarger,
} : {
element: HTMLElement,
largerRect: ClientRect,
smallerRect: ClientRect,
largerDimensions: Size,
smallerDimensions: Size,
... | preparePositionAnimation | identifier_name |
position-animation.ts | /**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | from {
transform: translate(${startTranslate.left}px, ${startTranslate.top}px);
}
to {
transform: translate(${endTranslate.left}px, ${endTranslate.top}px);
}
}
`;
}
| {
const curveString = curveToString(curve);
const keyframesName = `${keyframesPrefix}-object-position`;
const largerTranslate = getPositioningTranslate(
largerObjectPosition, largerRect, largerDimensions);
const smallerTranslate = getPositioningTranslate(
smallerObjectPosition, smallerRect, smaller... | identifier_body |
web_planner_crm.js | odoo.define('planner_crm.planner', function (require) {
"use strict";
var planner = require('web.planner.common');
var core = require('web.core');
var _t = core._t;
planner.PlannerDialog.include({
prepare_planner_event: function () {
this._super.apply(this, arguments);
if (this.planner['planner_ap... | for(var i=0; i<values.length; i++) {
$('#input_element_stage_'+i).val(values[i]);
}
}
});
}
}
});
}); | var option = $(ev.target).find(":selected").val();
if (_.has(stages, option)) {
var values = stages[option]; | random_line_split |
web_planner_crm.js | odoo.define('planner_crm.planner', function (require) {
"use strict";
var planner = require('web.planner.common');
var core = require('web.core');
var _t = core._t;
planner.PlannerDialog.include({
prepare_planner_event: function () {
this._super.apply(this, arguments);
if (this.planner['planner_ap... | _t('POC demonstration to the customer'), _t('Final Proposal sent'), ''],
'odoo_default': [
_t('New'), _t('Qualified'), _t('Proposition'), _t('Negotiation'), _t('Won'), _t('Lost'), '',
'', '', '', '', '', '', '']
};
this.... | {
var stages = {
'solution_selling': [
_t('Territory'), _t('Qualified'), _t('Qualified Sponsor'),
_t('Proposal'), _t('Negotiation'), _t('Won'), '',
_t('New propspect assigned to the right salesperson'),
_t('Set f... | conditional_block |
course.py | visibility.
"""
returned_data = {
'display_name': self.display_name,
'data': self.data,
'metadata': self.metadata,
'graderType': self.grader_type,
'publish': self.publish,
'fields': self.fields,
}
return json.dumps(... |
# Set a default start date to the past, but use Studio's
# default for the end date (meaning we don't set it here)
if start_date is None:
start_date = datetime.datetime(1970, 1, 1)
self._course_details = {
'start_date': start_date.isoformat(),
}
... | """
Configure the course fixture to create a course with
`org`, `number`, `run`, and `display_name` (all unicode).
`start_date` and `end_date` are datetime objects indicating the course start and end date.
The default is for the course to have started in the distant past, which is gene... | identifier_body |
course.py | a str (e.g. "January 29, 2014)
# `content` is also a str (e.g. "Test course")
CourseUpdateDesc = namedtuple("CourseUpdateDesc", ['date', 'content'])
class CourseFixture(XBlockContainerFixture):
"""
Fixture for ensuring that a course exists.
WARNING: This fixture is NOT idempotent. To avoid conflicts
... | raise FixtureError(
u"Could not update course handouts with {0}. Status was {1}".format(url, response.status_code)) | conditional_block | |
course.py | public visibility.
"""
returned_data = {
'display_name': self.display_name,
'data': self.data,
'metadata': self.metadata,
'graderType': self.grader_type,
'publish': self.publish,
'fields': self.fields,
}
return json... | (self):
"""
Create the course described in the fixture.
"""
# If the course already exists, this will respond
# with a 200 and an error message, which we ignore.
response = self.session.post(
STUDIO_BASE_URL + '/course/',
data=self._encode_post_dic... | _create_course | identifier_name |
course.py | public visibility.
"""
returned_data = {
'display_name': self.display_name,
'data': self.data,
'metadata': self.metadata,
'graderType': self.grader_type,
'publish': self.publish,
'fields': self.fields,
}
return json... | 'run': run,
'display_name': display_name
}
# Set a default start date to the past, but use Studio's
# default for the end date (meaning we don't set it here)
if start_date is None:
start_date = datetime.datetime(1970, 1, 1)
self._course_detai... | """
super(CourseFixture, self).__init__()
self._course_dict = {
'org': org,
'number': number, | random_line_split |
fs.rs | PathGlob::wildcard(canonical_dir, symbolic_path, SINGLE_STAR_GLOB.clone()),
]
);
}
// There is a double-wildcard in a dirname of the path: double wildcards are recursive,
// so there are two remainder possibilities: one with the double wildcard included, and the
//... | (root: &Dir, patterns: &Vec<String>) -> Result<Gitignore, ignore::Error> {
let mut ignore_builder = GitignoreBuilder::new(root.0.as_path());
for pattern in patterns {
ignore_builder.add_line(None, pattern.as_str())?;
}
ignore_builder
.build()
}
fn scandir_sync(dir: Dir, dir_abs: PathBuf... | create_ignore | identifier_name |
fs.rs | Future<(Vec<PathStat>, Vec<PathGlob>), E> {
match path_glob {
PathGlob::Wildcard { canonical_dir, symbolic_path, wildcard } =>
// Filter directory listing to return PathStats, with no continuation.
self.directory_listing(canonical_dir, symbolic_path, wildcard)
.map(|path_stats| (path... | let mut entry = entry_res?;
if entry.header().entry_type() == tar::EntryType::file() {
let path = | random_line_split | |
fs.rs | , in order.
outputs: OrderMap<PathStat, ()>,
}
pub struct PosixFS {
build_root: Dir,
// The pool needs to be reinitialized after a fork, so it is protected by a lock.
pool: RwLock<CpuPool>,
ignore: Gitignore,
}
impl PosixFS {
pub fn new(
build_root: PathBuf,
ignore_patterns: Vec<String>,
) -> Re... | {
self.expand_multi(path_globs.include).join(self.expand_multi(path_globs.exclude))
.map(|(include, exclude)| {
// Exclude matched paths.
let exclude_set: HashSet<_> = exclude.into_iter().collect();
include.into_iter().filter(|i| !exclude_set.contains(i)).collect()
})
.boxe... | identifier_body | |
tests.js | (milliseconds, resolve) {
return new Promise(function (resolve) {
setTimeout(resolve, milliseconds);
});
}
//Burdaki T ODO ödev icin bir önemi yok, sadece gelecek icin kodu düzeltme acisindan yapilacaklar
//TODO: For Instructors only -> Replace all Maps with Set's
//TODO: For Instructors only -> Null ch... | delay | identifier_name | |
tests.js |
//Burdaki T ODO ödev icin bir önemi yok, sadece gelecek icin kodu düzeltme acisindan yapilacaklar
//TODO: For Instructors only -> Replace all Maps with Set's
//TODO: For Instructors only -> Null checks
//TODO: For Instructors only -> Reduction of function chaining
//TODO: For Instructors only -> Simplify jQuery statem... | {
return new Promise(function (resolve) {
setTimeout(resolve, milliseconds);
});
} | identifier_body | |
tests.js | "The Best Collection"', () => {
changeHeadingToTheBestCollection();
let headingNew = $(".container > h4:first").text();
headingNew.should.equal("The Best Collection");
});
it('04) should make the hr (.line) element bolder', () => {
let hrLine = $("hr.line");
let boldnes... | return acc.set(value, 0);
}, new Map());
removeBuyItemButtonQuery.size().should.be.above(4);
mapOfGrayBorders.size.should.equal(1);
mapOfShadows.size.should.equal(1);
console.dir(mapOfGrayBorders.entries())
mapOfGrayBorders.entries(... | return $(tag).css("box-shadow");
}).reduce((acc, value) => { | random_line_split |
tests.js | .should.equal(5);
should.not.exist(lastItem);
should.not.exist(secondLastItem);
});
it('08) should make 10% reduction on all products', () => {
let prices = $('.price');
let pricesBefore = prices.map((index, tag) => {
return $(tag).text();
}).toArray();
... | if (valuePrices[i - 1] > valuePrices[i]) {
properlySorted = false;
}
}
| conditional_block | |
utils.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the Utils provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class Utils {
... | (serviceData:any, selectedCity:string,
area:string, houseNo:string, locality:string,date:string, time:string){
let data = {};
data['serviceData'] = serviceData;
data['city'] = selectedCity;
data['area'] = area;
data['houseNo'] = houseNo;
data['locality'] = locality;
data['date'] = date;
... | serviceSharedAddressToPhone | identifier_name |
utils.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the Utils provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class Utils {
... | data['description'] = desc;
return data;
}
serviceSharedAddressToPhone(serviceData:any, selectedCity:string,
area:string, houseNo:string, locality:string,date:string, time:string){
let data = {};
data['serviceData'] = serviceData;
data['city'] = selectedCity;
data['area'] = area;
data... | serviceShareData(serviceType:string, serviceList:Array<any>, desc: string){
let data = {};
data['serviceType'] = serviceType;
data['serviceList'] = serviceList; | random_line_split |
all_characters.py | from .frontend import JSON_Editor, mode, Page
from . import frontend
from .character import Character
from .util import load_json, debug
class CHARACTERS(JSON_Editor):
def __init__(self):
|
def render(self, requestdata):
if mode() == 'dm':
return JSON_Editor.render(self, requestdata)
else:
char = frontend.campaign.current_char()
return self.view(char.name())
def view(self, item):
page = Page()
if not item:
page.erro... | self._name = 'character'
JSON_Editor.__init__(self)
self._icons = 'avatars'
self._obj = Character({}) | identifier_body |
all_characters.py | from .frontend import JSON_Editor, mode, Page
from . import frontend
from .character import Character
from .util import load_json, debug
class CHARACTERS(JSON_Editor):
def __init__(self):
self._name = 'character'
JSON_Editor.__init__(self)
self._icons = 'avatars'
self._obj = Charac... | (self, item):
page = Page()
if not item:
page.error('No item specified')
return page.render()
try:
debug('try %s/%s' % (self._name, item))
json = load_json('%ss' % self._name, item)
except:
debug('except')
page.error... | view | identifier_name |
all_characters.py | from .frontend import JSON_Editor, mode, Page
from . import frontend
from .character import Character
from .util import load_json, debug
class CHARACTERS(JSON_Editor):
def __init__(self):
self._name = 'character'
JSON_Editor.__init__(self)
self._icons = 'avatars'
self._obj = Charac... |
try:
debug('try %s/%s' % (self._name, item))
json = load_json('%ss' % self._name, item)
except:
debug('except')
page.error('No files matching %s found in %s' % (item, self._name))
return page.render()
c = Character(json)
render... | page.error('No item specified')
return page.render() | conditional_block |
all_characters.py | from .frontend import JSON_Editor, mode, Page
from . import frontend
from .character import Character
from .util import load_json, debug
class CHARACTERS(JSON_Editor):
def __init__(self):
self._name = 'character'
JSON_Editor.__init__(self)
self._icons = 'avatars'
self._obj = Charac... | json = load_json('%ss' % self._name, item)
except:
debug('except')
page.error('No files matching %s found in %s' % (item, self._name))
return page.render()
c = Character(json)
rendered = {}
rendered['json'] = c.render()
return page.... | debug('try %s/%s' % (self._name, item)) | random_line_split |
exceptions.py | # Copyright 2016 Autodesk Inc.
#
# 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 in writing... |
class QMConvergenceError(Exception):
""" Raised when an iterative QM calculation (typically SCF) fails to converge
"""
pass
| def __init__(self, atom):
self.message = 'Atom %s has unhandled valence: %d' % (atom, atom.valence) | identifier_body |
exceptions.py | # Copyright 2016 Autodesk Inc.
#
# 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 in writing... |
class NotCalculatedError(Exception):
""" Raised when a molecular property is requested that hasn't been calculated """
pass
class UnhandledValenceError(Exception):
def __init__(self, atom):
self.message = 'Atom %s has unhandled valence: %d' % (atom, atom.valence)
class QMConvergenceError(Except... |
class ConvergenceFailure(Exception):
""" Raised when an iterative calculation fails to converge """
pass
| random_line_split |
exceptions.py | # Copyright 2016 Autodesk Inc.
#
# 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 in writing... | (Exception):
""" Raised when a molecular property is requested that hasn't been calculated """
pass
class UnhandledValenceError(Exception):
def __init__(self, atom):
self.message = 'Atom %s has unhandled valence: %d' % (atom, atom.valence)
class QMConvergenceError(Exception):
""" Raised when... | NotCalculatedError | identifier_name |
ModalLoading.js | import React,{
Component
} from 'react'
import {
View,
TouchableOpacity,
Modal,
Text,
DatePickerIOS,
StyleSheet,
Image,
ActivityIndicator,
}from 'react-native'
import { Actions } from 'react-native-router-flux';
import GlobalSize from '../common/GlobalSize'
export default class | extends Component{
constructor(props){
super(props);
// this.state={
// visible:false,
// }
}
render(){
console.log('加载modal是否显示'+this.props.visible);
return(
<Modal
animationType='fade'
transparent={true}
... | ModalLoading | identifier_name |
ModalLoading.js | import React,{
Component
} from 'react'
import {
View,
TouchableOpacity,
Modal,
Text,
DatePickerIOS,
StyleSheet,
Image,
ActivityIndicator,
}from 'react-native'
import { Actions } from 'react-native-router-flux';
import GlobalSize from '../common/GlobalSize'
export default class M... | </Modal>
);
}
}
var styles=Style
Sheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center',
backgroundColor:'rgba(0,1,0,0.2)',
},
contentContainer:{
height:60,
},
})
| {
console.log('加载modal是否显示'+this.props.visible);
return(
<Modal
animationType='fade'
transparent={true}
visible={this.props.visible}
onRequestClose={() => {}}
>
<View style={styles.container}>... | identifier_body |
ModalLoading.js | import React,{
Component
} from 'react'
import {
View,
TouchableOpacity,
Modal,
Text,
DatePickerIOS,
StyleSheet,
Image,
ActivityIndicator,
}from 'react-native'
import { Actions } from 'react-native-router-flux';
import GlobalSize from '../common/GlobalSize'
export default class M... | );
}
}
var styles=StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center',
backgroundColor:'rgba(0,1,0,0.2)',
},
contentContainer:{
height:60,
},
}) | </Text>
</View>
</View>
</Modal> | random_line_split |
characters.js | var total_records = 0;
var url;
var total_groups;
var id;
var loading = false;
function initScroll(total_groups, url, id) {
this.total_groups = total_groups;
this.url = url;
this.id = id;
loading = true;
$('#loader_image_div').show();
$.post(url + id,{'group_number': total_records},
function(data){ ... |
}
});
} | {
loading = true;
$('#loader_image_div').show();
$.post(url + id,{'group_number': total_records},
function(data){
if (data != "") {
$(data).each(function(index, element) {
if($(e... | conditional_block |
characters.js | var total_records = 0;
var url; |
function initScroll(total_groups, url, id) {
this.total_groups = total_groups;
this.url = url;
this.id = id;
loading = true;
$('#loader_image_div').show();
$.post(url + id,{'group_number': total_records},
function(data){
if (data != "") {
$(data).each(function... | var total_groups;
var id;
var loading = false; | random_line_split |
characters.js | var total_records = 0;
var url;
var total_groups;
var id;
var loading = false;
function initScroll(total_groups, url, id) | $('#loader_image_div').hide();
});
$(window).scroll(function() {
if(total_records >= total_groups) {
$(window).off('scroll');
}
if(($(window).scrollTop() + $(window).height() > $(document).height() - 100) && loading == false) {
if(total_records < total_groups) {
... | {
this.total_groups = total_groups;
this.url = url;
this.id = id;
loading = true;
$('#loader_image_div').show();
$.post(url + id,{'group_number': total_records},
function(data){
if (data != "") {
$(data).each(function(index, element) {
if($(element)... | identifier_body |
characters.js | var total_records = 0;
var url;
var total_groups;
var id;
var loading = false;
function | (total_groups, url, id) {
this.total_groups = total_groups;
this.url = url;
this.id = id;
loading = true;
$('#loader_image_div').show();
$.post(url + id,{'group_number': total_records},
function(data){
if (data != "") {
$(data).each(function(index, element) {
... | initScroll | identifier_name |
xiaoi.py | # coding: utf-8
from __future__ import unicode_literals
# created by: Han Feng (https://github.com/hanx11)
import collections
import hashlib
import logging
import requests
from wxpy.api.messages import Message
from wxpy.ext.talk_bot_utils import get_context_user_id, next_topic
from wxpy.utils.misc import get_text_wi... | "userId": user_id,
}
resp = self.session.post(self.url, data=params)
text = resp.text
for err in error_response:
if err in text:
return next_topic()
return text
| ion": question,
"format": "json",
"platform": "custom",
| conditional_block |
xiaoi.py | # coding: utf-8
from __future__ import unicode_literals
# created by: Han Feng (https://github.com/hanx11)
import collections
import hashlib
import logging
import requests
from wxpy.api.messages import Message
from wxpy.ext.talk_bot_utils import get_context_user_id, next_topic
from wxpy.utils.misc import get_text_wi... | sha2 = hashlib.sha1(sha2).hexdigest()
signature = "{0}:{1}:{2}".format(sha1, nonce, sha2).encode("utf-8")
signature = hashlib.sha1(signature).hexdigest()
ret = collections.namedtuple("signature_return", "signature nonce")
ret.signature = signature
ret.nonce = nonce
... | random_line_split | |
xiaoi.py | # coding: utf-8
from __future__ import unicode_literals
# created by: Han Feng (https://github.com/hanx11)
import collections
import hashlib
import logging
import requests
from wxpy.api.messages import Message
from wxpy.ext.talk_bot_utils import get_context_user_id, next_topic
from wxpy.utils.misc import get_text_wi... | (object):
"""
与 wxpy 深度整合的小 i 机器人
"""
# noinspection SpellCheckingInspection
def __init__(self, key, secret):
"""
| 需要通过注册获得 key 和 secret
| 免费申请: http://cloud.xiaoi.com/
:param key: 你申请的 key
:param secret: 你申请的 secret
"""
self.key = key
... | XiaoI | identifier_name |
xiaoi.py | # coding: utf-8
from __future__ import unicode_literals
# created by: Han Feng (https://github.com/hanx11)
import collections
import hashlib
import logging
import requests
from wxpy.api.messages import Message
from wxpy.ext.talk_bot_utils import get_context_user_id, next_topic
from wxpy.utils.misc import get_text_wi... | for err in error_response:
if err in text:
return next_topic()
return text
| "主人还没给我设置这类话题的回复",
)
if isinstance(msg, Message):
user_id = get_context_user_id(msg)
question = get_text_without_at_bot(msg)
else:
user_id = "abc"
question = msg or ""
params = {
"question": question,
"format": "js... | identifier_body |
parse-chromsizes-rows.js | /**
* Parse an array of chromsizes, for example that result
* from reading rows of a chromsizes CSV file.
* @param {array} data Array of [chrName, chrLen] "tuples".
* @returns {object} Object containing properties
* { cumPositions, chrPositions, totalLength, chromLengths }.
*/
function parseChromsizesRows(data) {... | chromLengths[data[i][0]] = length;
}
return {
cumPositions: cumValues,
chrPositions,
totalLength,
chromLengths,
};
}
export default parseChromsizesRows; | random_line_split | |
parse-chromsizes-rows.js | /**
* Parse an array of chromsizes, for example that result
* from reading rows of a chromsizes CSV file.
* @param {array} data Array of [chrName, chrLen] "tuples".
* @returns {object} Object containing properties
* { cumPositions, chrPositions, totalLength, chromLengths }.
*/
function parseChromsizesRows(data) | }
return {
cumPositions: cumValues,
chrPositions,
totalLength,
chromLengths,
};
}
export default parseChromsizesRows;
| {
const cumValues = [];
const chromLengths = {};
const chrPositions = {};
let totalLength = 0;
for (let i = 0; i < data.length; i++) {
const length = Number(data[i][1]);
totalLength += length;
const newValue = {
id: i,
chr: data[i][0],
pos: totalLength - length,
};
cu... | identifier_body |
parse-chromsizes-rows.js | /**
* Parse an array of chromsizes, for example that result
* from reading rows of a chromsizes CSV file.
* @param {array} data Array of [chrName, chrLen] "tuples".
* @returns {object} Object containing properties
* { cumPositions, chrPositions, totalLength, chromLengths }.
*/
function | (data) {
const cumValues = [];
const chromLengths = {};
const chrPositions = {};
let totalLength = 0;
for (let i = 0; i < data.length; i++) {
const length = Number(data[i][1]);
totalLength += length;
const newValue = {
id: i,
chr: data[i][0],
pos: totalLength - length,
};
... | parseChromsizesRows | identifier_name |
parse-chromsizes-rows.js | /**
* Parse an array of chromsizes, for example that result
* from reading rows of a chromsizes CSV file.
* @param {array} data Array of [chrName, chrLen] "tuples".
* @returns {object} Object containing properties
* { cumPositions, chrPositions, totalLength, chromLengths }.
*/
function parseChromsizesRows(data) {... |
return {
cumPositions: cumValues,
chrPositions,
totalLength,
chromLengths,
};
}
export default parseChromsizesRows;
| {
const length = Number(data[i][1]);
totalLength += length;
const newValue = {
id: i,
chr: data[i][0],
pos: totalLength - length,
};
cumValues.push(newValue);
chrPositions[newValue.chr] = newValue;
chromLengths[data[i][0]] = length;
} | conditional_block |
util.ts | import { SearchParams, SearchResult, PageResultsMap } from '..'
/**
* @param resultEntries Map entries (2-el KVP arrays) of URL keys to latest times
* @return Sorted and trimmed version of `resultEntries` input.
*/
export const paginate = (
resultEntries: SearchResult[] | PageResultsMap,
{ skip = 0, limit =... | .map(
([url, multi]): [string, number, number] => [
url,
Math.trunc(latestVisitsMap.get(url) * multi),
latestVisitsMap.get(url),
],
) | latestVisitsMap: PageResultsMap,
): SearchResult[] =>
[...urlScoreMap]
// Visits may be filtered down by time; only keep URLs appearing in visits Map
.filter(([url]) => latestVisitsMap.has(url)) | random_line_split |
typedefs_1.js | 32.h']]],
['gpr_5fcmdline',['gpr_cmdline',['../cmdline_8h.html#aaad93cd9bfc32c54fc89f7c2f3b74eb6',1,'cmdline.h']]],
['gpr_5fcv',['gpr_cv',['../sync__posix_8h.html#a1ad613e07180c0459cda9f3f6d881885',1,'gpr_cv(): sync_posix.h'],['../sync__win32_8h.html#a81241bed6e85e9b106a1311060a04d9d',1,'gpr_cv(): sync_wi... | ['gpr_5ftimespec',['gpr_timespec',['../time_8h.html#a7dd12c72fcf53ebecfdfc13632914c45',1,'time.h']]],
['gpr_5fuint16',['gpr_uint16',['../port__platform_8h.html#abb7bceac4325643af77af51c7b6af371',1,'port_platform.h']]],
['gpr_5fuint32',['gpr_uint32',['../port__platform_8h.html#aa6abd4df815a5498d1a04b5e691a74a9',1,... | ['gpr_5fslice_5frefcount',['gpr_slice_refcount',['../slice_8h.html#af8841873e741f6cf38b2192147ea4f3e',1,'slice.h']]],
['gpr_5fsubprocess',['gpr_subprocess',['../subprocess_8h.html#a1c3492c3aef738e6eef6b8cb1b435095',1,'subprocess.h']]],
['gpr_5fthd_5fid',['gpr_thd_id',['../thd_8h.html#a04194350e2fb18edc439ab0a9d35... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.